P. 1
JSF tutorial for RAD

JSF tutorial for RAD

|Views: 175|Likes:
Published by Naveen

More info:

Published by: Naveen on Mar 16, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

06/27/2011

pdf

text

original

Sections

  • Overview
  • Resources

Create Web-based user interfaces

Skill Level: Introductory

Ron Ben-Natan (rbennata@hotmail.com)
Freelance writer

19 May 2005

This tutorial demonstrates how to use JavaServer Faces (JSF) technology within IBM
Rational Application Developer Version 6.0. The tutorial walks you through a simple
application example that uses JSF technology to implement a simple messaging
center. Using Rational Application Developer, see how easy it is to build Web
applications that are based on JSF technology and how easy it is to support functions
relating to event handling, validation, and navigation using visual tools and
declarations rather than having to write long, tedious code.

Section 1. Before you start

About this tutorial

This tutorial is written for Web developers or Web site builders who want to quickly
learn how to use IBM® Rational® Application Developer Version 6.0 to build Web
applications that use JavaServer Faces (JSF) technology. This tutorial assumes a
basic knowledge of HTML and the Java™ language. However, because Rational
Application Developer is easy to use, you'll find the tutorial easy to follow even if
you're a beginner to HTML and the Java language.

JSF is an application framework for creating Web-based user interfaces (UIs). This
tutorial illustrates how to develop a Web application using JSF technology with a
focus on the visual tools provided for building Faces pages within Rational
Application Developer Version 6.0. It shows you how to use the JSF tags, how to
define validation within your Web forms, how to define navigation between the
different Web pages, and how to define what takes place when a button is clicked.
Finally, the tutorial shows you what happens behind the scenes, what JSF
constructs Rational Application Developer generates, and how all this works. While
you will learn the basics of JSF, you won't become an expert in JSF and its very
large feature set. For a great introduction to JSF, see the developerWorks tutorial, UI

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 1 of 46

development with JavaServer Faces, by Jackwind Li Guojie.

The tutorial uses a simple application -- the messaging center. Using the messaging
center, users can log in and view messages that have been sent to them. They can
also send messages to any other user that has access to the messaging center.
Because JSF technology brings visual graphical user interface (GUI) development to
Web applications, the focus is from the "outside-in" -- that is, starting with the pages,
then filling in the blanks. Therefore, you first design the pages, then assign values to
attributes belonging to components on your page and write only code that is not
generated on your behalf.

The messaging center application you create is not complete, because the purpose
of the tutorial is to show you how to use JSF within Rational Application Developer.
So, you won't spend any extra time making the application complete unless it
teaches you something about JSF.

The tutorial takes you through the entire development and packaging lifecycle. You
will:

• Create a JSF project and your first JSF page for allowing users to log into
the messaging center.

• Learn how to use the palette and the Attributes Editor to design pages.

• Learn about user interface (UI) components, validation, error handling,
and navigation.

• Learn all about Backing Beans, which are classes that Rational
Application Developer generates in support of UI components. You will
put your event-handling code inside this bean.

• Learn about Managed Beans and models and see how to manage data
that needs to be shared among all pages. You will also see how to use
the JSF Expressions Language (JSF EL) to bind components to data.

• Build the inbox page and use a fairly complex data grid component.

• Finish building the application, test it, package it an as Enterprise Archive
(EAR), and learn how to install it on a computer running IBM
WebSphere® Application Server.

Prerequisites

If you are a complete newbie to the Java programming language, some of these
concepts might be easier to follow if you have a basic understanding of servlets and
JavaServer Pages (JSP) technology. See Resources for some links on these topics.
Otherwise, while this tutorial does not aim to be a complete overview of JSF, it does
give you a pretty good overview of the main features. For more information on JSF,
see Resources for some excellent tutorials and sources.

To run the examples in this tutorial, you need Rational Application Developer

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 2 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

Version 6.0. You can download the latest trial version of Rational Application
Developer Version 6.0 at no charge.

Section 2. JSF basics

Overview

JSF is a component-based framework that brings advanced UI development
methods to the world of Java-based Web applications. If you're familiar with
Microsoft® .NET technologies, think of JSF as the equivalent to the WebForms
technology. By using JSF, you can easily create Web applications with complex UIs
using a minimal amount of effort. JSF includes two main modules: an API for
representing UI components and managing their state, and a JSP custom tag library
for making these UI components available in JSP pages.

Additional attributes that make JSF so powerful include:

• JSF gives you a set of standard and reusable server-side components
that support multiple rendering options. You use these components to
assemble pages and can later define how they are rendered. HTML
rendering is certainly the most common option, but in the same way that
some people render Swing components as Scalable Vector Graphics
(SVG) (for example, see the Batik project at apache.org), you might want
to render JSF components using other presentation capabilities in the
future.

• JSF encapsulates event handling, validation, and navigation in a way that
makes it declarative and very easy to use. The model follows the Swing
model with event handlers and listeners, meaning that if you are familiar
with this model (or other Model-View-Controller (MVC)-like models), you
will find JSF quite natural.

