The article guides you, step-by-step, through the process of designing and developing an application by using Asynchronous JavaScript and XML (AJAX, hereafter Ajax) with IBM® Rational® Application Developer Version 7.0. It includes practical techniques for how to use various Java™Server Faces (JSF) components in conjunction with Ajax and shows you how to overcome the built-in caching in a Relational Record List. It explains how to initialize the session scope variable to display the data corresponding to the initial value of the Combo Box control at application startup.
You will also learn the steps to add a Tabbed Panel control to a Web page and to configure a Data Tree to work with a Relational Record List. It concludes by showing you a technique for accessing data elements from a Relational Record List that consists of two related tables.
This article does not cover the details of each of the technologies used in the examples, but there are several articles cited in Resources that describe each of them if you want to learn more. The main technologies used are Ajax, JSF using IBM Enhanced Faces components, and service data objects (SDOs).
Knowledge and system requirements
The instructions assume a basic knowledge of the Java™ language, but you do not need extensive experience in Java. However, this article assumes that you have a basic knowledge of using the Rational Application Developer development environment. It also assumes you have basic knowledge of Ajax and SDOs. See Resources for more information on these technologies.
To run the examples in this article, you must have either IBM® Rational® Software Architect or Rational Application Developer installed on your workstation. The version of Rational Application Developer used in this article is 7.0.
Create the WeatherForecastDB database
To create the application database, you will complete these three tasks:
- Download and import the CreateWeatherForecastDatabase.zip into your workspace.
- Create the supporting Derby database named WeatherForecastDB by using the supplied Java application.
- Create a connection to the WeatherForecastDB database.
Download and import the Java project
The weather forecast application uses a Derby database for its information. For this example, you will use a Java application to create the database. If you want to learn more about how to manually create a database by using the Data perspective in Rational Application Developer, read the IBM® developerWorks® article titled "Hello World (Updated): Rational Application Developer V7, Create Java, Web Service, and database applications" (see Resources for a link).
To begin, follow these steps:
- Download and save the CreateWeatherForecastDatabase.zip file to your computer (see Downloads).
- Start Rational Application Developer on your desktop. If a window appears
asking for the workspace directory, enter
c:\temp\weatherforecast, and then click OK. - Close the Welcome screen if it appears.
- Import the CreateWeatherForecastDatabase.zip file:
- From the workbench, select Window > Open Perspective > Java to switch to the Java perspective.
- Select File > Import > Other > Project Interchange to import the project into your workspace.
- Click Next.
- Next to From zip file, click Browse to navigate to where you saved the CreateWeatherForecastDatabase.zip file.
- Click Select All.
- Click Finish.
Next, set up the Java build path for the Java project.
- Right-click CreateWeatherForecastDatabase in the Package Explorer view (Figure 1) to set the Java build path, in case it did not carry over when you imported the project.
Figure 1. Set the Java build path
- Select Properties (see Figure 2).
- Click Java Build Path.
- Click the Libraries tab. Ensure that the path for the derby.jar file has been added. If you can't find it, you will need to add it manually by following these steps:
- Click Add External JARs.
- Enter this path:
C:\Program Files\IBM\SDP70Shared\plugins\com.ibm.datatools.db2.cloudscape.driver_1.0.0.v200610121320\driver\derby.jar - Click Open.
- Click OK.
Figure 2. Path for the derby.jar file
Important note:
These instructions assume that you have selected the
default installation for Rational Application Developer Version 7.0, and that you
are using Embedded Derby file, which is included with Rational Application
Developer, with no database security.
If not, please modify the path for derby.jar file accordingly in the Java build path and class location for the connection. Also, you might need to edit the entries for the driver, protocol, user ID, and password in the CreateWeatherForecastTablesDB.java file.
Create the WeatherForecastDB database
Now you're ready to create the WeatherForecastDB database:
- Under the Package Explorer, expand CreateWeatherForecastDatabase > default package.
- Right-click CreateWeatherForecastTablesDB.java, and then select Run As > Java Application.
- Watch for the last message, "Committed transactions," in the
Console view. This message indicates that the Java application has completed
these tasks successfully:
- Created the WeatherForecastDB database in the c:\temp directory
- Created the tables, primary keys, foreign keys, and indexes
- Loaded the test data to be used by the examples
Create the database connection
Now that you have created the WeatherForecastDB database, you need to create the database connection. You will create the connection to the WeatherForecastDB database in the Database Explorer view.
Alternative:
The steps that follow show how to manually create a
database connection. If you prefer, you can create a connection by using the SDO
Creation wizard.
- Select Window > Open Perspective > Other to switch to the Data perspective.
- Select the Show all check box, and then select Data.
- Click OK.
- If you are asked to enable the Core Database Development capability, click OK.
- In the Database Explorer view, right-click Connections (in the bottom-left corner), and click New Connection.
- Under Connection identification (Figure 3), leave Use default naming convention checked.
- Select Derby 10.1.
- For Database location, enter
C:\temp\WeatherForecastDB. - Uncheck Create the database if required, because you already created the database.
- For Class location, enter this path:
/C:/Program Files/IBM/SDP70Shared/plugins/com.ibm.datatools.db2.cloudscape.driver_ 1.0.0.v200610121320/driver/derby.jar - Under User Information, enter
Weatherfor the User ID. Leave the Password blank. - Click Test Connection to see if a connection can be established. If it can be, you should see a window stating "Connection to Derby is successful."
- Click OK to close the window.
- Click Next.
- Click Finish to create the connection.
Figure 3. Connection parameters
- Under the Database Explorer view, expand WeatherForecastDB connection to see the database tables that Figure 4 shows (LARGESTCITIES, STATES, STATESANDCITIES and TENDAYFORECAST).
Figure 4. Database tables
The diagram in Figure 5 shows the tables that were created and their relationships.
Figure 5. Tables and their relationships
Create the weather forecast application
Now that you have the groundwork laid out, the following are the next steps:
- Create the weather forecast dynamic Web project.
- Create a JSP page using JavaServer™ Faces technology.
- Create session scope variables.
- Create Relational Record Lists.
- Add these components and Ajax support to the JSP page:
- Table
- Combo Box
- Panel Group-Box
- Deploy and test the weather forecast application.
- Turn off caching for the largestCityPopulationSB Relational Record List.
- Deploy and test the application again.
- Initialize the session scope variable.
- Deploy and test the application again.
Create the WeatherForecastProject project
The first part of the weather forecast application displays the population for a given city.
In this section, you will create the dynamic Web project and your first JavaServer Page (JSP) that uses JavaServer™ Faces (JSF) technology. The basic weather forecast application will use a Combo Box to display the various United States cities. Based on the selection, the city population and ranking are fetched from the database and displayed in a Relational Record List. JSF technology is used for building this dynamic Web application.
- From the menu bar, click File > New > Project.
- From Select a wizard, check Show All Wizards.
- Scroll down and select Web > Dynamic Web Project.
- Click Next.
- If prompted, click OK to confirm that you want to enable Web Development.
- In the Name field, enter
WeatherForecastProject. - Important: For Configurations, select Faces Project.
- Make sure that the Add project to an EAR check box is checked.
- Click Finish.
- Click Yes to switch to the Web perspective.
Figure 6. Create the Web project
Create the comboBoxExample.jsp JSP page
You now have a new Web project. Your next step is to build the comboBoxExample.jsp page:
- Close WebDiagram.gph if it was open.
- Right-click WeatherforecastProject, and then select New > Web Page to launch the New Page wizard.
- For File Name, type
comboBoxExample.jsp. - Under Basic Templates, select JSP.
- Click Options, select JavaServer Faces.
- Click Close.
- Click Finish.
- Click Finish.
Figure 7. Create the comboBoxExample.jsp page
The comboBoxExample.jsp file is created under WeatherForecastProject/WebContent. When Rational Application Developer opens that page, you are ready to design the page.
Create a sessionScope variable called largestCityVar
- From the Page Data view, which is the lower-left pane in the Web perspective, expand Scripting Variables.
- Right-click sessionScope, and then select New > Session Scope Variable.
- For the Variable name, enter
largestCityVar. - For Type, enter
java.lang.String. - Click OK.
Create a Relational Record List called largestCitiesSB
- In the Web perspective, go to the Page Data view, which is the lower-left pane.
- Right-click Relational Records and select New > Relational Record List.
- For Name, enter
largestCitiesSB. - Click Next.
- Click New.
- Select Use an existing connection.
Tip:
You are using the database connection that you previously
created manually. If you have not yet created that connection, you can use the SDO
Creation wizard here to create the connection to the database.
- Select WeatherForecastDB, and click Next.
- For User ID, leave it as Weather.
- Leave the Password field blank.
- Click Next.
- Click Finish.
- Under Table, scroll down, expand WEATHER, and select LARGESTCITIES.
- Click Next.
- Click None. You will notice that only LARGEST_CITY is still selected, because it is the primary key.
- Click Finish.
Figure 8. Create Relational Record List largestCitiesSB
Create a Relational Record List called largestCityPopulationSB
Note:
This time, you will apply a filter to the Relational Record List to select
only the records that correspond to the city, as specified by the
largestCityVar sessionScope variable.
- From the Page Data tab, which is in the lower-left pane in the Web perspective, right-click Relational Records and select New > Relational Record List.
- For the name, enter
largestCityPopulationSB. - Click Next.
- Under Table, scroll down, expand WEATHER, and select LARGESTCITIES.
- Click Next.
- Under Tasks, click Filter results.
- Click the plus sign (+).
- Select LARGEST_CITY, and then, from the drop-down menu for Column, select LIKE.
- Select Variable, and then click the button with the ellipses (three dots: ...).
- Expand sessionScope, and select largestCityVar.
Figure 9. Filter settings
- Click OK.
- Click OK again.
- Click Close.
- Under Tasks, click Order Results.
- Move Ranking and LARGEST_CITY under Order by.
- Click Close.
Figure 10. Order results
- Click Finish.
Add the components and Ajax support to the JSP page
Add a table to the JSP page
- Under HTML Tags, drag a table onto the page by using the palette, and specify these dimensions:
- Rows: 1
- Columns: 2
- Table width: 100%
- Border width: 0 pixels
Figure 11. Specify table dimensions
- Click OK.
- 5. In the Properties view for the table, make sure the Table is selected, click the table leaf, and specify these preferences:
- Align: Left
- Width: 100%
- Height: 100%
Figure 12. Table leaf alignment
- In the Properties view for the cell, with the cursor in the first cell, specify this layout:
- Horizontal: Left
- Vertical: Top
- Width: 20%
- Wrap lines automatically: Not checked
- Put your cursor in the second cell, and specify this layout:
- Horizontal: Left
- Vertical: Top
- Width: 80%
- Wrap lines automatically: Not checked
- Click File > Save All to save your work.
Add a Combo Box
- In the first cell, type
Select a City:. - From under Enhanced Faces Components drawer, next to the text that you just typed, drag a Combo Box into the first cell.
Add a Panel-Group Box
- Drag a Panel-Group Box into the second cell. This is the area of the page that will be updated by the Ajax request.
- For Select Type, select Box and click OK.
Figure 13. Add a Panel-Group Box
Adjust the Panel properties
- Select the panel and switch to the Properties view.
- Make sure that hx:panelBox is selected.
- Enter these values:
- Width: 100%
- Height: 100%
- Vertical: Top
- Horizontal: Left
Add Ajax support to the panel
- Select the Panel Box and switch to the Properties view.
- Make sure that hx:panelBox is selected.
- Select the Ajax leaf for the hx:panelBox.
- Check the Allow Ajax updates check box.
- Click Submit as the Ajax request type.
Figure 14. Select Ajax request type
- Click File > Save All to save your changes.
Initiate the Ajax request by using the Combo Box onchange event
- Select the Combo Box component.
- Switch to the Quick Edit view (next to the Properties view).
- In the Quick Edit view:
- Select the onchange event from the list of events on the left side.
- Click the Use predefined behavior check box.
- Select the Invoke Ajax behavior action on the specific tag.
- Select box1 as the target, and then press the Tab key.
- Click File > Save All to save your work.
Figure 15. Use the onchange event to initiate the Ajax request
Bind the largestCitiesSB Relational Record List to the Combo Box
- From the Page Data tab, expand Relational Records > largestCitiesSB (Service Data Object) > largestCitiesSB(LARGESTCITIES).
- Drag LARGEST_CITY(String) onto the Combo Box. The Combo Box gets populated with the largest cities at run time.
Add All Cities to the Combo Box as an additional choice
- Switch to the Combo Box Properties view.
- Click Add Choice, and enter these values:
-
Label:
All Cities(All Cities shows the information for all of the cities in the database.) -
Value:
%(The % is a SQL wild card.) - Switch to the Combo Box Properties view.
- Select the choice All Cities and click Move Up.
Bind the largestCityVar variable to the Combo Box
- From the Page Data tab, expand Scripting Variables > sessionScope.
- Drag largestCityVar onto the Combo Box. The variable will get updated with the Combo Box value (either with the largest city name when a specific city is selected or with the % wild card when All Cities is selected).
The Combo Box Properties should now look like Figure 16.
Figure 16. Updated Combo Box properties
Add the largestCityPopulationSB Relational Record List to the Panel-Box
- From the Page Data tab, expand Relational Records > largestCityPopulationSB (Service Data Object).
- Drag largestCityPopulationSB (LARGESTCITIES) onto the Panel-Box so that you can display the information about the selected city.
- Edit the Labels (by clicking inside each label) as Table 1 shows (also see Figure 17):
Table 1. Edit labels in this order
| Column Name | Label | Control Type |
|---|---|---|
| RANKING | Ranking | Output Field |
| LARGEST_CITY | Largest City | Output Field |
| STATE | State | Output Field |
| POPULATION | Population | Output Field |
Figure 17. Edited labels
- Click Finish to close the Configure Data Controls window.
Alternate the background color for each row in the table
- Click the Display options leaf.
- Make sure that Row classes shows rowClass1, rowClass2 (see Figure 18). These are two CSS classes, separated by a comma, with different background colors. These values are usually defined in theme file stylesheet.css file inside of the project.
Figure 18. CSS classes for alternating row colors
- Remove the columnClass1 entry from the Classes column, because the columnClass overrides the rowClasses when the CSS is applied to the table.
Figure 19. Remove the columnClass1 entry
- Select File > Save All to save your changes. Your page should now look like Figure 20.
Figure 20. Modified page
That's it. You are ready to test the page and observe its behaviors.
- Under WeatherForecastProject/WebContent, right-click the comboBoxExample.jsp file, and select Run As > Run on Server.
- Check the box for Set server as project default and click Finish.
- Wait for the server to start and for the comboBoxExample.faces page to display.
When the page displays, the first thing that you may notice is that the table is empty. However, the Combo Box is showing a city name (Austin). We will address this issue next, but first, notice the other behaviors.
Figure 21. Testing the page
- Click the Combo Box to select Chicago as the city.
- Click the Combo Box again to select Austin as the city one more time. Notice that the information about Chicago is displayed, instead.
Figure 22. Testing the page: 2
- Click the Combo Box again to select Chicago as the city. Notice that the information about Austin is displayed, instead.
Figure 23. Testing the page: 3
Turn off caching for the largestCityPopulationSB Relational Record List
Note:
The Relational Record List does not have a property to set or
reset the caching. Instead, you need to edit the page code bean to turn it off.
- Close the comboBoxExample.faces page by clicking the X on its tab. You will be switched back to the comboBoxExample.jsp view.
- Right-click inside the comboBoxExample.jsp page and select Edit Page Code to open the ComboBoxExample.java file.
- From the Edit drop-down menu, click Edit > Find/Replace.
- For Find, enter
List getLargestCityPopulationSB(), and then click Find. - Enter a comment to negate the if
(largestCityPopulationSB == null)statement by adding two forward-slash marks: //. This will turn the caching off by forcing thedoLargestCityPopulationSBFetchAction()method to run every time. ThegetLargestCityPopulationSB()should look like Listing 1
Listing 1. Edit the page code to turn off caching
public List getLargestCityPopulationSB() {
// if (largestCityPopulationSB == null) {
doLargestCityPopulationSBFetchAction();
// }
return largestCityPopulationSB;
}
|
- Close the ComboBoxExample.java file.
- To save your work, click File > Save All.
- Under WeatherForecastProject/WebContent, right-click comboBoxExample.jsp and select Run As > Run on Server.
- Wait for the server to start and for the comboBoxExample.faces page to display.
- When the page displays, click the Combo Box to select Chicago as the city. Notice that the information about Chicago is actually displayed this time.
Initialize the sessionScope variable
Now that you have resolved the caching issue, let’s address the other issue, which is displaying the information about the city that corresponds to the information shown in the Combo Box at startup.
To initialize the largestCityVar at page startup, we edit the page code
for comboBoxExample.jsp and modify the
getLargestCitiesSB() method.
Initialize the largestCityVar with the value of the first SDO element for
Largest_City:
- Close the comboBoxExample.faces page by clicking the X on its tab. You will be switched back to the comboBoxExample.jsp page.
- Right-click inside of the comboBoxExample.jsp page, and select Edit Page Code to open the ComboBoxExample.java file.
- from the Edit drop-down menu, click Edit > Find/Replace.
- For Find, enter
List getLargestCitiesSB(), and then click Find. - Add the code from Listing 2 to the method (see Resources to learn more about SDOs and DataObjects):
Listing 2. Initialize the largestCityVar with the value of the first SDO element
if (largestCitiesSB == null) {
doLargestCitiesSBFetchAction();
// Add the following code to initialize the "largestCityVar" variable.
// +++ Start of Added Code
if (getSessionScope().get("largestCityVar") == null && largestCitiesSB != null) {
// Get the first Object
DataObject myfirstObject = (DataObject) largestCitiesSB.get(0);
// Assign the first SDO value for element LARGEST_CITY to the variable.
getSessionScope().put("largestCityVar", myfirstObject.get("LARGEST_CITY"));
}
// +++ end of Added Code
}
return largestCitiesSB;
}
|
- Close the comboBoxExample.java.
- Click File > Save All again to save your changes.
- Under WeatherForecastProject/WebContent, right-click comboBoxExample.jsp and select Run As > Run on Server.
- Wait for the server to start and for the comboBoxExample.faces page to display.
Notice that the information is displayed at startup that corresponds to the Combo Box entry.
- Click the Combo Box and select All Cities. Now, you'll see
the list of the top 20 cities with their information. That's
because the largestCityVar has the % wild card as its value. Therefore,
the Where SQL Statement reads:
where LARGEST_CITY LIKE %. Also notice the alternating row background color in the table. Close comboBoxExample.faces.
- Close the comboBoxExample.jsp page.
Add a Data Tree JSP page to the application
This part of the weather forecast application displays the 10-day forecast for a given city within the state.
In this section, you will complete these seven main steps:
- Create a second JSP page using JavaServer™ Faces technology.
- Create session scope variables.
- Create Relational Record Lists.
- Add these controls and Ajax support to the JSP page:
- Table
- Input-Hidden components
- Data Tree
- Panel Group-Box
- Tabbed Panel
- Turn off the Relational Record List caching
- Access the State Details
- Deploy and test the weather forecast application.
Create the dataTreeExample.jsp JSP page
First, you will create your second JSP page using Java™Server Faces technology. The page will use a Data Tree to display all of the states and cities in a hierarchical view. It uses the Panels-Tabbed JSF component. The first panel will have a Relational Record List to display the 10-day forecast for the selected city. The second panel will display the details about its State.
To begin, stop the server:
- In the Servers view, right-click WebSphere Application Server v6.1 and select Stop.
Important:
The embedded Derby database that is included with
Rational Application Developer allows for only one active connection at a time.
This limitation does not apply if you are using IBM DB2®, instead.
Therefore, when you need to create or modify the Relational Record Lists, you must
stop the WebSphere Application Server to relinquish its database connection.
To create the JSP page:
- While in the Web perspective, right-click WeatherforecastProject, and then select New > Web Page to start the New Page wizard.
- For File Name, enter
dataTreeExample.jsp. - Under Basic Templates, select JSP.
- Click Options, select JavaServer Faces.
- Click Close.
- Click Finish.
Figure 24. Create a second JavaServer Page
The dataTreeExample.jsp file is created under WeatherForecastProject/WebContent. After Rational Application Developer opens the page, you are ready to design this page.
- Create a sessionScope variable called stateVar.
- From the Web perspective, click the Page Data tab, which is the lower-left pane, and expand Scripting Variables.
- Right-click sessionScope, and then select New > Session Scope Variable.
- For Variable name, enter
stateVar. - For Type, enter
java.lang.String. - Click OK.
- Create a second sessionScope variable called cityVar:
- Following the same instructions, create another sessionScope variable
called cityVar of type
java.lang.String.
- Following the same instructions, create another sessionScope variable
called cityVar of type
Create Relational Record Lists
You will create two Relational Record lists.
Create a Relational Record List called
stateCitiesSB.
- From the Page Data view, which is the lower-left pane in the Web perspective, right-click Relational Records and select New > Relational Record List.
- For the name, enter
stateCitiesSB. - Click Next.
- If you get the Database Authorization window:
- Click OK
- Click New.
- Select Use an existing connection.
- Select WeatherForecastDB and click Next.
- For User ID, leave it as Weather.
- Leave the Password field blank.
- Click Next.
- Click Finish.
- Under Table, scroll down, expand WEATHER, and select STATES.
- Click Next.
- Click None to deselect the columns. You will notice that only STATE is still selected, because it is the primary key.
- Under Tasks, click the link Add another database table through a relationship.
- Select WEATHER.STATES <- WEATHER.STATESANDCITIES.
Figure 25. Add another database table through a relationship
- Click Finish.
- Expand Relation: STATES_STATESANDCITIES > STATESANDCITIES.
- Ensure that LARGEST_CITY: String is selected.
- Click Finish.
Figure 26. Create the stateCitiesSB Relational Record List
Create another Relational Record List called
tenDayForecastSB
Note:
This time, you will apply a filter to select only the records
that correspond to the selected city and state, as specified by the cityVar
and stateVar sessionScope variables.
- From the Page Data tab, which is the lower-left pane in the Web perspective, right-click Relational Records and select New > Relational Record List.
- Enter
tenDayForecastSBfor the name. - Click Next.
- Under Table, scroll down, expand WEATHER, and select TENDAYFORECAST.
- Click Next.
- Under Tasks, click Filter results.
- Click the plus sign (+).
- For Column, select STATE =.
- Select Variable. and click the ellipses button (with the 3 dots: ...).
- Expand sessionScope and select stateVar.
- Click OK.
- Click OK again.
- Click the + sign again.
- For Column, select CITY =.
- Select Variable and click the button with the 3 dots.
- Expand sessionScope and select cityVar.
- Click OK.
- Click OK.
- Click Close.
- Click Finish.
Figure 27. Apply a filter to Relational Record List
Add the components and Ajax support to the JSP page
Add a table to the JSP page:
- Use the palette to drag a table onto the page under HTML Tags. Specify these values:
- Rows: 2
- Columns: 2
- Table width: 100%
- Border width: 0 pixels
- Click OK.
- In the Properties view for the table, select the table leaf and specify this layout (see Figure 28):
- Align: Left (Make sure the table leaf is still selected.)
- Width: 100%
- Height: 100%
Figure 28. Add a table to the JSP page
- In the Properties view for the cell, with the cursor in the top-left cell, specify these values:
- Horizontal: Left
- Vertical: Top
- Width: 20%
- Wrap lines automatically: Not checked.
- Put the cursor in the top-right cell and specify this format:
- Horizontal: Left
- Vertical: Top
- Width: 80%
- Wrap lines automatically: Not checked.
- Click File > Save All to save your work.
Add two Input-Hidden components to the JSP page:
- Under Enhanced Faces Components, drag an Input-Hidden component into the bottom-left cell.
- Change its ID in Properties to
txtState. - Still under Enhanced Faces Components, drag another Input-Hidden component to the bottom-right cell.
- Change its ID in Properties to
txtCity.
Bind the scripting variables to the Input components
- From the Page Data view, expand Scripting Variables > sessionScope.
- Drag stateVar onto the txtState.
- Drag cityVar onto the txtCity.
- Click File > Save All.
Notes:
- You will use the hidden input components to update the scripting variables, as outlined in the steps that follow.
- Some components, such as Input-Hidden, are hidden, by default on the
palette. To show a hidden component in the palette:
- Right-click inside of the Palette view and select Customize.
- Clear the Hide check box for each component that you want to display on the palette.
Add a Data Tree to the JSP page
Note:
A Data Tree component shows the
cities under each State in a hierarchical list (List of States > State
> City).
- Under Enhanced Faces Components, drag and drop a Data Tree to the top-left cell.
- When you see the dialog box that asks, ";This control requires new project resources. Copy them now?"; click Yes.
- From the Data Tree Properties view (Figure 29), with the odc:tree leaf selected, specify these values:
- Width: 100%
- Height: 100%
Bind the Relational Record List statesCitiesSB to the Data Tree
- From the Page Data tab, expand Relational Records > statesCitiesSB (Service Data Object).
- Drag statesCitiesSB (STATES) onto the Data Tree.
Figure 29. Data Tree Properties view
- From the Data Tree Properties view, click the Tree Node List leaf.
- Under ";Select the nodes to display," select Root.
- For the Label value, enter
List of States. - Under "Select the nodes to display," click the + sign to expand the State List node.
- Select stateCitiesSB, and make sure that STATE is showing in the Label value.
- Expand the stateCitiesSB node.
- Check the STATES_STATESANDCITIES node.
- From the drop-down menu for the Label value, select LARGEST_CITIES.
Figure 30. Data Tree Node List
- Click File > Save All to save your work.
Figure 31 shows how the Data Tree should look.
Figure 31. Data Tree hierarchy
In Figure 31, List of States is the Root node. The
stateCitiesSB node holds the names of the States, and
the STATES_STATESANDCITIES node holds the names of the
Largest Cities at run time. It corresponds to the Relational Record List
stateCitiesSB hierarchy shown in Figure 32.
Figure 32. Relational Record List stateCitiesSB hierarchy
When you click on a city name in the Data Tree, you need to capture its
corresponding State (the parent node), because both the State and City are
accessed as parameters to update the tenDayForecastSB
filter of the Relational Record List by using the variables stateVar
and cityVar.
Note:
To get the parent node, you will add another attribute to the
STATES_STATESANDCITIES node by using the
odc:treeColumnData tag.
Add an attribute to the Data Tree
- From the JSP page, select the Data Tree.
- From the Properties view, make sure that <odc:tree> is selected.
- Check Display tree as a table.
- Add these two labels:
- Label: Column 1, Width: 20
- Label: Column 2, Width: 20
- In the Properties view, click the Tree Node List leaf.
- Under "Select the nodes to display," expand List of States > stateCitiesSB.
- Select the STATES_STATESANDCITIES node (Figure 33).
- Under "Column data," click Add to add an attribute.
- Select STATE, and then press the Tab key.
Figure 33. Add State as an attribute
- From the Properties view, click <odc:tree> again.
- Uncheck Display tree as a table.
- Click Yes in response to this message: "Do you really want to
remove the
TreeTabletag and its content from this table?"
Note:
By unchecking "Display tree as a table,"
the Column data under the Properties view for the STATES_STATESANDCITIES node will
no longer show STATE. However, the attribute tag is hidden and will hold the STATE
value. It will be accessible through JavaScript in the Tree node event handlers
(in this example, it will be the onhighlight event), as
you will see later.
You can verify that the attribute been added by switching to the JSP Source tab. The screen capture in Figure 34 shows that this code was added:
<odc:treeColumnData id=":columnData1": attributeName=":STATE":></odc.treeColumnData> |
Figure 34. Verification that the code was added
- Click File > Save All to save your work.
Add a Panel-Group Box to the JSP page
- Drag a Panel-Group box into the top-right cell. This is the area of the page that will be updated by the Ajax request.
- For Type, select Box, and click OK.
Adjust the Panel Properties
- Select the panel and switch to the Properties view.
- Make sure that hx:panelBox is selected, and specify these values:
- Width: 100%
- Height: 100%
- Vertical: Top
- Horizontal: Left
Add Ajax support to the panel
- Select the panel, and switch to the Properties view (Figure 35).
- Make sure that hx:panelBox is selected.
- Select the Ajax leaf for the
hx:panelBox. - Click the Allow Ajax updates check box.
- Click Submit as the Ajax request type.
Figure 35. Properties view
- Click File > Save All.
Initiate the Ajax request
Use the onhighlight event for the
STATES_STATESANDCITIES node to initiate the Ajax
request:
- From the Data Tree, select the STATES_STATESANDCITIES node.
- Switch to the Quick Edit view (next to the Properties view).
- In the list of events on the left side, select the onhighlight event.
- Click the Use predefined behavior check box.
- Select the action to Invoke Ajax behavior on the specific tag.
- Select box1 as the target.
- For Target, replace
box1withform1:box1and press the Tab key.
Reason for this action:
In Version 7.0 of Rational Application Developer, you must fully qualify the ID of the Panel-Group Box (rather than "box1" use "form1:box1"). Otherwise, the Ajax Submit request would not work correctly.
- Click File > Save All.
- Click anywhere inside of the onhighlight event.
- Add the code shown in Listing 3
Listing 3. Code for onhighlight event
try {
var eobj = thisEvent.eobject;
var obj = document.getElementById("form1:txtCity");
var obj2 = document.getElementById("form1:txtSTATE");
if (obj && obj2) {
obj.value= eobj.eGet('LARGEST_CITY');
obj2.value = eobj.eGet('STATE');
}
}
catch (e) {
alert(e+": "+e.message);
}
|
- Click File > Save All.
The onhighlight event should look like Figure 36.
Figure 36. Code for the
onhighlight event
The onhighlight event is triggered when the user
clicks the tree node. The JavaScript assigns its value (in this example, the
Largest City name), along with the hidden attribute value associated with the node
(in this example, the associated State name) to the two input text components:
txtState and txtCity,
respectively. The sessionScope variables stateVar and cityVar are
updated accordingly.
- Switch to the JSP Source tab and verify the code (also see the screen output in Figure 37):
<odc:treeNodeAttr
className="commonj.sdo.DataObject(DynWDO`stateCitiesSB`STATEANDCITIES)"
id="treenodeattr3" attributeName="LARGEST_CITY">
<odc:behavior event="onhighlight" id="behavior1"
behaviorAction="get" targetAction="form1:box1"
onActionFunction="return func_1(this event);"></odc:behavior>
|
Figure 37. Workaround for the odc:behavior tag
Add a Panels-Tabbed component to the JSP page with two tabs
- Under the Enhanced Faces Components, from the Palette, drag a Panels-Tabbed component onto the Panel Box (box1) on the JSP page.
- Click Tabbed Panel to select it, and then click the Properties view.
- With the odc:tabbedPanel selected, enter these values;
- Width: 100%
- Height: 100%
- Deselect Show Next and Back buttons.
Figure 38. Panels-Tabbed Properties view
- Click the Panel List leaf, and modify the labels for bfpanel1
and bfpanel2 to say
Ten Day ForecastandState Details, respectively (see Figure 39).
Figure 39. Modify bfpanel1 and bfpanel2 in the Panel List leaf
Add the Relational Record List tenDayForecastSB to the Ten Day Forecast tab
- On the JSP page, click the Ten Day Forecast tab to select it.
- From the Page Data tab, expand Relational Records > tenDayForecastSB (Service Data Object).
- Drag tenDayForecastSB (TENDAYFORECAST) onto the Panels-Tabbed area.
- Deselect TENDAYIDX.
- Edit the labels (by clicking inside each label) as in Table 2 and also shown in Figure 40.
Table 2. Edit labels in this order
| Column Name | Label | Control Type |
|---|---|---|
| STATE | State | Output Field |
| CITY | City | Output Field |
| FORECASTDATE | Forecast Date | Output Field |
| FORECAST | Forecast | Output Field |
| TEMPERATURE | Temperature | Output Field |
| PRECIPITATION | Precipitation % | Output Field |
Figure 40. Edited labels
- Click Finish to close the Configure Data Controls window.
Alternate the background color for each row in the table
- Click the leaf Display options.
- Make sure that Row classes show rowClass1, rowClass2.
- Remove the columnClass1 entry from Column classes.
- Select File > Save All.
Your page should look like the screen capture in Figure 41.
Figure 41. Revised page
As explained in the earlier section, you need to turn off caching to get your updated city choices to display.
Turn off the caching for tenDayForecastSB
- Right-click the dataTreeExample.jsp page, and select Edit Page Code to open the dataTreeExample.java file.
- From the Edit drop-down menu, click Edit > Find/Replace.
- For Find, enter
List getTenDayForecastSB(), and then click Find. - Use a comment to negate the
if (tenDayForecastSB == null) {statement. This will turn the caching off by forcing thedoTenDayForecastSBFetchAction()to run every time. ThegetTenDayForecastSB()action should then look like Listing 4.
Listing 4. Turn off the caching for tenDayForecastSB
public List getTenDayForecastSB() {
// if (tenDayForecastSB == null) {
doTenDayForecastSBFetchAction();
// }
return tenDayForecastSB;
}
|
- Click Close to close Find/Replace.
- Close the DataTreeExample.java.
- Save your work by clicking File > Save All.
Important:
During the process of designing the JSP page, the Data
Tree might lose its configuration. Always ensure that the Tree Node List for the
Data Tree reflects what you previously configured, and save your work.
- Under WeatherForecastProject/WebContent, right-click dataTreeExample.jsp and select Run As > Run on Server.
- If the window to Disconnect ForecastWeatherDB appears, click Finish to close it.
- Wait for the server to start and for the dataTreeExample.faces page to display.
- Click the Data Tree to expand Alabama.
- Click Birmingham. The data table displays the 10-day forecast for that city.
We will populate the State Details tab with details about the selected State
You will perform these two primary tasks:
- Create a Relational Record List that includes both STATES and STATESANDCITIES tables. You will filter the information based on the selected State.
- Add Java code to the dataTreeExample.jsp page code to access the Relational Record List elements.
Tip:
This article shows you how to programmatically access data elements from a
Relational Record List. However, you can use a Relational Record as an alternative
to display the information without any coding.
- To begin, stop the server: In the Servers view, right-click WebSphere Application Server v6.1 and select Stop.
- Next, create a Relational Record List called
stateDetailsSB. - From the Page Data view, which is the lower-left pane in the Web perspective, right-click Relational Records and select New > Relational Record List.
- For the name, enter
stateDetailsSB. - Click Next.
- For User ID, leave it as Weather.
- Leave the Password blank.
- Click OK.
- Under Table, scroll down, expand WEATHER, and select STATES.
- Click Next.
- Under Tasks, click the link for Add another database table through a relationship.
- Select WEATHER.STATES <- WEATHER.STATESANDCITIES (see Figure 42).
Figure 42. Choose a relationship
- Click Next.
- Then click Finish.
Note:
Because you did not explicitly name the relationship in this
example, Rational Application Developer automatically provided the name:
STATES_STATESANDCITIES. If you want to rename this relationship, simply select it,
right-click and from the drop-down menu, select Rename Relationship. The
name of the relationship will appear in the stateDetailsSB.xml file under the
relationship tag name=:
<relationships childKey=";//@tables.1/@foreignKeys.0"; parentKey=";//@tables.0/@primaryKey"; name=";STATES_STATESANDCITIES"; exclusive=";false";/> |
You can find the stateDetailsSB.xml file under WebContent/WEB-INF/wdo.
- Now, under Tasks, click Filter results.
- Select STATES and click the + sign.
- Under Task, click Filter results.
- Click the + sign.
- Select STATES and, from the drop-down menu for Column, select the equal sign (=).
- Select Variable and click the button with the 3 dots (. . . ).
- Expand sessionScope and select stateVar.
- Click OK.
- Click OK again.
- Click Close.
- Then click Finish.
Add the Java code to dataTreeExample.jsp page
- Right-click the dataTreeExample.jsp page, and select Edit Page Code to open the dataTreeExample.java file.
- Enter the code shown in Listing 5 at the end of the
getSDOConnectionWrapper()method.
Listing 5. Code to add to the dataTreeExample.jsp page
:
:
:
return SDOConnectionWrapper;
}
:
:
// Add this code below
public String getStateInfo() {
String stateInfo = "";
List stateList = getStateDetailsSB();
if (stateList.size() != 0) {
try {
DataObject graph =
getStateDetailsSBMediator().getGraph(getStateDetailsSBParameters());
DataObject states = graph.getDataObject("STATES.0");
String strState = states.getString("STATE");
String strStateNickName = states.getString("STATE_NICKNAME");
String strCapital = states.getString("CAPITAL");
String strEstimatedPoplulation = states.getString("ESTIMATED_2006_POPULATION");
String strLargestCity =
states.getDataObject("STATES_STATESANDCITIES").getString("LARGEST_CITY");
stateInfo = "The nick name for the state of " + strState + " is " + strStateNickName + ".
The estimated 2006 population is " + strEstimatedPoplulation + ".
Its largest city is " + strLargestCity + " and its capital is " + strCapital + ".";
} catch (Throwable e) {
logException(e);
}
}
return stateInfo;
}
|
- Save your work: File > Save All.
Notes:
- The code above is an example showing you how to access a DataObject within
another DataObject. The Relational Record List
stateDetailsSBhas a filter that selects records only belonging to the specified state defined in stateVar. The codegetStateInfo()accesses the DataObject STATES using the code"DataObject states = graph.getDataObject("STATES.0");". This statement provides access to the various elements in the STATES (for example, CAPITAL) by calling states.getString("CAPITAL"). However, you also need to access the name of the largest city for the selected state. It happened to be that "LARGEST_CITY" is an element that belongs to STATESANDCITIES.
- DataObjects may contain other DataOjbects. In this example, the stateDetailsSB
contains both STATES and STATESANDCITIES that are related through
STATES_STATESANDCITIES relationship. The code
";states.getDataObject(";STATES_STATESANDCITIES";).getString(";LARGEST_CITY";));";accesses";LARGEST_CITY";, which is an element in the second DataObject.
- Accessing the elements is case-sensitive. To view the
stateDetailsSBelements, open the stateDetailsSB.xml file under WebContent/WEB-INF/wdo.
Turn off caching for Relational Record List stateDetailsSB
- From the Edit drop-down menu on the JSP page, click Edit > Find/Replace.
- For Find, enter
List getStateDetailsSB(), and then click Find. - Use a comment to negate the
if (stateDetailsSB == null) {statement. This will turn the caching off by forcing thedoStateDetailsSBFetchAction()to run every time.
The getStateDetailsSB() action should now look like
Listing 6.
Listing 6. Edit the page code to turn off caching
public List getStateDetailsSB() {
// if (stateDetailsSB == null) {
doStateDetailsSBFetchAction();
// }
return stateDetailsSB;
}
|
- Click Close to close Find/Replace.
- Close the DataTreeExample.java file.
- Select File > Save All to save your work.
Add stateInfo to the JSP page
- Click the State Detail tab.
- From the Page Data view, expand Page Bean.
- Drag stateInfo (java.lang.String) onto the State Detail tab.
- Under Label, delete StateInfo (make it blank).
Figure 43. Add
stateInfo to the JSP page
- Click Finish.
- Click File > Save All.
Note:
As mentioned previously, during the process of designing the
JSP page, the Data Tree might lose its configuration. Always ensure that the Tree
Node List for the Data Tree reflects what configured previously, and save your
work.
- Under WeatherForecastProject/WebContent, right-click dataTreeExample.jsp, and select Run As > Run on Server.
- Click Finish to disconnect WeatherForecastDB.
- Wait for the server to start and for the dataTreeExample.faces page to display.
When the page is displayed:
- Click the Data Tree to select a city. Notice that the 10-day forecast for the city is now displayed.
- Click the State Details tab. You will see the state details, including the name of the largest city.
This article explained how to use various JSF components in an Ajax environment. By following this step-by-step exercise and demonstration, you have learned how to design an application that uses Combo Box, Data Tree, Relational Record Lists or SDOs, Panels-Box, and Panels-Tabbed components. You also learned a technique for accessing elements from a DataObject that contains another DataObject.
See Resources to learn more about the various technologies used in this article.
The author thanks Yury Kats for his technical input. Yury is a developer on the IBM Rational Application Developer team, working with JSF implementation, components, and tooling. He is the author of several developerWorks articles.
| Description | Name | Size | Download method |
|---|---|---|---|
| Database used in this example | SolutionWeatherForecastAjaxProject.zip | 6028KB | HTTP |
Information about download methods
Learn
- For articles on Service Data Objects (SDOs),
check these developerWorks articles:
- Enabling a service-oriented architecture with SDO and the JDBC Data Access Service by Robert Peterson, WebSphere Enablement, IBM (IBM WebSphere Developer Technical Journal, October 2005).
- Introduction to Service Data Objects by Bertrand Portier, IT Architect, IBM, and Frank Budinsky, Eclipse EMF Project Lead, IBM (IBM developerWorks, September 2004).
- Simplify and unify data with a Service Data Objects architecture by Jean-Louis Marechaux, IT Architect, IBM (developerWorks, September 2005).
- For an excellent introduction to using Ajax
with IBM Rational Application Developer, read
JSF
and Ajax: Web 2.0 application made easy with Rational Application Developer
V7
by Yury Kats, Advisory Software Engineer, IBM (developerWorks, December 2006).
- For information about the Java™ Widget
Library (JWL) Tree component (not updated), check
The
JWL Tree component: The hierarchical organisation of data stored on the client
by Breffni Coffey, Software Engineer, IBM (developerWorks, December 2005).
- For JavaServer™ Faces basics, check these
resources:
- Create Web-based user interfaces by Ron Ben-Natan (requires user ID and password).
- JSF for nonbelievers: The JSF application lifecycle by Richard Hightower, CTO, ArcMind (developerWorks, March 2005).
- The JavaServer Faces (JSF) components reference page in the Rational Application Developer Information Center.
- For basic information about how to create
databases using Rational Application Developer, review
Hello
World (updated): Rational Application Developer V7 Create Java, Web service,
and database applications
by Jane Fung, Software Developer, IBM Toronto Lab (requires user ID and password).
- To learn more about Rational Application
Developer, check IBM Redbooks® for the
Rational
Application Developer V7 Programming Guide,
SG24-7501-00. To learn more about JSF and Ajax, specifically, see Chapter 14.
- Visit the
Rational software area on developerWorks
for technical resources and best practices for Rational Software Delivery Platform
products.
- Explore
Rational computer-based, Web-based, and instructor-led online courses.
Hone your skills and learn more about Rational tools with these courses, which
range from introductory to advanced. The courses on this catalog are available for
purchase through computer-based training or Web-based training. Additionally, some
"Getting Started" courses are available free of charge.
- Subscribe to the
Rational Edge newsletter
for articles on the concepts behind effective software development.
- Subscribe to the
IBM developerWorks newsletter,
a weekly update on the best of developerWorks tutorials, articles, downloads,
community activities, webcasts and events.
- Browse the
technology bookstore
for books on these and other technical topics.
Get products and technologies
- Download a free trial version of Rational Application Developer.
- Download
trial versions of IBM Rational software.
- Download these
IBM product evaluation versions
and get your hands on application development tools and middleware products from
DB2®, Lotus®, Tivoli®, and WebSphere®.
Discuss
- Check out
developerWorks blogs and
get involved in the
developerWorks community.
-
Rational Software Architect, Data Architect, Software Modeler, Application Developer and Web Developer forum: Ask questions about Rational Application Developer.
Comments (Undergoing maintenance)





