using ibm rational software architect to develop ajax

26
Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components Skill Level: Introductory Mike Starkey ([email protected]) Distinguished Engineer IBM Guang Qing Zhong ([email protected]) Software Engineer IBM Li Long Chen ([email protected]) Software Engineer IBM Chuan Yang ([email protected]) Software Engineer IBM Elaine Zhan ([email protected]) Software Engineer IBM Larry Zou ([email protected]) Software Engineer IBM 05 Aug 2008 This article explains how to use IBM® Rational® Software Architect v7.0 to develop Ajax-supported JSF components. Introduction to how Rational Software Architect implements Ajax Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components © Copyright IBM Corporation 1994, 2007. All rights reserved. Page 1 of 26

Upload: sampetruda

Post on 22-Apr-2015

1.886 views

Category:

Documents


6 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Using IBM Rational Software Architect to develop Ajax

Using IBM Rational Software Architect to developAjax-supported JavaServer Faces componentsSkill Level: Introductory

Mike Starkey ([email protected])Distinguished EngineerIBM

Guang Qing Zhong ([email protected])Software EngineerIBM

Li Long Chen ([email protected])Software EngineerIBM

Chuan Yang ([email protected])Software EngineerIBM

Elaine Zhan ([email protected])Software EngineerIBM

Larry Zou ([email protected])Software EngineerIBM

05 Aug 2008

This article explains how to use IBM® Rational® Software Architect v7.0 to developAjax-supported JSF components.

Introduction to how Rational Software Architect implementsAjax

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 1 of 26

Page 2: Using IBM Rational Software Architect to develop Ajax

Java™Server Faces (JSF) is a Web application framework in the Java® 2 Platform,Enterprise Edition (J2EE) specification that has already been used by manycompanies. IBM has created a JSF-based component library called JWL (for JSFWidget Library) that implements and extends the JSF specification (JSR 127). JWLmakes it easier to create applications based on JSF.

More recently, Asynchronous JavaScript and XML (AJAX, known as Ajax) hasbecome very popular, because it can greatly enhance the user experience ofWeb-based applications. However, it is difficult to develop Ajax applications withoutusing an Ajax framework. Fortunately, JWL, which is available in IBM® Rational®Software Architect Version 7.0, provides Ajax functionality through JSF components.This JWL support makes it easier to develop Ajax-supported JSF components.

This article uses an example and hypothetical user scenarios to explain how to useRational Software Architect v7.0 to develop Ajax-supported JSF components.

Ajax functionality provided by Rational Software Architect Version 7.0

A JSF page is populated by JSF components; therefore, Rational Software Architect7.0 implements Ajax functionality by refreshing the target JSF component withoutrefreshing the whole page in the user interface (UI) layer. Currently, not all JSFcomponents can be refreshed. However, Ajax functionality is useful for most panelcomponents, including these:

• <h:panelGroup>

• <h:panelGrid>

• <hx:panelMenu>

• <hx:panelDialog>

There are three types of Ajax requests:

• <hx:ajaxRefreshRequest> Get request from the same page. Thisrequest is used to pass values of various input fields on the page.Therefore, developers should specify parameters that need to be passed.

• <hx:ajaxSubmitRequest> Post request to the same page. This requestis used to submit the entire form; therefore, you do not need to specifyparameters.

• <hx:ajaxExternalRequest> Get request from another page. This is usedto embed a JSF component from another page.

The next section explains the basic steps for adding Ajax support to a JSFcomponent.

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 2 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 3: Using IBM Rational Software Architect to develop Ajax

Steps to add Ajax support to JSF components

Generally, adding Ajax support to JSF a component requires three steps:

1. Specify the target JSF component and select the Ajax request typeIn a JSF page, you must refresh the target area with the Ajax request.Thus, you need to specify which JSF component that you want to refresh.After you select the targeted JSF component, you must specify whichtype of Ajax request that you want to use.

2. Configure the request parametersIn most scenarios, you will probably want to pass parameters in arequest, so you must specify those parameters. Except for theajaxSubmitRequest type, the left two types of Ajax requests shouldspecify the parameters.

3. Specify the behavior that invokes the Ajax requestUntil this step, you can say that the target JSF component is ready toaccept the Ajax request. The only thing that you lack is that you mustspecify a behavior to invoke the Ajax request. This behavior can beevents from the client side, such as an onclick event upon the click of abutton or an onchange event for a selection from a drop-down menu.

