jsf tutorial for rad

46
Create Web-based user interfaces Skill Level: Introductory Ron Ben-Natan ([email protected]) 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

Upload: api-3819398

Post on 14-Nov-2014

18 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: JSF Tutorial for RAD

Create Web-based user interfacesSkill Level: Introductory

Ron Ben-Natan ([email protected])Freelance writer

19 May 2005

This tutorial demonstrates how to use JavaServer Faces (JSF) technology within IBMRational Application Developer Version 6.0. The tutorial walks you through a simpleapplication example that uses JSF technology to implement a simple messagingcenter. Using Rational Application Developer, see how easy it is to build Webapplications that are based on JSF technology and how easy it is to support functionsrelating to event handling, validation, and navigation using visual tools anddeclarations 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 quicklylearn how to use IBM® Rational® Application Developer Version 6.0 to build Webapplications that use JavaServer Faces (JSF) technology. This tutorial assumes abasic knowledge of HTML and the Java™ language. However, because RationalApplication Developer is easy to use, you'll find the tutorial easy to follow even ifyou're a beginner to HTML and the Java language.

JSF is an application framework for creating Web-based user interfaces (UIs). Thistutorial illustrates how to develop a Web application using JSF technology with afocus on the visual tools provided for building Faces pages within RationalApplication Developer Version 6.0. It shows you how to use the JSF tags, how todefine validation within your Web forms, how to define navigation between thedifferent 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 JSFconstructs Rational Application Developer generates, and how all this works. Whileyou will learn the basics of JSF, you won't become an expert in JSF and its verylarge 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

Page 2: JSF Tutorial for RAD

development with JavaServer Faces, by Jackwind Li Guojie.

The tutorial uses a simple application -- the messaging center. Using the messagingcenter, users can log in and view messages that have been sent to them. They canalso send messages to any other user that has access to the messaging center.Because JSF technology brings visual graphical user interface (GUI) development toWeb 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 toattributes belonging to components on your page and write only code that is notgenerated on your behalf.

The messaging center application you create is not complete, because the purposeof 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 itteaches you something about JSF.

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

• Create a JSF project and your first JSF page for allowing users to log intothe 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 RationalApplication Developer generates in support of UI components. You willput your event-handling code inside this bean.

• Learn about Managed Beans and models and see how to manage datathat needs to be shared among all pages. You will also see how to usethe 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 IBMWebSphere® Application Server.

Prerequisites

If you are a complete newbie to the Java programming language, some of theseconcepts might be easier to follow if you have a basic understanding of servlets andJavaServer 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 doesgive 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 interfacesPage 2 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 3: JSF Tutorial for RAD

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

Section 2. JSF basics

Overview

JSF is a component-based framework that brings advanced UI developmentmethods to the world of Java-based Web applications. If you're familiar withMicrosoft® .NET technologies, think of JSF as the equivalent to the WebFormstechnology. By using JSF, you can easily create Web applications with complex UIsusing a minimal amount of effort. JSF includes two main modules: an API forrepresenting UI components and managing their state, and a JSP custom tag libraryfor 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 componentsthat support multiple rendering options. You use these components toassemble pages and can later define how they are rendered. HTMLrendering is certainly the most common option, but in the same way thatsome people render Swing components as Scalable Vector Graphics(SVG) (for example, see the Batik project at apache.org), you might wantto render JSF components using other presentation capabilities in thefuture.

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

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

• Finally, JSF allows tool vendors to manage JSF components within anIntegrated Development Environment (IDE) such as Rational ApplicationDeveloper. As you'll see, JSF components are placed on palettes andhave 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

Page 4: JSF Tutorial for RAD

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

