Developing Java Server Faces Applications in Rational Application Developer (RAD)

By enabling JavaServer Faces in Rational Application Developer, you'll be surprised how easy it is to create applications -- with very little actual coding required.

Jeff Wilson (wilsonje@us.ibm.com), e-business Architect, IBM

Jeff K. Wilson is an e-business Architect in IBM's Developer Relations group. Before joining IBM in April, Jeff K. Wilson went by Jeff Wilson -- and in some circles, just Jeff would suffice. Currently, Jeff K. Wilson enjoys the company and solidarity of the ever-growing "Club De Jeff Wilson" here at IBM. Be wary of contacting Jeff Wilson, even if you have the city -- or even building of the Jeff Wilson you may think wrote this article. The official "Jeff Wilson" in town sits a short walk down the hall collecting occasional poorly addressed Jeff K. Wilson e-mail. Jeff K. Wilson can be properly reached at wilsonje@us.ibm.com.



10 November 2005 (First published 10 June 2005)

I remember the good old days: scouring through line after line of code till the wee hours, looking for the stupid typo in the file that no one claimed to touch but nevertheless was wreaking havoc like nobody's business. Or the twelfth cup of coffee at 9 p.m. (or was it the following a.m.?), wracking my brain to figure out how to display something a certain way -- or how to get data from one place to the next, or any of a number of coding obstacles that I once found challenging but now consider, well, simply obstacles.

You know what I did yesterday? I downloaded the latest IBM® IDE (Integrated Development Environment), Rational® Application Developer (RAD). Then I opened it. Then, I created a Web project to see some of the new JavaServer™ Faces (JSF) components that I will (for the sake of example) pretend that I know very little about. Here's how it went. I:

  1. Created a few pages using the Faces JavaServer Pages™ (JSP) wizard
  2. Tossed in a few components using the drag-and-drop palette
  3. Configured them using an Attributes GUI
  4. Designed the flow in a visual modeler
  5. Flipped over to the Source view
    1. Gads!
    2. Flipped back to the Design view
  6. Finally, I right-clicked the main JSP and clicked Run on Server to kick off the embedded Test Environment, which (for those of you who live under rocks) is a fully-functioning IBM® WebSphere® Application Server v6 running inside the development environment -- thus no packaging, deploying, or installing

Guess what, it worked. Then I went home, had some dinner, and played with my kid for a couple hours before putting her to bed.

It was 7:30. And I had two cups of coffee.

Did I know how to do this last week? Nope. Was I already familiar with the tooling? Not really. Sure I may have used WebSphere Studio a bit before, but who hasn't? I've developed maybe a handful of conference labs, a few workshops, perhaps written a certification test or two on the matter, but forget all that. The point I am trying to make is that with very little prior experience, I was able to open up a tool I had never seen before and create a simple application in a few hours. No stress. No big issues. Why? Open standards.

Standards say how something should be done. Open standards mean we all agree on how that "how something should be done" is done. With available open standards like JSF, it is simply a matter of time before someone starts developing widgets that do that something for us -- and, better yet, do the something in such a way that it prevents me from doing it any other wrong way.

Let me give you an example: the JSF components. Do you know all the components available and all their possible attributes? I don't. But I know that in the Palette view of the development tooling, I have a list of all the components. I drag one to where I want it on a JSP and it's just there. If I want to configure it, I look at the fields displayed in the Attributes view. This simplifies your life because:

  • There's no guess work
  • Just fill out the form
  • You're done

You may not have the experience I have -- maybe you have none at all. But that is exactly the purpose of this article: to give you enough of an understanding of the new tooling -- particularly in this case the JSF tooling - that you're able to expand on it by implementing similar methodologies on your own applications, which you likely know quite well.

What this article is about

Developing a JSF application can be as complex as you want or need to make it. As with any application, the amount of effort is directly proportional to the flexibility required to get the job done.

Your application may be riddled inside and out with JSF components controlling every aspect of the flow and processing. Or it may be that you will simply ease into this technology by adding a few key components to some of your JSPs. What we will focus on in this article is the tooling -- how to implement some of the components in your application, where to use them, and how they interrelate. While there are many more components than those you will use here, you should gain enough of an understanding of the environment to use really anything in the JSF palette (for added fun once you complete your task at hand).

This article addresses the basics of setting up a JSF-based Dynamic Web Project. It will focus on the following areas:

  • Creating a dynamic Web Project in RAD
  • Using the Web Diagram tooling to model our web application
  • Using the Web Diagram tool to generate the components of our application
  • Adding JSF components to the individual JSPs
  • Utilizing the Page data view to manage both request variables and managed beans
  • Using the Quick Edit view to manage the flow of our application and to manage session data
  • And finally, testing our application in the embedded Test Environment