The section of this article titled Refresh a JSF component by usingajaxRefreshRequest describes and illustrates these steps.

Example used in this article

For this article, we use a sales management system as an example. This systemhas three requirements:

• Requirement 1: Total customers and sales by date. Lists the numberof customers and sales totals by each calendar day.

• Requirement 2: Products sold by date and customer. Lists all of theproducts that customers bought by date and customer selected. Userscan also get detailed information about the products.

• Requirement 3: Customer information by date. Lists all of thecustomers, as well as summary information for each customer, by date.

Figure 1 shows the main Web page design elements included for these

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 3 of 26

Page 4: Using IBM Rational Software Architect to develop Ajax

requirements.

Figure 1. Segments from the main Web page

This page includes three areas:

• Summary information area. This area lists the number of customers andtotal sales by calendar day, thereby implementing Requirement 1.

• View selection area. This area is used to decide which view should bedisplayed. Different selections can show different views. In theimplementation code, this is implemented by usingajaxExternalRequest.

• Concrete view display area. This area displays statistical information.The view is determined by the radio button selection, and the datadisplayed is determined by the date selected.

• When the user clicks the Detailed View button, this area displays adrop-down menu that contains all of the customer names. Users canthen select a customer name to show products bought by that person.Results are shown in the products table below. In the products table,users can click each row to get detailed product information in thearea to the right. This view implements Requirement 2.

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 4 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 5: Using IBM Rational Software Architect to develop Ajax

• When the user clicks Summary View, this area displays a table withall of the customers names and their basic shopping summaries. Thisview implements Requirement 3.

With this page design, all of the functions can be implemented in a main page sothat a users don't need to click many choices to get the views that they want. Thisdesign enhances the user experience. Unfortunately, it is too difficult for developersto implement this design by using traditional Web technology. However, by using theAjax functionality provided by Rational Software Architect 7.0, you can implementthis design easily.

For this example, we applied Ajax technology in two parts:

1. Using ajaxRefreshRequest to refresh the JSF component

A. Refreshing a JSF component by using the radio button

B. Refreshing a JSF component by selecting from the drop-downmenu

2. Using ajaxExternalRequest to embed a JSF component of anexternal JSF page

A. Embedding an external JSF component from the same JSF pageby using a radio button

B. Embedding an external JSF component from a different JSF pageby using a set of radio buttons

By focusing on these two parts, the following sections introduce how to develop thisexample by using Rational Software Architect 7.0.

Refresh the JSF component by using ajaxRefreshRequest

Here, refreshing a JSF component means refreshing only a JSF component withnew data, not also embedding a JSF component from an external JSF page. Torefresh a JSF component, we usually use ajaxRefreshRequest, notajaxSubmitRequest. The next two subsections explain how to use radio buttonsand drop-down menus to invoke ajaxRefreshRequest.

Invoke ajaxRefreshRequest by using a radio button

The scenario: A user wants to get a detailed view, thus he must select the date firstand then click the Detailed View button. After that, the detailed view will be displaybelow (see Figure 2).

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 5 of 26

Page 6: Using IBM Rational Software Architect to develop Ajax

Figure 2. Screen fragments: Date and Detailed View selections and resultingdisplay of details

However, when this user selects another date, the detailed view should be refreshedand all of the data should belong to the selected date (see Figure 3).

Figure 3. Detailed View with a different date selected

As you learned in the section about How to add Ajax support to JSF components,there are three steps to add Ajax support to JSF components. The next sectiondescribes how to implement this scenario by following those three steps.

Step 1. Specify the target JSF component and select the Ajax request type

According to this scenario, you know that you want to refresh "concrete view displayarea" so that you can put this area into one panelGrid named ViewWrapper and thenset this panelGrid as the target JSF component. Here, you can select

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 6 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 7: Using IBM Rational Software Architect to develop Ajax

ajaxRefreshRequest as the Ajax request type (Figure 4).

Figure 4. Add Ajax support for panelGrid

1. Select panelGrid ViewWrapper and then select the Properties view.

2. Click the Ajax menu in the left panel.

3. In the right panel, check "Allow Ajax updates."

4. Select Refresh, which means that the Ajax request type isajaxRefreshRequest.

Listing 1 shows the code snippet.

Listing 1. ajaxRefreshRequest code sample