JSF is typically used within Web applications and thus handles HTTP requests andproduces HTTP responses. The JSF run time manages a sequence of events knownas the JSF lifecycle. This lifecycle has seven phases, as shown in Figure 1. Thesolid lines show normal flow of control, whereas the dashed lines show alternateflows 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 buttonbeing clicked) is the reconstruction of the request tree. A JSF page is a tree ofcomponents, and the JSF run time instantiates this tree for use by the other phasesof the lifecycle, including the wiring of event handlers (registered as listeners),validators, and navigators. If the tree has already been constructed (perhapsbecause this is a second request within the same page), the JSF run time restoresthe application state information from the server.

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

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

Next comes the Process Validations phase. The JSF run time processes allvalidations registered on the components of the tree. If values cause a validationrule to fire, an error message is queued, and the run time progresses to the RenderResponse phase, causing the page to be rendered again with error messages nextto 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 interfacesPage 4 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 5: JSF Tutorial for RAD

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

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

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

JSF components and the view tree

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

JSF component event handling can be managed directly by the component or bydelegating to event handlers that are registered with the component. This addedlayer of flexibility allows you to build flexible UIs as well as build custom componentsand 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. Thefunctionality of the messaging center is certainly nothing to write home about -- it ismerely aimed at showing you the JSF capabilities within Rational ApplicationDeveloper Version 6.0.

The messaging center will include a login page, an inbox page on which you canview 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

Page 6: JSF Tutorial for RAD

compose and send messages to other users in the system. The application willinclude 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 apassword. To keep the underlying model simple (even trivial), use a static set ofusers with hard-coded names. Validation should be kept simple and the focus onexemplifying JSF features. Successful login moves users to their inbox, where theycan view their messages. In addition, they can click a button from the inbox tocompose 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 withinRational 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, whenusing JSF technology, your project needs to have the right underlying support. Toadd a new Web project:

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

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

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 6 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 7: JSF Tutorial for RAD

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

4. To add features to your Web project, in the Features window, select theJSP 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 yourdisposal.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

Page 8: JSF Tutorial for RAD

5. Click Finish.

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

Create the login page

To create the login page:

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

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 8 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 9: JSF Tutorial for RAD

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 JavaBeanscomponents, event listeners, JSP pages, and server-side helper classes. This setupis 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

Page 10: JSF Tutorial for RAD

application special is that it has a large "infrastructure" on which you can rely andprevents a lot of unnecessary coding. This infrastructure comes in the form oflibraries 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, andgenerate the HTML to be displayed

• Backing Beans, which work with the UI components and maintainproperties that the UI components use as well as process events onbehalf of the UI components

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

Using the palette

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

Start by replacing the placeholder text with an instruction string telling the user thatthis page allows him or her to log into the messaging center. Then add a descriptionfor 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 inDesign mode, the right-most pane is the palette shown in Figure 7. In it you will findmany reusable components that you can drag onto your page. The components areorganized into categories -- with Faces Components being the open category given

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 10 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 11: JSF Tutorial for RAD

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

Page 12: JSF Tutorial for RAD

Now, click on your page just after the user name text to drop the component on thepage. Doing so creates the user name input field on your page. If you want to seewhat Rational Application Developer did behind the scene, click the Source tab tosee the JSP code. As you can see, a new component named h:inputText wasadded to the page. This tag is part of the JSF HTML tag library, as shown by the hprefix -- a tag library that was automatically added to the page because yourequested 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 canonly within a form, Rational Application Developer automatically added the formcomponent for you:<h:formstyleClass="form" id="form1">

Add a prompt for the password field, and then add the password input field. Selectthe 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 theProperties Editor (sometimes called the Attributes Editor), which allows you tospecify 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 tousernameField. As you'll see later, these IDs are carried over toBacking Beans, which are generated automatically on your behalf. Usingmeaningful names for your components makes this code easier to readand understand.

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 12 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 13: JSF Tutorial for RAD