• JSF provides a framework and APIs for allowing you to create custom
components and extend existing ones. This topic is more advanced, and I
don't cover it in this tutorial. Refer to the Resources for more on custom
components in JSF.

• Finally, JSF allows tool vendors to manage JSF components within an
Integrated Development Environment (IDE) such as Rational Application
Developer. As you'll see, JSF components are placed on palettes and
have attribute editors.

JSF lifecycle

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 3 of 46

Note: You do not need to fully understand the description of the JSF lifecycle to get
the full value from this tutorial; it is provided here for curious readers.

JSF is typically used within Web applications and thus handles HTTP requests and
produces HTTP responses. The JSF run time manages a sequence of events known
as the JSF lifecycle. This lifecycle has seven phases, as shown in Figure 1. The
solid lines show normal flow of control, whereas the dashed lines show alternate
flows that are mostly used to handle errors:

Figure 1. The JSF lifecycle

The first thing that happens when a request comes in (as a result of a link or button
being clicked) is the reconstruction of the request tree. A JSF page is a tree of
components, and the JSF run time instantiates this tree for use by the other phases
of the lifecycle, including the wiring of event handlers (registered as listeners),
validators, and navigators. If the tree has already been constructed (perhaps
because this is a second request within the same page), the JSF run time restores
the application state information from the server.

When the components tree is restored, values from the request (typically from an
HTML form) are applied to the components in the tree. For example, input fields will
have values sent from the client, and these values need to be applied to the
component tree. Each component is responsible for extracting its values from the
request using various decode methods.

Events might be outstanding in the Handle Request Events phase, in which case the
JSF run time dispatches events to the listeners. A typical example of such event
handling occurs when an event handler has registered interest in value changes of a
value (typically through an input field).

Next comes the Process Validations phase. The JSF run time processes all
validations registered on the components of the tree. If values cause a validation
rule to fire, an error message is queued, and the run time progresses to the Render
Response phase, causing the page to be rendered again with error messages next
to the erroneous components.

Now that the JSF run time knows that the data are valid, it can update the values in

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 4 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

the model components. The run time will update the bean properties that the UI
component's attributes point at. If conversion errors occur, the run time redirects to
the Render Response phase, and the error messages are displayed on the page.

The run time then handles any application-level events, and all listeners are
activated based on all queued events. Finally, the run time invokes the component's
encoding functions and renders the component tree to produce the final HTML that
is sent to the client who made the original request.

This description might sound complex -- and it is. Luckily, you do not need to fully
understand all these intricacies to use JSF -- and certainly not if you plan on using
JSF from within Rational Application Developer Version 6.0. Still, it is always a good
idea to have a general idea of what is going on. If you would like to read more on the
JSF lifecycle, see Resources.

JSF components and the view tree

Each JSF page is a tree constructed of components; this tree is often called the JSF
view. Each component in turn has a list of child components, a set of attributes, one
or more validators, and one or more event handlers. A JSF component's attributes
store component-specific information such as the URL for an image component and
the text for a label component. Validators are used by the Process Validations
phase, and the event handlers are used by the Handle Request Events phase. JSF
components can either render themselves or delegate to an external renderer.

JSF component event handling can be managed directly by the component or by
delegating to event handlers that are registered with the component. This added
layer of flexibility allows you to build flexible UIs as well as build custom components
and custom event-handling code.

Now that you've gotten some theory under your belt, build a JSF application.

Section 3. Create the project and your first JSF page

The messaging center application

By following this tutorial, you'll build a very simple messaging center application. The
functionality of the messaging center is certainly nothing to write home about -- it is
merely aimed at showing you the JSF capabilities within Rational Application
Developer Version 6.0.

The messaging center will include a login page, an inbox page on which you can
view all the messages that were sent your way, and a page on which you can

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 5 of 46

compose and send messages to other users in the system. The application will
include three JSP pages with the navigation paths among them shown in Figure 2.

Figure 2. Navigation paths among three JSP pages

A user first logs into the messaging center by supplying a user name and a
password. To keep the underlying model simple (even trivial), use a static set of
users with hard-coded names. Validation should be kept simple and the focus on
exemplifying JSF features. Successful login moves users to their inbox, where they
can view their messages. In addition, they can click a button from the inbox to
compose a new message to send to other messaging center users.

Now that you understand what you need to build, let's see how it is done within
Rational Application Developer.

Create the project

Start Rational Application Developer, then open the Web perspective. In this section,
you will create the project and the first Faces JSP page.

JSF technology is used for building dynamic Web applications. Therefore, when
using JSF technology, your project needs to have the right underlying support. To
add a new Web project:

1. From the menu bar, click File > New > Dynamic Web Project to start the
New Dynamic Web Project wizard.

2. Enter MessagingCenter in the Name field, and then click Show
Advanced
to get the detailed panel shown in Figure 3.
Figure 3. New Dynamic Web Project wizard

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 6 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

3. The Web application will become a part of the MessagingCenterEAR
project created for you. The target server that you use to test the
application is the built-in WebSphere Application Server Version 6.0 test
environment. Click Next.

4. To add features to your Web project, in the Features window, select the
JSP Tag Libraries option, as shown in Figure 4. JSF is based on JSP,
and Faces pages are really JSP pages with additional tag libraries.
Therefore, it is always a good idea to have all that JSP has to offer at your
disposal.