<h:panelGrid id="ViewWrapper"><h:panelGrid id="ViewGrid" styleClass="panelGrid"></h:panelGrid></h:panelGrid><hx:ajaxRefreshRequest id="ajaxRefreshRequest1"target="ViewWrapper"></hx:ajaxRefreshRequest>

The target attribute means which JSF component you want to send the Ajax request.

Step 2. Configure the request parameters

In this scenario, you must pass the selected date to the server. In this example, thedate selections are items in a dataTable. However, because JSF keeps only oneinstance of each component in the table, you must let the server know that the valuethat you want to use is in the active row. "Active row" means that this row will invokean event to invoke the Ajax request.

1. Therefore, to pass the value of selected date, you must add$$AJAXROW$$ before the ID of the component.

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 7 of 26

Page 8: Using IBM Rational Software Architect to develop Ajax

2. To add parameters, you can either select Click to edit Ajax requestproperties (see Figure 4, previously) or select ajaxRefreshRequest inthe Source view and then select Properties > Add Parameter (Figure 5).

Figure 5. Configure the parameters of ajaxRrefreshRequest

The input focus will be moved to table "Parameter values send from the browser",input the parameter you want to send, here is"$$AJAXROW$$form1:tableEx1:selectedDate". Listing 2 shows the code that isgenerated.

Listing 2. Generated code

<hx:ajaxRefreshRequest id="ajaxRefreshRequest1" target="ViewWrapper"params="$$AJAXROW$$form1:tableEx1:selectedDate"></hx:ajaxRefreshRequest>

3. Use the params attribute to set parameters that you want to pass. Youcan specify a set of values.

Step 3. Specify the behavior that invokes the Ajax request

When you click the radio button in the summary table, the JSF ViewWrappercomponent should refresh. The JWL runtime process can capture the onclickevent to invoke the Ajax request, as Figure 6 shows.

Figure 6. Quick Edit view

1. Select the radio button in the Design view and then select Quick Edit

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 8 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 9: Using IBM Rational Software Architect to develop Ajax

View.

2. Select onclick in the left panel. The left panel lists all the supported eventto invoke the Ajax request.

3. Check the check box, User pre-defined behavior Action on the top ofQuick Edit View.

4. From the drop-down menu, select Invoke Ajax behavior on thespecified tag.

5. Select the target JSF component, which is ViewWrapper.

6. Change to the Source view so that you can see the source code in Listing3.

Listing 3. Source code

<hx:inputRowSelect id="rowSelect1" styleClass="inputRowSelect"selectOne="true" value="#{summary.selected}">

<hx:behavior event="onclick" behaviorAction="get"targetAction="ViewWrapper"></hx:behavior>

</hx:inputRowSelect><h:inputHidden id="selectedDate"value="#{summary.date}"></h:inputHidden>

The hx:behavior is used to attach JavaScript functionality to client-side events onJSF components.

7. In this case, use the onclick event of radio button to invoke the Ajaxrequest.

The value get of the behaviorAction attribute means that you want to run a getaction on the ViewWrapper component. As you may recall from the previous section,you need to pass the value of the selected date. Therefore:

8. Add an inputHidden component to bind the selected date.

Until this point you can use the radio button to refresh the target JSF component.The next section explains how to use drop-down menu to invoke an Ajax request.

Invoke the ajaxRefreshRequest by using the drop-down menu

For this section, assume this scenario: After selecting one date, the user wants toget the list of all of the customers. The user can also select one customer to get thedetailed shopping information of that customer. In the Web site in this example, the

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 9 of 26

Page 10: Using IBM Rational Software Architect to develop Ajax

user selected Detailed View to display an area. In that area, all of the customers'names are listed in the drop-down menu, and the user can select from that menu toshow detailed shopping information. The effect is illustrated in Figures 7 and 8.

Figure 7. Select the customer named Jimmy from the drop-down menu

Figure 8. Select another customer, named Tom

As you see, this design can improve the user's experience greatly.

The steps that follow describe how to invoke an Ajax request by using thedrop-down menu.

Step 1. Specify the target JSF component and select the Ajax request type

In this example, the target JSF component is a panelGrid, which contains adataTable. The name of the panelGrid is userTable. In this scenario, useajaxRefreshRequest. Listing 4 shows the code snippet.

Listing 4. ajaxRefreshRequest code sample

<h:panelGrid id="UserTable" styleClass="panelGrid" columns="3"width="700px">……</h:panelGrid><hx:ajaxRefreshRequest id="ajaxRefreshRequest1"target="UserTable"></hx:ajaxRefreshRequest>