3. Click the Validation property. Because the whole purpose of JSF is topackage tasks that are very common when developing UIs, and becausevalidation is perhaps the most common task that any UI developer needsto do, Rational Application Developer Version 6.0's JSF support includeseasy-to-use validation behaviors. In the Properties editor, you can simplyclick and choose some of the most common validations. These validationcapabilities are based on pre-packaged validation components that existwithin 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 shownin Figure 9.Figure 9. Requiring a user name to log in

5. Assume (for demonstration purposes) that a user name can only havealphabetic characters. Select Alphabetic characters only from theConstraint drop-down list.

These validations occur before anything else does, so you won't have to check forthem 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 aspecial attribute to the inputText element as well as an embedded tag defining aregular expression constraining the input:<h:inputText styleClass="inputText" id="usernameField" required="true"><hx:validateConstraint regex="AlphabetOnly" />

</h:inputText>

The JSF libraries have a set of standard validation attributes and tags. Each one ofthese is added automatically when you set the appropriate attribute in the Validationpane of the Properties editor. Table 1 lists some examples of the standard validationattributes 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

Page 14: JSF Tutorial for RAD

Properties editor

Validator tag Meaning Properties/Attributes Editor

f:validate_required Verifies that the value of thecomponent is not null

f:validate_length Verifies that the length of acomponent's value is within thespecified range

f:validate_longrange Verifies that the value of acomponent of type Number(selected in the Formatdrop-down list on theh:inputText tab) is within thespecified range

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

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

Displaying errors

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

1. In the Validation pane of the Properties editor, select the Displayvalidation error message in an error message control option. Doingso adds another JSF component to your page -- a component that isresponsible for displaying an error message if and when the validationcheck fails. The component is placed next to the User name field, asshown 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 interfacesPage 14 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 15: JSF Tutorial for RAD

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

styleClass="message"id="userNameErrors" for="usernameField"></h:message>

3. Do the same for the Password field. Select the Password field on thepage, 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 messagecontrol check box to see the error message component added to yourpage.

7. Click the error message component, then change the Id attribute in theProperties 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 betweenpages. 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 toadding 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

Page 16: JSF Tutorial for RAD

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'smessages are displayed. Building this kind of functionality involves some additionalJSF components but little or no code that you need to write.

Before you can implement the navigation, build a page for displaying the user'smessages. You'll fill in the details of this page later (using JSF components), but atthis time, this page remains empty and simply functions as a placeholder so that youcan 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 clickFinish. 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 thepalette, 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 PropertiesEditor, and then set the Button label field to Login. Doing so adds the appropriatelabel 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 pagerepresenting 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 theJSF HTML tag library (with an h prefix). If you look at the top of the JSP source, thehx references a tag library that is specific to Rational Application Developer Version6.0:

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 16 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 17: JSF Tutorial for RAD

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

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

Specify navigation

Now that you have a button, specify what happens when a user clicks it. Select thebutton on the page, then click the hx:commandExButton pane. The right side ofthe Properties editor includes the navigation rule table -- a table that allows you todefine a set of navigation rules. Each rule defines a string that represents a conditionand 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 failedlogin should stay on the login page to allow the user to re-enter a user name andpassword.

Click Add Rule to bring up the Navigation Rule editor shown in Figure 12. SelectInbox.jsp from the Page drop-down list, then enter success in the The outcomenamed: 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

Page 18: JSF Tutorial for RAD

Click OK. As you can see, doing so creates a navigation rule within the table. Add asecond navigation case by selecting Login.jsp from the Page drop-down list, thenentering 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. RationalApplication Developer used these items to generate a navigation rule for yourapplication. As a JSF application, these rules are stored in the faces-config.xml filethat resides in the WEB-INF folder of your application. Let's see what this file and

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 18 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 19: JSF Tutorial for RAD

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 isfaces-config.xml. Double-click this file to open it in the main pane. This file containsthe configuration definitions for your JSF application. Among these definitions are allthe navigation rules that you define for your application. Each navigation rule defineshow to get from one page to other pages of the application (specified in thefrom-view-id element). Each rule defines a page for which the rule applies and aset of navigation possibilities, each one a definition of a conditional outcome(resulting from a method you will implement later) and the page to which navigationshould occur. In other words, a navigation rule contains a number ofnavigation-case elements, each of which defines the page to open next basedon an outcome defined in the from-outcome element. Specifically, the rule thatwas created for you specifies that it is relevant when the current page is Login.jspand that if the outcome is success, navigation should occur to Inbox.jsp, and if theoutcome is failure, navigation should occur to Login.jsp. The XML definition lookslike this:<navigation-rule><from-view-id>/Login.jsp</from-view-id><navigation-case>