Figure 4. The JSP Tag Libraries check box

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 7 of 46

5. Click Finish.

You now have a new Web project. Next, build the login page to the messaging
center.

Create the login page

To create the login page:

1. In the Project Navigator, right-click your MessagingCenter project, then
select New > Faces JSP File. Doing so starts the New Faces JSP File
wizard shown in Figure 5.

Figure 5. The New Faces JSP File wizard

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 8 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

2. Enter Login.jsp as the file name, and then click Finish.

Move on to designing this page.

Section 4. Design your page with JSF components

Overview

A JSF application runs in a Java Servlet container and contains JavaBeans
components, event listeners, JSP pages, and server-side helper classes. This setup
is common to other Java Web application frameworks. What makes a JSF

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 9 of 46

application special is that it has a large "infrastructure" on which you can rely and
prevents a lot of unnecessary coding. This infrastructure comes in the form of
libraries of components and includes:

• A tag library for rendering UI components on pages

• A tag library for event handling, validation, and conversions

• UI components that run on the server, manage application state, and
generate the HTML to be displayed

• Backing Beans, which work with the UI components and maintain
properties that the UI components use as well as process events on
behalf of the UI components

The tag libraries used when developing JSF applications represent UI components
and core actions such as validation and event handling. The component tag library
eliminates the need to hard-code UI components, and the core tag library makes it
easy to register events, validators, and other actions with the components. Some of
these tag libraries became part of your project when you chose to create a Faces
JSP Page; others became part of the project when you added the HTML JSF library
to the JSF page. After these libraries are available to you, you add components to
your page directly from the palette.

Using the palette

In the previous section, you created your Faces JSP page. The page starts out
empty, with a placeholder string telling you that you should start placing your
content.

Start by replacing the placeholder text with an instruction string telling the user that
this page allows him or her to log into the messaging center. Then add a description
for the user name field, as shown in Figure 6.

Figure 6. Replacing placeholder text with an instruction string

Now the fun begins. When you are in the Web perspective and are working in
Design mode, the right-most pane is the palette shown in Figure 7. In it you will find
many reusable components that you can drag onto your page. The components are
organized into categories -- with Faces Components being the open category given

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 10 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

that you are building a Faces JSP page. You need to add an input field to your page,
so click the Input entry in the palette.

Figure 7. The palette in the Design mode of the Web perspective

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 11 of 46

Now, click on your page just after the user name text to drop the component on the
page. Doing so creates the user name input field on your page. If you want to see
what Rational Application Developer did behind the scene, click the Source tab to
see the JSP code. As you can see, a new component named h:inputText was
added to the page. This tag is part of the JSF HTML tag library, as shown by the h
prefix -- a tag library that was automatically added to the page because you
requested to create a JSF page. At the top of the page, the tag library is included as:

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

Note that because the component you dropped on the page is an input field that can
only within a form, Rational Application Developer automatically added the form
component for you:

styleClass="form" id="form1">

Add a prompt for the password field, and then add the password input field. Select
the Input-Password element from the palette, and then click on the page.

In the next section, you set some of the component's properties and add validation.

Use the Properties/Attributes Editor to add validation

When you select a component on the page, the bottom middle pane shows the
Properties Editor (sometimes called the Attributes Editor), which allows you to
specify the component's attributes (see Figure 8).

Figure 8. The Properties editor

1. Select the user name input field.

2. Change the name in the Id field from the auto-generated ID to
usernameField. As you'll see later, these IDs are carried over to
Backing Beans, which are generated automatically on your behalf. Using
meaningful names for your components makes this code easier to read
and understand.

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 12 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

3. Click the Validation property. Because the whole purpose of JSF is to
package tasks that are very common when developing UIs, and because
validation is perhaps the most common task that any UI developer needs
to do, Rational Application Developer Version 6.0's JSF support includes
easy-to-use validation behaviors. In the Properties editor, you can simply
click and choose some of the most common validations. These validation
capabilities are based on pre-packaged validation components that exist
within JSF.

4. Because a user name is mandatory for logging into the messaging center,
select the Value is required check box in the Validation pane, as shown
in Figure 9.

Figure 9. Requiring a user name to log in

5. Assume (for demonstration purposes) that a user name can only have
alphabetic characters. Select Alphabetic characters only from the
Constraint drop-down list.

These validations occur before anything else does, so you won't have to check for
them in the code that is invoked when a user clicks the Login button.

Standard validation tags

Let's look at the generated JSP code for the login page. Click the Source tab.
Because you added validation to this field, Rational Application Developer added a
special attribute to the inputText element as well as an embedded tag defining a
regular expression constraining the input:

The JSF libraries have a set of standard validation attributes and tags. Each one of
these is added automatically when you set the appropriate attribute in the Validation
pane of the Properties editor. Table 1 lists some examples of the standard validation
attributes and tags and where to set them in the Properties editor.

Table 1. Standard validation attributes and tags with locations in the

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 13 of 46

Properties editor

Validator tag

Meaning

Properties/Attributes Editor