Step 2. Configure the request parameters

You pass the selected value of the drop-down menu to the server. This article

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 10 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 11: Using IBM Rational Software Architect to develop Ajax

already covered how to pass parameters by using radio buttons, but the process isdifferent when using the drop-down menu. When using a radio button, you can passthe value of the active row to the server. But when using drop-down menu, there isno active row concept; therefore, you add a JavaScript function to set the value ofthe drop-down menu to the inputHidden component. Listing 5 shows the codesnippet.

Listing 5. Code to add the JavaScript function to set the value to inputHidden

function passCurSelect(srcSelect, tgtInput) {var select = document.getElementById("form1:"+srcSelect);var input = document.getElementById("form1:"+tgtInput);input.value = select.value;}

<h:selectOneMenu style="margin-right:0px;" id="selectUser"onchange="passCurSelect('selectUser','userName');"><f:selectItems value="#{pc_DetailedReport.userItems}" /></h:selectOneMenu><h:inputHidden id="userName"value="new"></h:inputHidden>

From the code, you can see that the value of inputHidden will be set as the valueof the drop-down menu when the selection changes. You also need to addparameters to the ajaxRefreshRequest component, as Listing 6 shows.

Listing 6. Add parameters to the ajaxRefreshRequest component

<hx:ajaxRefreshRequest id="ajaxRefreshRequest1"target="UserTable"params="userName"></hx:ajaxRefreshRequest>

Step 3. Specify behavior to invoke Ajax request

In this scenario, the target JSF component should be refreshed when a userchanges the selection on the drop-down menu. You use the onchange event toinvoke the Ajax request, so you must add an hx:behavior component to theh:selectOneMenu component. Listing 7 shows the h:selectOneMenu definitionwith hx:behavior component.

Listing 7. The h:selectOneMenu definition with hx:behavior component

<h:selectOneMenu style="margin-right:0px;" id="selectUser"onchange="passCurSelect('selectUser','userName');"><f:selectItems value="#{pc_DetailedReport.userItems}" /><hx:behavior event="onchange" target="selectUser"behaviorAction="get" targetAction="UserTable"></hx:behavior></h:selectOneMenu>

The value of attribute target should be set as the value of the ID of

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 11 of 26

Page 12: Using IBM Rational Software Architect to develop Ajax

h:selectOneMenu (the drop-down menu). Here, the hx:behavior means thatwhen the user changes the selection on the drop-down menu, the drop-down menuwill invoke the Ajax request and run the get action to get the content of JSFUserTable component.

Embed an JSF component of an external page by usingajaxExternalRequest

In traditional Web technologies, you can embed external pages by using iFrame,jsp:includePage, and so on, but all of these technologies embed all of thecontent of the external page rather than only part of the content. WithajaxExternalRequest, you can embed a specified target JSF component withAjax support. In the following subsections, you will see how to use radio buttons toinvoke ajaxExternalRequest.

Embed the JSF component of the same external page by using a set of radiobuttons

First, let's review the scenario. In the Detailed View, the user can list all of theproducts by selecting a customer in the drop-down menu. But the information aboutthe product listed in the table may be not enough, so the user may want to see someother detailed information about this product. In this design, the user can click theradio button in each row to get other details, which will be displayed on the right sideof the screen. The screen elements in Figures 9, 10, and 11 illustrate this design.

Figure 9. Detailed View without the radio button selected

Figure 10. Detailed View with the radio button selected

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 12 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 13: Using IBM Rational Software Architect to develop Ajax

Figure 11. Detailed View with another radio button selected

From these screen captures, you can see that the detailed information is displayedonly when one of the radio buttons is selected and that when the user selectsanother radio button, the details change without refreshing the whole page.

Step 1. Specify the target JSF component and select the Ajax request type

In this scenario, assume that you want to show detailed product information whenthe product is selected. You can use ajaxExternalRequest to embed detailedproduct information of another page when the product is selected. In Figure 9, theright rectangle area is used for detailed product information. It is s a panelGridnamed ProductDetail in the DetailedReport.jsp file. Listing 8 shows the source code.

Listing 8. Source code for the ProductDetail panelGrid

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 13 of 26

Page 14: Using IBM Rational Software Architect to develop Ajax

<h:panelGrid id="ProductDetail"styleClass="panelGrid"></h:panelGrid>