<from-outcome>success</from-outcome><to-view-id>/Inbox.jsp</to-view-id>

</navigation-case><navigation-case>

<from-outcome>failure</from-outcome><to-view-id>/Login.jsp</to-view-id>

</navigation-case></navigation-rule>

Note that the outcome entries are the string values that you entered into theProperties editor. These strings are arbitrary, and you are free to choose any valuesso long as you take care that they are the same values returned by the methodcalled when (in our case) the user clicks the button. Eventually, it is theimplementation of the method that determines what navigation should occur. Andwhile the returned strings truly are arbitrary, there are some conventions that mostJSF developers adhere to and that make your code more readable. Try to stick tothe 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 searchpage 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

Page 20: JSF Tutorial for RAD

navigation rule needs to be activated and how to compute the value, which will bechecked to determine which of the two parts of the navigation rule applies. Thisprocess needs to occur when the user clicks the Login button. The way this is donein 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 youcalled the Backing Bean. The Backing Bean defines properties that can hold thedata or instances of the components on the page. It also includes methods thatperform certain functions associated with components on the page, includingvalidation, event handling, and navigation processing. For example, if you open theMessagingCenter > Java Resources > Java Sources > pagecode package in theProject Navigator, you can see that a Java class has been created for each of yourJSF pages. If you double-click the Login.java class and look at the code, you cansee (among other things) that there is a variable for every UI component you put onyour page. (Incidentally -- the variable name is the value you entered in the Idattribute. If you choose meaningful names, your code is that much more readable).The Backing Bean defines all the custom behavior of your application -- the decisionon what navigation should occur being one such example.