f:validate_required

Verifies that the value of the
component is not null

f:validate_length

Verifies that the length of a
component's value is within the
specified range

f:validate_longrange

Verifies that the value of a
component of type Number
(selected in the Format
drop-down list on the
h:inputText tab) is within the
specified range

In addition, conversion tags are added depending on the format of the input field. As
an example, if you change the format type to Date/Time, a tag by the name of
is added within the h:inputText (try it).

Finally, note that you can also define validation elements invoked (through
JavaScript) on the client side, eliminating additional server hits when the validation
can be performed on the client as well as the need to program tedious JavaScript
functions.

Displaying errors

Now that JSF will perform the validation for the user name field, specify where to
display the error message in case validation fails (for example, the field is left
empty). To do so:

1. In the Validation pane of the Properties editor, select the Display
validation error message in an error message control
option. Doing
so adds another JSF component to your page -- a component that is
responsible for displaying an error message if and when the validation
check fails. The component is placed next to the User name field, as
shown in Figure 10. The error component on the main pane is selected,
and the Properties editor is focused on the error message component.

Figure 10. Component for displaying an error message

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 14 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

2. Change the Id to a meaningful name (userNameErrors), and make sure
that the Id: drop-down list shows usernameField. If you look at the
Source tab, you can see that a h:message tag has been added to the
page:

styleClass="message"
id="userNameErrors" for="usernameField">

3. Do the same for the Password field. Select the Password field on the
page, and turn to the Properties editor.

4. Change the Id to passwordField.

5. Click the Validation pane, and select the Value is required check box.

6. Select the Display validation error message in an error message
control
check box to see the error message component added to your
page.

7. Click the error message component, then change the Id attribute in the
Properties editor to passwordErrors.

8. Make sure that the Id: drop-down list is set to passwordField.

9. Click the Save icon to save your work.

Another common task when building application UIs is defining navigation between
pages. Doing so involves specifying how the user causes navigation to take place
(the events upon which navigation occurs) and what the navigation path is. Here too,
Rational Application Developer JSF support makes this task easy. Let's move on to
adding a button and an action that is invoked when the button is clicked.

Section 5. Build navigation

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 15 of 46

Build a placeholder for a page to navigate to

In this section, you add a button to the login page. When the user clicks the button,
the application logs the user in and then navigates to a page where the user's
messages are displayed. Building this kind of functionality involves some additional
JSF components but little or no code that you need to write.

Before you can implement the navigation, build a page for displaying the user's
messages. You'll fill in the details of this page later (using JSF components), but at
this time, this page remains empty and simply functions as a placeholder so that you
can implement the navigation.

In the Project Navigator (the top left pane), right-click the MessagingCenter project,
then select New > Faces JSP File. Enter Inbox.jsp as the file name, then click
Finish. Now you have a new page to use as the target for navigation.

Add a command button

Go back to the Login.jsp page. Click the Command - Button entry within the
palette, and then click your Login.jsp page to drop the component onto the page.
Change the Id to loginButton. Click the Display Options tab in the Properties
Editor, and then set the Button label field to Login. Doing so adds the appropriate
label to the button. Your page should now look like Figure 11.

Figure 11. Labeling the button

If you click the Source tab and look at the tag that was added to your page
representing the command button component, it is of type hx:commandExButton.
This type is not part of the JSF core tag library (with an f prefix), nor is it part of the
JSF HTML tag library (with an h prefix). If you look at the top of the JSP source, the
hx references a tag library that is specific to Rational Application Developer Version
6.0:

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 16 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

<%@taglib
uri="http://www.ibm.com/jsf/html_extended" prefix="hx"%>

The components in the HX tag library are part of Rational Application Developer's
implementation of JSF rather than part of the JSF specification and follows one of
the main philosophies of JSF: to encourage extensions (new UI components) that
make developing easier.

Specify navigation

Now that you have a button, specify what happens when a user clicks it. Select the
button on the page, then click the hx:commandExButton pane. The right side of
the Properties editor includes the navigation rule table -- a table that allows you to
define a set of navigation rules. Each rule defines a string that represents a condition
and the page to navigate to. Your login page has two cases for navigation:
Successful login should cause the application to bring up the inbox page, and failed
login should stay on the login page to allow the user to re-enter a user name and
password.

Click Add Rule to bring up the Navigation Rule editor shown in Figure 12. Select
Inbox.jsp from the Page drop-down list, then enter success in the The outcome
named:
field.

Figure 12. The Navigation Rule Editor

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 17 of 46

Click OK. As you can see, doing so creates a navigation rule within the table. Add a
second navigation case by selecting Login.jsp from the Page drop-down list, then
entering failure as the Alias. The navigation rules look like Figure 13.

Figure 13. Navigation rules table

Navigation: Behind the scenes

In the previous section you entered two line items for navigation. Rational
Application Developer used these items to generate a navigation rule for your
application. As a JSF application, these rules are stored in the faces-config.xml file
that resides in the WEB-INF folder of your application. Let's see what this file and

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 18 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

navigation rule look like.