In this case, we put the detailed product information in the ProductDetail.jsp file.Because we want to embed another JSF panelGrid of ProductDetail.jsp toDetailedReport.jsp, we have to follow these rules to define the target JSFcomponent in DetailedReport.jsp:

• The component should be the same type as the component inDetailedReport.jsp, which is a panelGrid here.

• The component ID should have the same name as the component inDetailedReport.jsp, thus ProductDetail here.

• If the target component in DetailedReport.jsp is in a form, the externalcomponent in ProductDetail.jsp should also be in a form with the samename. Here, the form name is form1.

The target external JSF component is defined as code Listing 9 shows.

Listing 9. Code for the target external JSF component

<h:form id="form1"><h:panelGrid id="ProductDetail" styleClass="panelGrid" style="width:200px"><h:outputText id="text1" styleClass="outputText"value="Name" style="font-style: normal; font-weight: bold"></h:outputText><h:outputText id="text2" styleClass="outputText"value="#{pc_ProductDetail.product.name}"></h:outputText><h:outputText id="text3" styleClass="outputText"value="Description" style="font-style: normal; font-weight: bold"></h:outputText><h:outputText id="text4" styleClass="outputText"value="#{pc_ProductDetail.product.description}"></h:outputText><h:outputText id="text5" styleClass="outputText"value="Price" style="font-style: normal; font-weight: bold"> </h:outputText><h:outputText id="text6" styleClass="outputText"value="#{pc_ProductDetail.product.price}"></h:outputText><h:outputText id="text7" styleClass="outputText"value="Discount" style="font-style: normal; font-weight: bold"></h:outputText><h:outputText id="text8" styleClass="outputText"value="#{pc_ProductDetail.product.discount}"></h:outputText></h:panelGrid></h:form>

Step 2. Configure the request parameters

When the radio button is clicked, you must pass the product ID to the server, so thatyou know which product you need to show the detailed information. Therefore, in theradio button column, you use the code shown in Listing 10.

Listing 10. Code for the Radio Button column

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 14 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 15: Using IBM Rational Software Architect to develop Ajax

<hx:columnEx id="column3" width="50" align="left"><f:facet name="header"><h:outputText id="text5" styleClass="outputText" value="Select"></h:outputText></f:facet><hx:inputRowSelect id="productSelect"styleClass="inputRowSelect" selectOne="true"></hx:inputRowSelect>

<h:inputHidden id="productID" value="#{item.product.productID}"></h:inputHidden></hx:columnEx>

After you put an inputHidden component in this column, you also need toconfigure the params in ajaxExternalRequest component so that, when theradio button is clicked, you can use the value of this component as a parameter andthe external page can get the value of productID from the HttpRequest. Listing11 shows the source code.

Listing 11. Source code

<h:panelGrid id="ProductDetail" styleClass="panelGrid">

</h:panelGrid><hx:ajaxExternalRequest id="ajaxExternalRequest1"target="ProductDetail" href="ProductDetail.faces"params="$$AJAXROW$$form1:tableEx2:productID"></hx:ajaxExternalRequest>

The value of the target attribute should be the same as the value of the JSFcomponent to which you want to add Ajax support. The value of the href attributeshould be set as the JSF page where you put the external target JSF component.

Step 3. Specify the behavior that invokes the Ajax request

This scenario requires that the detailed product information should be displayedwhen the radio button is selected. Thus, from a technical viewpoint, you should usethe onclick event to invoke the Ajax request. Listing 12 shows the radio buttondefinition with the behavior definition.

Listing 12. Radio button and behavior definitions

<hx:inputRowSelect id="productSelect"styleClass="inputRowSelect" selectOne="true">

<hx:behavior event="onclick" behaviorAction="get;stop"targetAction="ProductDetail"></hx:behavior></hx:inputRowSelect>

The second action in the behavior (stop) is to prevent the event from bubbling up inthe browser. That is because you just want to invoke Ajax request and don't want thelink to act like you want to invoke the real target link in this case.

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 15 of 26

Page 16: Using IBM Rational Software Architect to develop Ajax

After completing these three steps, all UI code has been set. You can implement thebackend code in PageCode to implement this scenario. From a technical viewpoint,when the radio button is selected, the content of the ProductDetail component inthe ProductDetail.jsp file will be retrieved, and that content will be used to replacethe definition of the ProductDetail component in the DetailedReport.jsp file. Afterthat substitution, the ProductDetail component area will be refreshed and thenthe detailed product information will be displayed in the DetailedReport.jsp file.