If you are new to JSF or RAD, this article will provide you with the basic understanding required to master any project.


Our task at hand

Application flow

I created a simple product display application that accesses a list of plants from a supplier backend. When selecting a plant from the list, you will be directed to one of three pages:

  • An error page if a product is not carried at all
  • A backordered product page that might display information on dealing with that issue or
  • A product detail page for items in stock and ready for ordering

Figure 1, following, displays how these pages are organized.

Figure 1. Product display application flow diagram
Product display application flow diagram

Managed JavaBeans

Additionally, as with a standard application, we make use of JavaBeans™ to manage business logic and hold data from request to request -- in the session, or however a JSP might need to access it.

One of the beans will manage accessing data about our plant request. In our example, this JavaBean has hard-coded plant data, but you can assume that, in a real application, the data would of course be pulled from a database.

The other JavaBean simply holds data in the session where JSPs can easily access it.

What's in these managed beans

The first (business logic) bean has two methods:

  • One pulls data about a particular plant, stores the information in the data bean, and returns the populated data bean to whatever called the method. This is the method we will call to load a specific plant data bean in the session.
  • The other checks to see if a plant is in stock, backordered, or simply not a product at all. Based on what this method returns (backordered, instock, or dontcarry), the JSF-defined flow will determine to which JSP to forward information.

The data bean, used to hold data in the session, simply has various String properties that describe a plant (plantID, plantName, and sunTolerance), along with typical "getters" and "setters".

Both JavaBeans are maintained as "managed beans" in JSF-speak. These are similar to using typical <jsp:use-bean ? /> and <jsp:getProperty ?/> tags in standard JSP pages. In this case, the tooling makes managing and displaying certain bean properties a simple matter of dragging them -- as you will find (at least the basics) with all the other components you use.


Setting up the project

By now you should have downloaded the RAD software and installed it. If not, you might be getting ahead of yourself.

Also download and unzip RAD_JSF.zip to C:\temp to extract the components we will pretend were developed by other members of your team.

You are tasked with devising a JSF front-end application using these back-end components.

  1. Open RAD to any workspace
  2. From the main toolbar, select File -> New -> Dynamic Web Project
  1. Name it PlantInfo and click Finish
  1. Click Yes to accept the perspective switch
  1. In the Project Explorer view, expand Dynamic Web Projects\PlantInfo\Java Resources
  2. Right-click \Java Resources\JavaSource and click Import
  3. On the Import dialog, click File System -> Next
  4. Browse to C:\temp
  5. Expand temp in the left panel of the dialog
  6. Select the com check box
  7. Make sure that PlantInfo/JavaSource is entered in the Into folder field, and then click Finish
  8. This means that your required package and two included JavaBeans has been imported

Note: CutAndPasteCode.txt is just a file that includes code from which you will later -- you guessed it -- cut and paste code to use with your application at various steps.


Modeling our application in RAD

Before creating your application components, you want to model the application using the Web Diagram tool. The Web Diagram tool allows you to drag components, and to draw connectors indicating the flow of a Web application, prior to any coding effort. This lets you define the core components and the flow of the greater application in a more efficient and visual manner.

  1. Double-click to open Dynamic Web Projects\PlantInfo\Web Diagram
  1. From the Palette view click Web Page and drag it onto the Web Diagram editor
  1. Name the jsp icon /productList.jsp and press Enter (the preceding "/" will disappear)
  1. Repeat the steps to add 3 more Web Pages
    1. /error.jsp,
    2. /notInStock.jsp
    3. /productDetails.jsp
  1. In the Palette view, click Connection
  1. Click once on the productLis.jsp icon and then click error.jsp
  2. In the Choose a connection dialog, expand Faces Outcome, click <new>, and then click OK
  1. A connection arrow now links the two icons: Change <new> to notAProduct

Note: Later, you will associate the labels created here to pages to which to forward information.

  1. From the Palette view again, click Connection and add two more connections from productList.jsp to both notInStock.jsp and productDetails.jsp
  2. Name the connections notInStock and loadProductInfo
  1. Press Ctrl+S to save the model

What you now have is a model for the application, but no code (other than what was imported). From here on out you will start using this model to help generate your code for you.


Generating code from the model