In the Project Navigator pane (the top left pane), open MessagingCenter >
WebContent > WEB-INF
. One of the configuration files in this folder is
faces-config.xml. Double-click this file to open it in the main pane. This file contains
the configuration definitions for your JSF application. Among these definitions are all
the navigation rules that you define for your application. Each navigation rule defines
how to get from one page to other pages of the application (specified in the
from-view-id element). Each rule defines a page for which the rule applies and a
set of navigation possibilities, each one a definition of a conditional outcome
(resulting from a method you will implement later) and the page to which navigation
should occur. In other words, a navigation rule contains a number of
navigation-case elements, each of which defines the page to open next based
on an outcome defined in the from-outcome element. Specifically, the rule that
was created for you specifies that it is relevant when the current page is Login.jsp
and that if the outcome is success, navigation should occur to Inbox.jsp, and if the
outcome is failure, navigation should occur to Login.jsp. The XML definition looks
like this:


/Login.jsp

success
/Inbox.jsp


failure
/Login.jsp

Note that the outcome entries are the string values that you entered into the
Properties editor. These strings are arbitrary, and you are free to choose any values
so long as you take care that they are the same values returned by the method
called when (in our case) the user clicks the button. Eventually, it is the
implementation of the method that determines what navigation should occur. And
while the returned strings truly are arbitrary, there are some conventions that most
JSF developers adhere to and that make your code more readable. Try to stick to
the following conventions listed in Table 2 when you build your navigation rules.

Table 2. Navigation rules and conventions

Returned string

Recommended meaning

success

Everything worked. Go to the next page.

failure

Something is wrong. Go to an error page.

login

The user needs to log in. Go to the login page.

no result

A search did not find anything. Go to the search
page again.

Event handling in a Backing Bean

Although you've defined a navigation rule, you still need to define when the

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 19 of 46

navigation rule needs to be activated and how to compute the value, which will be
checked to determine which of the two parts of the navigation rule applies. This
process needs to occur when the user clicks the Login button. The way this is done
in JSF is by an event handler in the Backing Bean.

Behind every Faces JSP page that includes a form is a Java class created for you
called the Backing Bean. The Backing Bean defines properties that can hold the
data or instances of the components on the page. It also includes methods that
perform certain functions associated with components on the page, including
validation, event handling, and navigation processing. For example, if you open the
MessagingCenter > Java Resources > Java Sources > pagecode package in the
Project Navigator, you can see that a Java class has been created for each of your
JSF pages. If you double-click the Login.java class and look at the code, you can
see (among other things) that there is a variable for every UI component you put on
your page. (Incidentally -- the variable name is the value you entered in the Id
attribute. If you choose meaningful names, your code is that much more readable).
The Backing Bean defines all the custom behavior of your application -- the decision
on what navigation should occur being one such example.

Go back to the Login.jsp page and click Login. In the Properties editor, switch to the
QuickEdit view by clicking the button shown in Figure 14.

Figure 14. Button for switching to the QuickEdit view

You can also add this code by right-clicking the button and selecting Edit Events.
Doing so opens the QuickEdit tab next to the Properties editor. The left side shows
all possible events, including the command event (the one you're interested in right
now) as well as various HTML page JavaScript events for which you can add
JavaScript scripts directly into the page.

Add code to be invoked on the server

Let's go back to adding the code to be invoked on the server when you click Login.
Click the command event, then type in Java code on the right. Doing so
automatically adds a new method called doLoginButtonAction to the Login.java
Backing Bean. The JSF run time calls this method whenever the button is clicked
and should return a string that is then used to determine which part of the navigation
rule to choose. This is where it all comes together: The action method is where
you implement your custom code, but all the mechanics to make this happen are
automatic.

By default, the implementation is empty. Your responsibility is to implement this
method and return either the success or the failure string -- depending on the
values that exist in the User name and Password fields. Feel free to implement this
any way you like. Typically, this will involve a lookup in a database for the user name

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 20 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