Embed a JSF component of a different JSF page by using a set of radiobuttons

In this scenario, after the user selects the date, she can select different radio buttonsto get different views.

• When she selects Detailed View, the page will display the content asFigure 12 shows.

• If she selects Summary View instead, the page content will look likeFigure 13.

Figure 12. Detailed View

Figure 13. Summary View

From a technical perspective, when the user selects Detailed View, the page shouldembed a JSF component from an external page, and when she selects SummaryView, the page should embed a JSF component from a different external page. Thisscenario is more difficult to implement than the previous one. Therefore, we need toreview the design first.

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 16 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 17: Using IBM Rational Software Architect to develop Ajax

Figure 14 is the layout of the main JavaServer Page. This page can be divided intofour parts, each part is implemented by using panelGrid: Part 1 is SummaryListpanelGrid which is used to list total customers and sales by date; Part 2 isSelectionArea panelGrid which is used to offer selections to select different views;Part 3 is ViewWrapper panelGrid which wraps a panelGrid to list products sold bydate and customer; Part 4 is ViewGrid panelGrid and is the panelGrid wrapped byViewWrapper. Because you want to embed a different JSF component of a differentJSF page, you must bind a variant of the href attribute in theajaxExternalRequest component, and you need to change the value when theuser clicks a different radio button in Part 2. To change the value of the hrefattribute, you add a ViewGrid panelGrid inside the ViewWrapper panelGrid andmake ViewGrid support ajaxExternalRequest. This is the invocation process:

Figure 14 Layout of the Main.jsp page

1. When the user clicks the radio button in Part 2, that refreshes Part 3, sothe value of href will be changed according to the latest selection.

2. Then the ajaxExternalRequest will be invoked, and the ViewGridpanelGrid will be substituted by an external JSF component.

The following steps explain this in more detail.

Step 1. Specify the target JSF component and select the Ajax request type

In this case, you must use ajaxRefreshRequest and ajaxExternalRequest:

• The first, ajaxRefreshRequest, is used to refresh the ViewWrapperpanelGrid.

• The second, ajaxExternalRequest is used to embed an external JSF

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 17 of 26

Page 18: Using IBM Rational Software Architect to develop Ajax

ViewGrid component.

Step 2. Configure the request parameters

Because you must refresh the ViewWrapper panelGrid, you need to make theViewWrapper component support ajaxRefreshRequest, as the code in Listing 13shows.

Listing 13. Code to make the ViewWrapper component supportajaxRefreshRequest

<h:panelGrid id="ViewWrapper"><h:panelGrid id="ViewGrid" styleClass="panelGrid"></h:panelGrid>

</h:panelGrid><hx:ajaxRefreshRequest id="ajaxRefreshRequest1" target="ViewWrapper"params="radio1;$$AJAXROW$$form1:tableEx1:selectedDate"></hx:ajaxRefreshRequest>

The first parameter, #radio1, is used to pass the value of radio button selection. Thesecond one is used to pass the selected date (this value is available only when thisAjax request was invoked by radio buttons in Part 1). Besides that, you need tomake the #ViewGrid panelGrid support #ajaxExternalRequest. Figure 14 shows thesource code that does this.

Listing 14. Source code to make the ViewGrid panelGrid supportajaxExternalRequest

<h:panelGrid id="ViewGrid" styleClass="panelGrid"></h:panelGrid><hx:ajaxExternalRequest id="ajaxExternalRequest1" target="ViewGrid"params="hidden1" href="#{pc_Main.urlOfView}"onstart="func_1(this, event);setRadioButtons('#{pc_Main.urlOfView}');"></hx:ajaxExternalRequest>

If the value of parameters will not change, the ajaxExternalRequest will usecached external JSF component. Therefore, you need to pass a dynamically uniquevalue to make the ajaxExternalRequest get a new JSF component each time.As Listing 15 shows, you can do that by including an inputHidden component,hidden1, and invoking a JavaScript function, func_1, to change the value ofhidden1 when the Ajax request was invoked.

Listing 15. Code to make the ajaxExternalRequest get a new JSF componenteach time

<h:selectOneRadio disabledClass="selectOneRadio_Disabled"enabledClass="selectOneRadio_Enabled" id="radio1"styleClass="selectOneRadio"

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 18 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 19: Using IBM Rational Software Architect to develop Ajax