Go back to the Login.jsp page and click Login. In the Properties editor, switch to theQuickEdit 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 showsall possible events, including the command event (the one you're interested in rightnow) as well as various HTML page JavaScript events for which you can addJavaScript 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 soautomatically adds a new method called doLoginButtonAction to the Login.javaBacking Bean. The JSF run time calls this method whenever the button is clickedand should return a string that is then used to determine which part of the navigationrule to choose. This is where it all comes together: The action method is whereyou implement your custom code, but all the mechanics to make this happen areautomatic.

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

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 20 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 21: JSF Tutorial for RAD

and password as well as all sorts of additional validations. For purposes of thistutorial, this code is unimportant, and you can implement a very primitive check asfollows (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 ONLYprivate 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 QuickEditview 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 informationif (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 commandevent: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 informationif (allUsers().contains((String)usernameField.getValue()))

return "success";else return "failure";}

You've now completed your login page and have sampled the JSF support featureswithin Rational Application Developer Version 6.0 (including validation and eventhandling). Let's move on to building the other pages in your application to see howyou 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 andbuild 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 doeshide 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

Page 22: JSF Tutorial for RAD

you will appreciate the simplicity behind JSF). You've been using Backing Beans asclasses that "sit behind" the page. These classes should be viewed as an extensionto the page (or the view): They do not represent the application data (the model). Asa result, each Backing Bean is useful primarily within the context of a single pageand is not useful in passing data from one page to another. Therefore, if you want topass the user name of the user who just logged in to the Inbox.jsp page, the BackingBean is not the way to do it. Instead, you should build a class that serves as themodel, 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 thisclass as the main data repository, but for now it only maintains the user name. Theclass 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 Classwizard. Enter model as the package name and User as the class name.The class needs to be a JavaBean and should have accessor methodsfor each data element, but otherwise it is a simple class inheriting fromObject.

2. Click Finish.

3. Add the following code to the class:// simple model class representing a user objectpublic 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 ManagedBean. 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 thatthis Managed Bean has a session context. Doing so allows multiple pages to accessthe same user object.

To add a Managed Bean:

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 22 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 23: JSF Tutorial for RAD

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

2. Expand Scripting Variables, right-click sessionScope, and then selectNew > 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 ofthe bean.

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

5. Enter a description for the bean, and select session from the Scopedrop-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

Page 24: JSF Tutorial for RAD

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

7. Select the line, then enter userName as the name, Enter user nameas the (initial) value, and java.lang.String as the data type, asshown in Figure 17.Figure 17. Add properties for the bean

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 24 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 25: JSF Tutorial for RAD

8. Recall that Managed Beans are defined in the faces-config.xml filelocated in the MessagingCenter > WebContent > WEB-INF folder.Double-click this file to open it in the central pane, then click the Sourcetab. Notice that Rational Application Developer added the Managed Beanas shown below:<managed-bean>

<description>Maintain the user object as a JSF managed bean</description><managed-bean-name>user</managed-bean-name><managed-bean-class>model.User</managed-bean-class><managed-bean-scope>session</managed-bean-scope><managed-property>

<property-name>userName</property-name><property-class>java.lang.String</property-class><value>Enter user name</value>

</managed-property></managed-bean>

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 foryou, 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. Startwith 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

Page 26: JSF Tutorial for RAD

here with Welcome to your inbox. Make this page a little more user-friendly byadding 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 andchange the ID to welcomeUserName.

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

4. In the Add JavaBean window, select the Add existing reusableJavabean (JSF ManagedBean) option, then select the user bean. ClickFinish to add the bean to the page; you will see this new entry in thebottom 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 theValue field. Doing so allows you to select the appropriate property, asshown in Figure 20.

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 26 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 27: JSF Tutorial for RAD

Figure 20. Selecting the expression for the Value field

You are telling the JSF run time that the value of the component is basedon a Managed Bean named user, and the value is accessed/storedusing 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 theLogin.jsp page, you also need to change the binding there. OpenLogin.jsp in Design mode, then click the User name input field. Modify thebinding attribute in the Properties editor by clicking the icon to the right ofthe 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

Page 28: JSF Tutorial for RAD

The doLoginButtonAction method

The last modification to make is in the doLoginButtonAction method inLogin.java. Make sure that the value extracted for validating the user name matchesthe way the component is bound to the model. Change the method to look as followsto make sure you are extracting the value that the run time is assigning to thecomponent 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 byright-clicking the Login.jsp page in the Project Navigator and selecting Run > Runon server (more instructions in the Overview), you should be able to log in (for

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 28 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 29: JSF Tutorial for RAD

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 Figure23.

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 someadditional 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.jsppage. Because many of the concepts here have been covered in the previoussections, the build process is a little faster.

Build the back-end model for the lists of messages. Keep it very simple andimplement 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

Page 30: JSF Tutorial for RAD

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

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

2. Enter model as the package and Message as the class name. ClickFinish.

3. In the Properties editor, implement the class as follows:// simple model class representing a message objectspublic 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 codebefore 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 (oneper user):private static HashMap _messageMap;

private static HashMap getMessageMap() {// Lazy initialization of a map of messagesif (_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 mapHashMap 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 pagemList.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 interfacesPage 30 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 31: JSF Tutorial for RAD

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

}

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

Let's build the inbox.

Using a data table

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

1. Open the Inbox.jsp page in Design mode, then click the Data Tablecomponent on the palette. (You might have to click the arrow, becausethe 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 theValue 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

Page 32: JSF Tutorial for RAD

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

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

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 32 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 33: JSF Tutorial for RAD

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 elaborateand 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 toomany messages to see it working), then click Add a simple pager. Thedata table implementation has various types of pagers; you canexperiment 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 isthe heading.

10. Click the column itself, and then change the ID to from. Drop anoutputText element from the palette into the column. In the Propertieseditor, click the icon to the right of the Value field, then select the frommessage, 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

Page 34: JSF Tutorial for RAD

11. Click the h:dataTable element in the Properties editor. To the right is atable that shows the columns of the table. Click Add to add a secondcolumn. 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 tomessage.

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 objectfor 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 interfacesPage 34 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 35: JSF Tutorial for RAD

If you run your application (see Run the messaging center within RationalApplication 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

Page 36: JSF Tutorial for RAD

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. RationalApplication Developer Version 6.0 creates the Faces JSP file.

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

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

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

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

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

8. In the Properties Editor, change its ID to receiverError. The resultingJSP 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 componenton the palette to add the field for the message text.

10. Click the page to drop the component. In the Properties Editor in theh:inputText tab, change the ID to messageText and change the Widthfield 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 thenext panel.

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 36 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 37: JSF Tutorial for RAD

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 newmessage needs to be generated and added to the receiver's list.

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

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

3. Click the hx:commandExButton pane, and then click Add Rule to add anew 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 Formattab, 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 andthe target of the navigation. Because both buttons "live" on the same page, theymust 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), navigationoccurs to Inbox.jsp. More specifically, if you look at the navigation rule infaces-config.xml, this becomes clearer:<navigation-rule>

<from-view-id>/Compose.jsp</from-view-id><navigation-case>

<from-outcome>success</from-outcome><to-view-id>/Inbox.jsp</to-view-id>

</navigation-case></navigation-rule>

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 mustremember 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

Page 38: JSF Tutorial for RAD

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

3. The Cancel button is very easy to implement. You really don't need to doanything, because you're just going back to the inbox without savinganything. The following code is therefore enough. One small issue notaddressed is that if you cancel, no validation should occur. But that isn'tvery important for purposes of this tutorial.public String doCancelButtonAction() {

// Do nothing - always navigate back to the inboxreturn "success";

}

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

public void addMessage(String receiver, String text) {// get the user's message map and add the new messagegetUserMessages(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 firstgetting the User Managed Bean. You can access this object through theFacesContext by looking up the object using its name, using the utilitymethod you just added, and returning success. The code for this methodis:

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 pagefrom the Inbox page. You can easily do this navigation with a commandbutton, but all you really need is a simple hyperlink. Select Inbox.jsp, andthen 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, enterCompose.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 saveyour work and go to the next section for testing and packaging.

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 38 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 39: JSF Tutorial for RAD

Section 8. Test, package, and install your application

Overview

Now that you've finished developing your simple messaging center, run or debug itwith Rational Application Developer. (Use the Test Environment, an embeddedWebSphere Application Server instance.) When everything works, package andexport the application to be deployed on a production WebSphere Application Serverinstance.

Run the messaging center within Rational ApplicationDeveloper

To run the messaging center:

1. Launch the Login.jsp page on the test environment.

2. In the Project Navigator, right-click MessagingCenter > WebContent >Login.jsp, then select Run > Run on server (or Debug on Server if youwant to step through your code).

3. If this is the first time you are launching an application within RationalApplication Developer Version6.0, a window appears asking you to selectwhich server environment you want to launch on. Select the Create anew Server option, then select one of the WebSphere (or other server)environments.

4. Select the Set server as project default check box so that RationalApplication Developer doesn't prompt you every time you want to checkyour application.

5. Click Finish.

The server starts, and various messages are written to the console. When you see asequence of messages of the following form, the server is up and running (the linesbelow are cropped to fit the page):[3/10/05 1:32:00:141 EST] 00000018 WebGroup A SRVE0169I: Loading Web Module: WebSphe[3/10/05 1:32:00:203 EST] 00000019 ApplicationMg A WSVR0221I: Application started: Sample[3/10/05 1:32:00:219 EST] 00000018 VirtualHost I SRVE0250I: Web Module WebSphere Admin...[3/10/05 1:32:10:969 EST] 0000000a RMIConnectorC A ADMC0026I: The RMI Connector is availa[3/10/05 1:32:11:047 EST] 00000021 WorkSpaceMana A WKSP0023I: Workspace configuration con[3/10/05 1:32:13:531 EST] 0000000a WsServerImpl A WSVR0001I: Server server1 open for e-b[3/10/05 1:32:17:562 EST] 00000012 WorkSpaceMana A WKSP0023I: Workspace configuration con[3/10/05 1:32:17:875 EST] 0000002e ServletWrappe A SRVE0242I: [transfer]: Initialization[3/10/05 1:32:18:109 EST] 0000002e WorkSpaceMana A WKSP0023I: Workspace configuration con[3/10/05 1:32:23:391 EST] 0000002e WorkSpaceMana A WKSP0023I: Workspace configuration con

ibm.com/developerWorks developerWorks®

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

Page 40: JSF Tutorial for RAD

[3/10/05 1:32:30:844 EST] 0000002f ServletWrappe A SRVE0242I: [Faces Servlet]: Initializa[3/10/05 1:32:31:172 EST] 0000002f ServletWrappe A SRVE0242I: [/Login.jsp]: Initializatio

At this point, a browser window opens as a new page on the main pane with thelogin page. You can test your application as shown in Figure 30.

Figure 30. Testing your application

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 40 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 41: JSF Tutorial for RAD

Package and export your application

Now that you've tested your messaging center application, package it in a form that

ibm.com/developerWorks developerWorks®

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

Page 42: JSF Tutorial for RAD

can be deployed on a Java 2 Platform, Enterprise Edition (J2EE) application server,such as WebSphere Application Server.

To package your application:

1. The messaging center is part of the MessagingCenterEAR enterpriseapplication project. If you open the MessagingCenterEAR folder in theProject Navigator (within the Enterprise Applications folder) anddouble-click Deployment Descriptor, you can see that the messagingcenter is inserted as a Web Archive (WAR) module, as shown in Figure31.Figure 31. EAR deployment descriptor

2. Right-click the MessagingCenterEAR project, then select Export > EARFile.

3. Enter a file name indicating where the application package should beexported in the Destination field, then click Finish. The EAR file is createdwith an embedded MessagingCenter.war file. If you open the embeddedWAR file, you see that in addition to your code, all the JSF run time isincluded in the form of JAR files, such as jsf-api.jar, jsf-impl.jar, andjsf-ibm.jar.

Install the EAR on WebSphere Application Server (Optional)

To complete this section, you need to have an instance of the WebSphereApplication Server installed. To deploy your exported application, use theWebSphere administrator console. Make sure that WebSphere Application Server isrunning; if it isn't, start both the HTTP server and the WebSphere Application Server.

1. Open the administrator's console by navigating your browser tohttp://localhost:9060/admin.

2. Enter your user ID, then click Submit.

3. Using the navigator pane on the left, go to Applications > Install New

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 42 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 43: JSF Tutorial for RAD

Application.

4. Enter the path to the EAR file, or use the Browse button to find it.Because you are deploying an EAR file, you do not need to specifyanything else: All the application properties are embedded within theEAR.

5. Click Next.

6. Because the EAR includes a Web module, you need to specify whichvirtual host it should be deployed onto. The next window in the ApplicationInstallation Wizard allows you to specify the virtual host. Keep thedefault_host value, then click Next.

7. Click Next again, unless you want to modify some of the defaultdeployment parameters.

8. Map all Web modules to the default host, then click Next.

9. In the next wizard window, select the cell and server on which the Webmodules are to be deployed, then click Next.

10. Confirm that all the application details are correct, then click Finish. Theapplication is installed; this can take some time, so be patient.

11. Save the changes to the master configuration by clicking on the Save toMaster configuration link, then clicking Save.

When you click the Enterprise Applications link in the navigator pane, you shouldsee your new enterprise application.

Section 9. Summary

Summary

JSF is an exciting new technology that promises to make it far easier to build Webapplications. It allows Web developers to finally use techniques and methods thatwere all used when developing Swing applications within IDEs (or other UIs such asPowerBuilder) -- methods that transform Web application development from atedious task of understanding what happens on the server versus what happens onthe client to a visual design exercise using reusable components and attributeeditors. And while JSF is a new kid on the block, Rational Application DeveloperVersion 6.0 already implements this technology and gives you a chance to startusing it now.

ibm.com/developerWorks developerWorks®

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

Page 44: JSF Tutorial for RAD

In this tutorial, you developed a full Web application and saw the various facets ofJFS, including visual composition of JSP pages, navigation, validation, actions,Backing Beans, and Managed Beans. You used several UI components, includingsimple components such as input fields and hyperlinks as well as complexcomponents such as the data table. Most importantly -- if you now look back at theamount of code that you actually wrote -- you will see that it is very small and thatmany of the definitions are declarative in nature and are used by the JSF run time toimplement your application flow. After all -- that's what a good framework does.

developerWorks® ibm.com/developerWorks

Create Web-based user interfacesPage 44 of 46 © Copyright IBM Corporation 1994, 2006. All rights reserved.

Page 45: JSF Tutorial for RAD

Resources

Learn

• Download or browse the Rational Application Developer V6 ProgrammingGuide Redbook.

• For more on the basics for developing Web applications using JSF, see thedeveloperWorks tutorial " UI development with JavaServer Faces " by JackwindLi Guojie.

• IBM WebSphere Developer Technical Journalhas a five-part series onDeveloping JSF Applications using Rational Application Developer V5.1.1.

• A tutorial on building Java HTTP servletsis available on developerWorks.

• Check out the Apache Jakarta taglib project at http://jakarta.apache.org/taglibs/.

• You can find the Sun tag library page athttp://java.sun.com/products/jsp/taglibraries.html.

• The JavaServer Faces home pageincludes the latest specifications as well asadditional JSF resources.

• Go to JFSCentralfor a comprehensive collection of JSF-related resources.

• Struts is today's de-facto framework for building Web applications. You can readabout Struts on the Apache Software FoundationWeb site.

• You can download a Struts-JSF integration library from the JakartaWeb site.

• Visit the Rational Application Developerhome page for more information aboutRational Application Developer.

Get products and technologies

• Register to download Rational Application Developer Version 6.0.

• Check out JSF Early Access Release 4 (EA4) -- a reference implementation forJSF 1.0.

Discuss

• Participate in the discussion forum for this content.

About the author

Ron Ben-NatanRon Ben-Natan, a Studio B author, is CTO and VP, R&D, at Guardium Inc. -- aleader in data access security solutions. Prior to that, he worked for companies suchas Intel, AT&T Bell Laboratories, Merrill Lynch, J.P. Morgan, and ViryaNet. He has aPh.D. in Computer Science in the field of distributed computing and has beenarchitecting and developing distributed applications for more than 15 years. His

ibm.com/developerWorks developerWorks®

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

Page 46: JSF Tutorial for RAD

hobby is writing about how technology is used to solve real problems, and he isauthor and co-author of numerous books, including Implementing Database Securityand Auditing, Mastering IBM WebSphere Portal, CORBA: A Guide to CommonObject Request Broker Architecture, The San Francisco Developer's Guide, and IBMWebSphere: The Complete Reference. He has also written numerous articles andtutorials.

developerWorks® ibm.com/developerWorks

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