and password as well as all sorts of additional validations. For purposes of this
tutorial, this code is unimportant, and you can implement a very primitive check as
follows (don't forget to add an import java.util.ArrayList or use QuickFix):

// VERY primitive and static way to maintain authorized users
// For demonstration purposes ONLY
private static ArrayList allUsers() {
ArrayList userList = new ArrayList(4);
userList.add("Joe");
userList.add("Jane");
userList.add("Jack");
userList.add("Julie");
return userList;

}

When this method exists within Login.java, add the following code into the QuickEdit
view for the command event:

// Primitive implementation -- just check if the user is among the
// static list; normally would also check password and use a real
// repository for looking up user/password information
if (allUsers().contains((String)usernameField.getValue()))
return "success";
else return "failure";

Click Save.

If you look back to Login.java, you will see the method that handles the command
event:

public String doLoginButtonAction() {
// Primitive implementation -- just check if the user is among the
// static list; normally would also check password and use a real
// repository for looking up user/password information
if (allUsers().contains((String)usernameField.getValue()))
return "success";
else return "failure";

}

You've now completed your login page and have sampled the JSF support features
within Rational Application Developer Version 6.0 (including validation and event
handling). Let's move on to building the other pages in your application to see how
you can pass data between pages and their Backing Beans.

Section 6. Use Managed Beans to share data

Overview

Until now, the Inbox.jsp file has been only a placeholder. Let's design the page and
build the code behind it. In the process, you'll learn more about Managed Beans,
and you'll build a Managed Bean that acts as a model.

Like all modern UI frameworks, JSF is built on an MVC paradigm -- although it does
hide much of the complexity from you (for example, if you have used Struts before,

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 21 of 46

you will appreciate the simplicity behind JSF). You've been using Backing Beans as
classes that "sit behind" the page. These classes should be viewed as an extension
to the page (or the view): They do not represent the application data (the model). As
a result, each Backing Bean is useful primarily within the context of a single page
and is not useful in passing data from one page to another. Therefore, if you want to
pass the user name of the user who just logged in to the Inbox.jsp page, the Backing
Bean is not the way to do it. Instead, you should build a class that serves as the
model, and this class should then be used by both pages.

Let's build a model class and then modify the pages to use it.

Build a model

First, build a simple class that maintains the user information. Later, you'll use this
class as the main data repository, but for now it only maintains the user name. The
class you'll build will be named User and it will be in a package called model.

1. Right-click MessagingCenter > New > Class to launch the New Class
wizard. Enter model as the package name and User as the class name.
The class needs to be a JavaBean and should have accessor methods
for each data element, but otherwise it is a simple class inheriting from
Object.

2. Click Finish.

3. Add the following code to the class:

// simple model class representing a user object
public class User {

private String _userName;

public String getUserName() {
return _userName;

}

public void setUserName(String s) {
_userName = s;

}

}

4. Save the class definition.

Add a Managed Bean entry

The next step is to tell the JSF run time that it needs to manage User as a Managed
Bean. The same data need to be available across different pages in the application,
but different browser sessions can be open for different users. Therefore, define that
this Managed Bean has a session context. Doing so allows multiple pages to access
the same user object.

To add a Managed Bean:

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 22 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

1. Turn to the Page Data tab, which is the lower left pane in the Web
perspective.

2. Expand Scripting Variables, right-click sessionScope, and then select
New > JavaBean, as shown in Figure 15.
Figure 15. Adding a Managed Bean

3. Select the Add new JavaBean option, then enter user as the name of
the bean.

4. Enter model.User as the class, and select the Make this JavaBean
reusable (Make this JavaBean a JSF ManagedBean)
check box.

5. Enter a description for the bean, and select session from the Scope
drop-down list, as shown in Figure 16.

Figure 16. Adding a new JavaBean

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 23 of 46

6. Click Initialize Properties. Right-click the table, and then select Add to
add an empty line.

7. Select the line, then enter userName as the name, Enter user name
as the (initial) value, and java.lang.String as the data type, as
shown in Figure 17.

Figure 17. Add properties for the bean

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 24 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

8. Recall that Managed Beans are defined in the faces-config.xml file
located in the MessagingCenter > WebContent > WEB-INF folder.
Double-click this file to open it in the central pane, then click the Source
tab. Notice that Rational Application Developer added the Managed Bean
as shown below:


Maintain the user object as a JSF managed bean

user
model.User
session

userName
java.lang.String
Enter user name

In this definition, you are telling the JSF run time the following things:

• A new Managed Bean should be created.

• It will be referenced within the JSF application (for example, from pages)
by the named user.

• It is implemented as an instance of the class model.User.

• It has a session scope.

• Its starting value is Enter user name.

Now that the JSF run time knows all these things and is managing the instance for
you, let's see how to use it within your pages.

Using the Managed Model Bean

Go back to page editing and change the pages to use the shared data model. Start
with the Inbox.jsp page. Open the JSP in Design mode, and replace Place content

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 25 of 46

here with Welcome to your inbox. Make this page a little more user-friendly by
adding the user name -- after all, this screen comes up after the user has logged in.
To change this page:

1. Click the Output component on the palette, as shown in Figure 18.
Figure 18. The Output component on the palette

2. Click the page to drop the component. Go to the Properties editor and
change the ID to welcomeUserName.

3. Expand Scripting Variables in the bottom left pane. Right-click it, then
select sessionScope > New > JavaBean.

4. In the Add JavaBean window, select the Add existing reusable
Javabean (JSF ManagedBean)
option, then select the user bean. Click
Finish to add the bean to the page; you will see this new entry in the
bottom left pane as shown in Figure 19.

Figure 19. The new bean on the page

In the Properties editor for the output text, click the icon to the right of the
Value field. Doing so allows you to select the appropriate property, as
shown in Figure 20.

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 26 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

Figure 20. Selecting the expression for the Value field

You are telling the JSF run time that the value of the component is based
on a Managed Bean named user, and the value is accessed/stored
using default accessor methods getUserName and setUserName.

(The syntax used above is JSF EL, and it is part of the JSF specification
(see Resources for a link).

5. Because the value of the User bean needs to be populated by the
Login.jsp page, you also need to change the binding there. Open
Login.jsp in Design mode, then click the User name input field. Modify the
binding attribute in the Properties editor by clicking the icon to the right of
the Value field and selecting the property, as shown in Figure 21.

Figure 21. Modifying the binding attribute in the Properties editor

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 27 of 46

The doLoginButtonAction method

The last modification to make is in the doLoginButtonAction method in
Login.java. Make sure that the value extracted for validating the user name matches
the way the component is bound to the model. Change the method to look as follows
to make sure you are extracting the value that the run time is assigning to the
component from the Managed Bean:

public String doLoginButtonAction() {
// Type Java code to handle command event here
// Note, this code must return an object of type String (or null)
// Primitive implementation -- just check if the user is among the
// static list; normally would also check password and use a real
// repository for looking up user/password information

String userName = (String)getUsernameField().getValue();
if (allUsers().contains(userName))
return "success";
else return "failure";

}

The two pages now use a common data model. If you run the application by
right-clicking the Login.jsp page in the Project Navigator and selecting Run > Run
on server
(more instructions in the Overview), you should be able to log in (for

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 28 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

example, as Jane) as shown in Figure 22.

Figure 22. Running the application

The inbox page opens with the appropriate welcome message, as shown in Figure
23.

Figure 23. Inbox page with welcome message

Click the Save icon to save your work.

Let's move on to finish building our simple messaging center and use some
additional components in the process.

Section 7. Complete the application pages

Overview

In this section, you finish building the Inbox.jsp page and build the Compose.jsp
page. Because many of the concepts here have been covered in the previous
sections, the build process is a little faster.

Build the back-end model for the lists of messages. Keep it very simple and
implement a static hash map in which the key is the user name and the value is a list

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 29 of 46

of messages. Each message is a simple class maintaining only the text and who the
message is from. To build the model:

1. To implement the message class, right-click the MessagingCenter folder
in the Project Navigator, then select New > Class.

2. Enter model as the package and Message as the class name. Click
Finish.

3. In the Properties editor, implement the class as follows:

// simple model class representing a message objects
public class Message {
private String _from;
private String _message;

public Message(String from, String message) {
_from = from;
_message = message;

}
public String getFrom() {
return _from;

}
public String getMessage() {
return _message;

}
public void setFrom(String from) {
from = from;

}
public void setMessage(String message) {
message = message;

}

}

4. Open the User.java class in the Properties editor. Add the following code
before the class:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

5. Add the following code implementing the hash map of message lists (one
per user):

private static HashMap _messageMap;

private static HashMap getMessageMap() {
// Lazy initialization of a map of messages
if (_messageMap == null)
_messageMap = new HashMap(10);

return _messageMap;

}

public List getUserMessages(String userName) {
// Returns the messages for a user.
// Two default welcome messages are added for each new map
HashMap mmap = getMessageMap();
if (!mmap.containsKey(userName)) {
List mList = new ArrayList(10);
// For demonstration purposes - let's add two initial messages
// just so that we'll see them on the page
mList.add(new Message("System", "Welcome to the messaging center"));
mList.add(new Message("System", "You can ignore the previous message"));
mmap.put(userName, mList);

}
List userMessages = (List)mmap.get(userName);
return userMessages;

}

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 30 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

public List getUserMessages() {
// Return messages for the current user
return getUserMessages(getUserName());

}

Every user starts off with two messages supposedly sent by the system. The main
purpose of these messages is that when you build the message display on the inbox
page, you are able to verify that it works without having to send yourself a lot of
messages.

Let's build the inbox.

Using a data table

If you've been building Web applications using the Java programming language, you
will find this panel a pleasant surprise. With JSF, you can build quite complex tabular
displays without writing a single line of code.

1. Open the Inbox.jsp page in Design mode, then click the Data Table
component on the palette. (You might have to click the arrow, because
the palette contains many Faces components.)

2. Click the page to drop the component into it.

3. In the Properties Editor, change the ID to messageInbox, then set the
Value attribute by selecting the data object as shown in Figure 24.

Figure 24. Set the Value attribute for Inbox.jsp data table

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 31 of 46

You're telling the JSF run time that the data model for this component will
be retrieved by calling getUserMessages from the User bean.

4. Because this method returns a collection of objects, Rational Application
Developer needs more typing information. You need to tell it that each
element of the collection will be a message, as Figure 25 shows.

Figure 25. Typing information

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 32 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

5. Set the width attribute (the width of the data table) to 600 pixels.

6. Click the Display options tab. The data table component is quite elaborate
and supports features such as paging (that is, displaying partial contents).

7. Enter 3 in the Rows per page field (so that you don't have to send too
many messages to see it working), then click Add a simple pager. The
data table implementation has various types of pagers; you can
experiment with them to find the one you like the most.

8. Click the column within the data table (on the page itself).

9. Click on the Column1 output text, and then set the value to From: This is
the heading.

10. Click the column itself, and then change the ID to from. Drop an
outputText element from the palette into the column. In the Properties
editor, click the icon to the right of the Value field, then select the from
message, as shown in Figure 26.

Figure 26. Select the from message

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 33 of 46

11. Click the h:dataTable element in the Properties editor. To the right is a
table that shows the columns of the table. Click Add to add a second
column. Change Column 2 to Message as a label.

12. Click Add again and enter Message as a heading.

13. Select the right column on the page designer, then change the ID to
message.

14. Drop an outputText element in the second column.

15. Click the icon to the right of the Value field to select the page data object
for the second column, as shown in Figure 27.

Figure 27. Selecting page data object for the second column

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 34 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

If you run your application (see Run the messaging center within Rational
Application Developer) and log in as Jane, you see the window shown in Figure 28.

Figure 28. Re-running the application

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 35 of 46

Next, build the page used to compose new messages and link it to the inbox.

Build Compose.jsp

To create a new Faces JSP file:

1. Right-click MessagingCenter, then select New > Faces JSP File.

2. Enter Compose.jsp in the File Name field, then click Finish. Rational
Application Developer Version 6.0 creates the Faces JSP file.

3. You should now be looking at the JSP page in the designer. Replace the
default Place content here text with Send message to.

4. Click the Input component on the palette, then click the page to drop the
component.

5. In the Properties Editor, on the h:inputText tab, change the ID to
receiver.

6. Click the Validation pane, then click the Value is required check box (the
receiver is a mandatory field).

7. Select the Display validation error messages in an error message
control
check box to place an error message next to the field. This adds
an h:message component.

8. In the Properties Editor, change its ID to receiverError. The resulting
JSP page thus far should look like Figure 29.

Figure 29. The JSP page so far

9. On the page, add Message Text:, and then click the Input component
on the palette to add the field for the message text.

10. Click the page to drop the component. In the Properties Editor in the
h:inputText tab, change the ID to messageText and change the Width
field to 400. No validation is required: The message text can be empty.

What is missing on the compose page are the action buttons, which you add in the
next panel.

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 36 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

Add command buttons to Compose.jsp

Add two buttons: one for sending the message and one for canceling the message.
In either case, navigation should occur back to the inbox, but in the first case, a new
message needs to be generated and added to the receiver's list.

1. Click the Command-Button entry in the palette, and drop it on the
Compose.jsp page.

2. In the Properties Editor, change the ID to sendButton. In the Display
options pane, change Button label to Send.

3. Click the hx:commandExButton pane, and then click Add Rule to add a
new navigation rule.

4. Select Inbox.jsp as the Page and success as The outcome named.

5. Click OK.

6. Add the Cancel button. Click the Command-Button entry in the palette,
and drop it on the Compose.jsp page.

7. In the Properties Editor, change the ID to cancelButton. On the Format
tab, change Button label to Cancel.

You don't need to add another navigation rule, because navigation rules are per-
originating-page. The various line items in a navigation rule specify a condition and
the target of the navigation. Because both buttons "live" on the same page, they
must share the navigation rule. In this case, both buttons behave in the same way:
Upon success (which can mean a different thing for different buttons), navigation
occurs to Inbox.jsp. More specifically, if you look at the navigation rule in
faces-config.xml, this becomes clearer:

/Compose.jsp

success
/Inbox.jsp

You still need to write the code that is activated when each button is clicked.

Handling the command events

Now, write the code to be invoked when the buttons are clicked (and you must
remember to return the success string to cause navigation to occur).

1. On the designer, right-click the Cancel button, then select Edit Events.

ibm.com/developerWorks

developerWorks®

Create Web-based user interfaces
© Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 37 of 46

2. Click Command on the left pane of the Properties editor and enter the
handler for the Cancel button.

3. The Cancel button is very easy to implement. You really don't need to do
anything, because you're just going back to the inbox without saving
anything. The following code is therefore enough. One small issue not
addressed is that if you cancel, no validation should occur. But that isn't
very important for purposes of this tutorial.

public String doCancelButtonAction() {
// Do nothing - always navigate back to the inbox
return "success";

}

4. Add a utility method to User.java in the model package. This method
creates a new message for the receiver and looks as follows (add it to
User.java and save that file):

public void addMessage(String receiver, String text) {
// get the user's message map and add the new message
getUserMessages(receiver).add(new Message(getUserName(), text));

}

5. In the designer, right-click the Send button, then select Edit Events.

6. Click Command in the left pane, and implement the handler by first
getting the User Managed Bean. You can access this object through the
FacesContext by looking up the object using its name, using the utility
method you just added, and returning success. The code for this method
is:

model.User currentModel =

(model.User)getFacesContext().getApplication().
getVariableResolver().resolveVariable(getFacesContext(), "user");

currentModel.addMessage(

(String)getReceiver().getValue(),
(String)getMessageText().getValue());

return "success";

}

7. You're almost done. The only thing left is getting to the compose page
from the Inbox page. You can easily do this navigation with a command
button, but all you really need is a simple hyperlink. Select Inbox.jsp, and
then click the Link component on the palette (not the Command -
Hyperlink).

8. Click the Inbox.jsp page to drop it on the page. In the window, enter
Compose.jsp as the URL and the label Compose a new message.

9. Click OK, then save the page.

Believe it or not, you're done! (With developing, that is.) Click the Save icon to save
your work and go to the next section for testing and packaging.

developerWorks®

ibm.com/developerWorks

Create Web-based user interfaces
Page 38 of 46

© Copyright IBM Corporation 1994, 2006. All rights reserved.

Section 8. Test, package, and install your application

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->