><f:selectItem itemValue="DetailedReport.faces"itemLabel="Detailed View" /><f:selectItem itemValue="SummaryReport.faces"itemLabel="Summary View" /><h:inputHidden id="hidden1" value="1" /></h:selectOneRadio>

var counter=0;function func_1(thisObj, thisEvent) {var obj = document.getElementById("form1:hidden1");if (obj) {var datetime = new Date();var datetimeString = datetime + "";counter++;obj.value = counter+"X"+datetimeString;}}

Step 3. Specify the behavior that invokes the Ajax request

These two Ajax requests should be invoked when a user clicks a radio button. TheJWL runtime process will capture the onclick event to invoke the Ajax request.The ajaxRefreshRequest needs to be invoked first and then theajaxExternalRequest will be invoked. Listing 16 shows the source code for this.

Listing 16. Code to invoke two Ajax requests in sequence

<h:panelGrid id="SelectionArea" styleClass="panelGrid" columns="2">

<h:outputText styleClass="normalLabel" value="Please select view: "></h:outputText><h:selectOneRadio disabledClass="selectOneRadio_Disabled"enabledClass="selectOneRadio_Enabled" id="radio1"styleClass="selectOneRadio" ><f:selectItem itemValue="DetailedReport.faces"itemLabel="Detailed View" /><f:selectItem itemValue="SummaryReport.faces"itemLabel="Summary View" /><h:inputHidden id="hidden1" value="1" /></h:selectOneRadio><hx:behavior event="onclick" target="radio1"behaviorAction="get;get;" targetAction="ViewWrapper;ViewGrid"></hx:behavior>

</h:panelGrid>

One behavior can invoke multiple Ajax requests. In this case, the radio button shouldrefresh the ViewWrapper component and then ViewGrid, in that order. To get thatresult, add multiple values in the behaviorAction and targetActionattributes. Figure 15 illustrates how to use Quick Edit to configure multiple action inthis scenario.

Figure 15. Using Quick Edit to configure multiple actions

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 19 of 26

Page 20: Using IBM Rational Software Architect to develop Ajax

As Figure 15 shows:

1. Click onclick on the left panel.

2. Check the box Use pre-defined behavior Actionand select Multipleactions in the adjacent drop-down menu on the right.

3. Clicking the drop-down Target menu will let you input multiple actions.

4. In the popup window, select Invoke Ajax behavior on the specified tagin column Action, then set the value of Target as ViewWrapper.

5. Click button Insert After on the right of the popup window to add anotherAjax action using the same previous steps.

Ways to use Rational Software Architect to developAjax-supported JSF components

Use Ajax support judiciouslyFor each JSF page, it has a corresponding pagecode (it is a Javaclass) and each JSF component has a corresponding initializationmethod in the pagecode. Ideally, for each Ajax invocation you wouldjust invoke the initialization method to initialize the target JSFcomponent, but actually, it will refresh the whole pagecode, thus allthe initialization methods will be invoked and all the JSFcomponents in the pagecode will be reinitialized. Thus, usingextensive Ajax support may cause performance issues. To avoidperformance issues caused by Ajax, you can add a decisionsentence in the initialization code of JSF components.

When you write JSF pages, you can write code manually or you can use RationalSoftware Architect to generate code automatically. We suggest that you useRational Software Architect to generate code automatically, because there are ways

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 20 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 21: Using IBM Rational Software Architect to develop Ajax

to implement these requirements, but only the code generated by Rational SoftwareArchitect is stable.

Use Rational Software Architect to generate code

For example, in this scenario, when the user selects a different date, the ConcreteStatistic View should refreshed. In this implementation, when the user clicks theradio button, that action should invoke a JavaScript function to refresh the ConcreteStatistic View. If you write the code manually, you can code it as Listing 17 shows.

Listing 17. Code for invoking JavaScript to refresh the Concrete Statistic View

<hx:inputRowSelect id="rowSelect1" styleClass="inputRowSelect"selectOne="true" value="#{summary.selected}" onclick="window.setTimeout(clickRadio,200);">

<hx:behavior event="onclick" behaviorAction="get"targetAction="ViewWrapper"></hx:behavior></hx:inputRowSelect>