Now you can begin to create your application components. You will use the model as a starting point for this process.

  1. In the Web Diagram tool, double-click the productList.jsp icon to launch the New Faces JSP File dialog
  1. Click Finish (in the current build of the IDE, there appears to be a bug: initially, you can't click the Finish button. To get around this if you have the same issue, select and then clear the Configure advanced options checkbox -- the Finish button should now work)
  2. Go back to the Web Diagram editor and double-click all three icons (error.jsp, notInStock.jsp, and productDetails.jsp) icons to generate those Faces-based JSPs
  3. Notice that in the Web Diagram editor, the JSP icons display in color when they are "realized" -- meaning that when a file is created, it is associated with the icon that it represents
  1. Go back to the Web Diagram editor again and double click the notAProduct connection label

Note: This will launch the Navigation Rule dialog, generate the URL forward labeled notAProduct, and point to the error.jsp

  1. On the Edit Navigation Rule dialog, accept the defaults and click OK
  1. Do the same for both of the other remaining connection labels

Note: Now when actions occur that return one of these three labels, the JSF engine will know to forward to the listed pages.


Edit the JSPs

Now we can begin to add JSF components to our JSPs.

  1. Open productList.jsp in the main editor and delete the default text in it
  1. From the Palette view, expand Faces Components and drag Output to the JSP main editor
  1. With the Output component selected in the JSP, locate the Properties view and enter Product List as the Value, then press Enter
  1. Click the Style: Props button
  1. Select a given font (to be replicated in the header of all the JSPs), as shown following:
  1. Click OK
  1. Press Enter a few times to add some line breaks after the header
  2. Repeat this process to add headers and line breaks as described below to each of the three other pages
    1. error.jsp -- Errors
    2. productDescription.jsp -- Product Info
    3. notInStock.jsp -- Not In Stock
  3. Open up productList.jsp again
  4. Drag another Output component to the JSP
  5. Set the Value field in the Properties view to Select a product:
  1. From the Palette view, drag the List Box - Single Select next to Select a product:
  1. Set the Id field to productId
  2. Click the Add Choice button to add the following select choice name and value pairs to the list box
  1. Set the Size: Height field to 1
  1. Locate the Page Data view
  2. Expand Scripting Variables
  3. Right-click requestScope and select New -> Scripting Variable -> Request Scope Variable
  1. In the Add Request Scope Variable dialog, enter the Variable name (productId), set the Type to java.lang.String, and click OK
  1. Expand requestScope and drag productId onto the list box

Note: This binds the requestScope variable to the value selected in this list box when submitted. By that, I mean that the value entered using this input field will automatically populate requestScope and be managed by the JSF framework. Any JSP the user is sent to can access requestScope and use it on that page. In addition, if you redirect the user back to the original form -- say they forgot to enter something and you push them back to the form to complete it -- the field is automatically populated with the value of requestScope, so the user does not need to re-enter the already-filled-out part of the form. Thanks to the tooling, no additional coding is required - it just happens. Nifty.

  1. From the Palette view, drag the Command Button component to the JSP
  1. Notice in the Properties view that all the URL forwards are already set (from when you generated them in the Web Diagram editor)
  1. Click Add Rule
  2. In the Add Navigation dialog, select the productList.jsp Page, set The outcome named field to productList, and click the All pages option button

Note: This provides a global forward from any page to the productList.jsp

  1. Click OK
  2. On the Display Options tab, set the Button label field to Lookup plant

Setting up the managed beans

Your next step is to attach managed beans to your JSP. Your managed beans hold the business logic that our JSPs use to process or access data. In this case you will be using it look up the availability of a particular plant. Setting them up is a simple task using the Page Data view.

  1. Right-click Scripting Variables in the Page Data view and select New -> JavaBean
  1. In the Add JavaBean dialog, click the Add new JavaBean option button, and enter plantInfo in the Name field
  2. Click the Class button and start typing plant to see a subset of classes beginning with the same characters -- select PlantInfoBean and click OK
  1. Select the Make this JavaBean reusable checkbox
  2. Choose Session Scope
  3. Click Finish
  4. Add another JavaBean named plantLookup to the Page Data view of the class com.acme.plants.PlantLookup

Process something already, will you?

So far you haven't manually coded anything. All you have done is drag components onto the page, designing the look of the page. There is only so much the tooling will do for us before we must add our own processing instructions. The task at hand is to submit the form and define what happens to the submitted information.

The way you accomplish this in RAD is by using the Quick Edit view. You could edit the specific Java classes, but the Quick Edit view conveniently displays only the portion of a given class relevant to what you want to edit. For instance, when you submit a form, the JSF framework will call a specific method -- the command method -- based on what button was pushed. To edit this command method, all you need to do is have a button selected in the design view, select Command from the Quick Edit view, and enter the processing code into the space provided. The tooling will put that code in the appropriate class.

Additionally, we can use the Quick Edit view to define processing on the client side when certain events fire (like onclick, onmouseover, and so on). When those events occur, whatever you enter into the Quick Edit view will run.

  1. On the productList.jsp, right-click on the Lookup plant button and select Edit Events
  2. Locate the Quick Edit view that loads and click Command in the left pane
  3. Click somewhere in the right pane and code auto-magically appears (trust me, try it)

Note: The code in this Command space is called when the form is submitted. The return will be one of the forward labels you set. Typically, some processing will determine which label is returned. You will use one of the managed beans to determine whether or not a product is in stock, and therefore which page to forward to.

  1. Replace the return ""; in the Quick Edit view with the following (now is a good time to open CutAndPasteCode.txt and copy the code discussed in the Setting up the project section):

Note: Let's take a look at what is happening. It is first important to realize what is being called in this code.

For example, the line getProductId().getValue().toString() returns the value of the input field labeled productId. If you do not recall making a method called getProductId, that is because the tooling added this for you into a code-behind bean (a JavaBean JSF uses to manage JSPs with JSF content).

The getter and setter methods in the code behind bean are similar to -- but more flexible than -- using JSP tags to reference request object values, because you can add other processing instructions that you want to have run when the form was submitted. This could be validation code, refining code, and so on.

Another new method to note is getPlantInfo. The return of this method is the plantInfo managed bean that you added to the Page Data view. This is the PlantInfoBean data bean that is to be stored in the session. You may notice that you don't have to do anything on your own to store that in the session -- the JSF framework again does the work for you. All you need to do is call getPlantInfo to access and set a property on that object.

So, let's take a look at what you are processing when this form is submitted by clicking the Lookup plant button.

Admittedly, I have methods ready to go that do the processing on the managed beans. In your next project, you will also have back-end beans that you tie into from these front-end JSF components. In this case, the method used tells you whether or not an item is in stock, or if it is even a product at all. You will use the return of that method to determine what page to forward the client to. Given all this information, you can now determine what the code is doing:

  1. The first line simply accesses the value of the productList -- it is the ID to lookup
  2. The next line grabs an instance of the managed bean plantLookup from the session
  3. The first IF statement checks if the ID is set to 000, which is not a product but is the value of the first selection in the list. If so it returns to the page labeled productList - namely productList.jsp
  4. Otherwise, it sets a property called availability to the return of checkStock, which is the method that indicates what the status of a given product is
  5. Then, based on the availability, you forward to one of the JSPs by returning one of the four labels you set up
  1. Save (Ctrl+S) and close productList.jsp

Create the error page

Now let's add error handling for products that do not exist. In this case, you will have no product data associated with the supplied product ID. You will create a page that says the ID does not appear to be a product, and show the ID pulled from the form submission for reference.

  1. From the Project Explorer view, double-click error.jsp to open it in the main editor
  2. Below the header, add the following text (again, this can be copied from CutAndPasteCode.txt):

Sorry, the product ID, , was not found in the database

Note: Notice the double commas -- you are going to place the product ID output of the form in between those.

  1. From the Palette view, select Output and drag it between those commas
  1. In the Page Data view, right-click Scripting Variables and click New -> Scripting Variable -> Request Scope Variable
  2. In the Add Request Scope Variable dialog, set the Variable name to productId and the Type to java.lang.String
  3. Drag the new productId request variable onto the outputText on the JSP
  1. With the output text component still selected, set the Style props field in the Properties view to color:red and press Enter
  1. Now to add a link back to the product list, select Command - Hyperlink from the Palette view and drag it to your JSP
  1. Right-click the component and select Edit Event (the Quick Edit view opens)
  2. In the Quick Edit view, with Command selected in the left pane, click somewhere in the right pane
  3. Set the return to productList (recall that is the pointer back to the productList.jsp)
  1. Now click on the actual words link label in the component on the JSP
  1. In the Properties view, set the Value field to Try again and press Enter
  1. Save (Ctrl+S) and close error.jsp

Handle back-ordered products

Back-ordered products are items we know about, but which are out of stock. We can pull more information from that item for display. In this case, when the product list form submits, recall that the command code executes the following:

In this case, if the item is back-ordered, the first thing it does is call a method called loadPlantInfo which takes in a PlantInfoBean and product ID as the two arguments. The product ID is used to look up details of a particular plant, and the information is stored in the PlantInfoBean passed in. The method returns the populated bean and is stored as plantInfo -- the beans stored in the session. You can use this bean -- with the information used to populate it -- on other JSPs.

On this Not in Stock page, you will pull the product name out of this stored bean to display to the user.

  1. Open notInStock.jsp
  2. Just as you did on the error page, add the following text below the header (this can also be found in CutAndPasteCode.txt)

Sorry, the product, , is not currently in stock. Please try again later.

  1. In the Page Data view, right-click and select New -> Scripting Variable -> Request Scope Variable
  2. On the Add Request Scope Variable name it productId with the Type of java.lang.String and click OK
  3. Right-click Scripting Variable again and select New -> JavaBean
  1. In the Add JavaBean dialog, click the Add existing reusable JavaBean option button, select plantInfo from the Existing reusable JavaBeans list, and click Finish
  1. From the Palette view, select Output again and drag it between the commas in the JSP
  2. In the Page Data view, expand plantInfo and drag plantName onto the outputText in the JSP
  1. With the output selected in the JSP, set the Style Props field in the Properties view to color:red and press Enter
  1. From the Palette view, select Command - Hyperlink and drag it to the bottom of the JSP
  2. Right-click the component and select Edit Event
  3. In the Quick Edit view, with Command selected in the left pane, click somewhere in the right pane
  4. In the right pane, set the return to productList
  1. Click the actual words link label in the component
  1. In the Properties view, set the Value field to Back to product list and press Enter
  1. Save (Ctrl+S) and close notInStock.jsp

Finally, add the product details page

  1. Open productDetails.jsp
  2. In the Page Data view, right-click Scripting Variables and click New -> JavaBean
  1. In the Add JavaBean dialog, click the Add existing reusable JavaBean option button, select plantInfo from the Existing reusable JavaBeans list, and click Finish
  1. Select the whole plantInfo managed bean and drag it to the JSP
  1. In the Insert JavaBean dialog, re-label the field names to something slightly easier to understand (for example, change sunTolerance to Sun Tolerance) and click Finish
  1. A table is now generated in the JSP
  1. From the Palette view, select Command - Hyperlink and drag it to the bottom of the JSP
  2. Right-click the component and select Edit Event
  3. In the Quick Edit view, with Command selected in the left pane, click somewhere in the right pane
  4. In the right pane, set the return to productList
  1. Click the actual words link label in the component
  1. In the Properties view, set the Value field to Search for another and press Enter
  1. Save (Ctrl+S) and close productDetails.jsp

Test the application

Now the only thing left to do is test it out.

RAD includes a fully-functioning application server within the tooling, so no need for packaging, exporting, or installing is necessary. Also, any specific server configurations can be set up within the tool as well. This way you can define several different types of servers with various configurations to test your application in many types of environments.

In this case you will be using the WebSphere Application Server v6.0 environment with the basic set of configurations.

  1. Right-click productList.jsp and select Run -> Run on Server
  2. In the Server Selection dialog, accept the defaults using WebSphere Application Server v6.0
  1. Next, the WebSphere Application Server Test Environment loads and displays the product list form
  1. Simply click Lookup plant without selecting one in the list -- the same form should be returned, since you set it up so that if the product ID was 000 then forward to productList
  2. Select Rosemary from the plant list and click Lookup plant (this was the plant identified as a product we do not carry so it ought to return the error page)
  1. Click Try again
  2. You should return to the product list
  3. Now select Yaupon Holly (which I hear from a reliable source is out of stock) and click Lookup plant
  1. Oh, what a surprise
  1. Click Back to product list
  2. Finally choose Italian Cypress and click Lookup plant
  3. Yippie

Summary

So, there you have it -- JSF enabled in RAD. As you saw, taking some existing code and layering a JSF front-end on top of it was a truly simple task. Though our application was fairly simplistic, it required exceptionally little actual coding - especially compared to what would be required to manually write a similarly functioning non-JSF version.

Also, as I mentioned at the beginning of this article, we used only a subset of the components JSF has to offer. You may have noticed several of these components along the way. It should be noted that many of these other components can be implemented in much the same way as you did in the steps of this tutorial.

Likewise, your final application, though likely more complex, will also employ many of the same steps you just followed. A much more complex JSF-based application would use the same methodology, and would not likely be all that much more difficult than this simple exercise.

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Rational software on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Rational, DevOps
ArticleID=84862
ArticleTitle=Developing Java Server Faces Applications in Rational Application Developer (RAD)
publish-date=11102005