In this example, the code to invoke the JavaScript function is in the onclickattribute, but if you use Quick Edit, the code generated is different. Figure 16 showsa screen capture of using Quick Edit to generate code to invoke JavaScript functionby following these steps:

1. Click the Quick Edit tab to get the editor view.

2. Select the onclick event from the directory.

3. In the code view, input JavaScript code you want to invoke.

4. Save your changes.

Figure 16. Use JSF quick editor to invoke JavaScript function

Listing 18 shows the generated code.

Listing 18. Code generated when using Quick Edit

<hx:inputRowSelect id="rowSelect1" styleClass="inputRowSelect"selectOne="true" value="#{summary.selected}" >

<hx:behavior event="onclick" behaviorAction="get"

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 21 of 26

Page 22: Using IBM Rational Software Architect to develop Ajax

targetAction="ViewWrapper"onActionFunction="return func_2(this, event);"></hx:behavior></hx:inputRowSelect>

The code snippet in Listing 19 is the generated JavaScript function.

Listing 19. Code generated for the JavaScript function

function func_2(thisObj, thisEvent) {//use 'thisObj' to refer directly to this component instead of keyword 'this'//use 'thisEvent' to refer to the event generated instead of keyword 'event'window.setTimeout(clickRadio,200);}

Although both of these implementations will work well, we suggest that you use theJSF editor to generate code, because the generated code is stable.

Share this...

Diggthisstory

Posttodel.icio.us

Slashdotit!

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 22 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 23: Using IBM Rational Software Architect to develop Ajax

Downloads

Description Name Size Download method

Sample code AjaxableJSF.zip 4656KB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 23 of 26

Page 24: Using IBM Rational Software Architect to develop Ajax

Resources

Learn

• Learn more by reading JSF and Ajax: Web 2.0 application made easy withRational Application Developer V7 by Yury Kats (IBM® developerWorks®,December 2006).

• Visit the Rational software area on developerWorks for technical resources andbest practices for Rational Software Delivery Platform products.

• Explore Rational computer-based, Web-based, and instructor-led onlinecourses. Hone your skills and learn more about Rational tools with thesecourses, which range from introductory to advanced. The courses on thiscatalog are available for purchase through computer-based training orWeb-based training. Additionally, some "Getting Started" courses are availablefree of charge.

• Subscribe to the IBM developerWorks newsletter, a weekly update on the bestof developerWorks tutorials, articles, downloads, community activities, webcastsand events.

• Subscribe to the developerWorks Rational zone newsletter. Keep up withdeveloperWorks Rational content. Every other week, you'll receive updates onthe latest technical resources and best practices for the Rational SoftwareDelivery Platform.

• Subscribe to the Rational Edge newsletter for articles on the concepts behindeffective software development.

• Browse the technology bookstore for books on these and other technical topics.

Get products and technologies

• Download trial versions of IBM Rational software.

• Download these IBM product evaluation versions and get your hands onapplication development tools and middleware products from DB2®, Lotus®,Tivoli®, and WebSphere®.

Discuss

• Rational Software Architect, Data Architect, Software Modeler, ApplicationDeveloper and Web Developer forum: Ask questions about Rational SoftwareArchitect.

About the authors

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 24 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 25: Using IBM Rational Software Architect to develop Ajax

Mike StarkeyMike Starkey is a Distinguished Engineer on assignment from IBM Canada to theIBM China Development Lab in Beijing, China. He is the architect for MBPS SolutionAssets.

Guang Qing ZhongGuang Qing Zhong is a Software Engineer supporting the IBM Software Group.

Li Long ChenLi Long Chen is a Software Engineer supporting the IBM Software Group.

Chuan YangChuan Yang is a Software Engineer supporting the IBM Software Group.

Elaine ZhanElaine Zhan is a Software Engineer supporting the IBM Software Group.

Larry ZouLarry Zou is a Software Engineer supporting the IBM Software Group.

Trademarks

IBM, the IBM logo, and ibm.com are trademarks or registered trademarks ofInternational Business Machines Corporation in the United States, other countries, or

ibm.com/developerWorks developerWorks®

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces components© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 25 of 26

Page 26: Using IBM Rational Software Architect to develop Ajax

both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Other company, product, or service names may be trademarks or service marks ofothers.

developerWorks® ibm.com/developerWorks

Using IBM Rational Software Architect to develop Ajax-supported JavaServer Faces componentsPage 26 of 26 © Copyright IBM Corporation 1994, 2007. All rights reserved.