Dynamically Building a Tree from Database Data

Here is a mini tutorial that teaches you how to dynamically build a tree structure from data in a database. You populate the first-level nodes in the Tree with names from a database and the second-level nodes with the trip dates for that person.

Notes: Due to cookie problems, it is hard to tell which node the user selects. See http://blogs.sun.com/divas/entry/workaround_for_dynamic_trees for a workaround

Events related to tree node selection do not work correctly in portlets because the Tree component uses cookies to pass the selected node id back and forth, and cookies are not correctly handled by the portlet container.

Designing the Home Page

You begin by building a home page that includes the Tree component and the TRIP database table. The following figure shows the page.

Figure 1: Page Design
Figure 1: Page Design
  1. Create a new project and name it DatabaseTree.

  2. From the Basic section of the Palette, drag a Tree component onto the Page, type Travel Information, and press Enter. In the Properties window, set the id property to displayTree and the clientSide property to True.

    When clientSide is True, every child node (expanded or not) is sent to the client, but is not made visible unless the parent node is expanded. When clientSide is False, only the child nodes of the expanded parent nodes are rendered.

  3. Select Tree Node 1, right-click, and choose Delete from the pop-up menu.

    For this application, you do not need the initial tree node that the IDE creates because you are populating the tree programmatically. If you do not remove the node, the values set in the JSP tag attributes take precedence over the runtime settings, and the page displays the node.

  4. Drag a Message Group component from the Palette onto an out-of-the-way place on the page, such as the upper-right corner of the page.

Connecting to the Database

Next, you connect the page with a database table in the Travel data source. You then use the Query Editor to modify the SQL query used to retrieve the data so that the traveler names appear in alphabetical order and the travel dates appear in chronological order.

  1. Open the Servers window and ensure that the Bundled Database Server is running.

    The node's status icon and tooltip indicate whether the server is running. If the Bundled Database Server is not running, right-click the Bundled Database Server node and choose Start Bundled Database from the pop-up menu.

  2. In the Servers Window, expand Data Sources > Travel > Tables. Drag the TRIP node onto the Visual Designer.

    The Outline window shows a tripDataProvider node in the Page1 section and a tripRowSet node in the SessionBean1 section.

  3. In the Outline window, right-click the tripRowSet node and choose Edit SQL Statement.

    The Query Editor appears in the editing area, with a a TRIP table diagram.

  4. From the Servers window, drag the Travel > Tables > PERSON node and drop it next to the Trip table diagram in the Query Editor, as shown in Figure 2.

    Another table diagram appears with a link, or join, between the two table diagrams.

  5. In the PERSON table, clear the checkbox for PERSONID.

  6. In the Design Grid of the Query Editor, find the NAME row for the TRAVEL.PERSON table. Click in the Sort Type cell and choose Ascending from the drop-down list.

    This action sorts the names in the database table alphabetically by last name.

  7. Find the DEPDATE row for the TRAVEL.TRIP table. Click in the Sort Type cell and choose Ascending from the drop-down list.

    This action sorts the trip dates from earliest date to latest date. The following figure shows the Query Editor.
    Figure 2: Query Editor
    Figure 2 : Query Editor

Building the Tree From the Database Table

Now you add code to the prerender() method to dynamically build the Tree component from the TRIP and PERSON database tables.

  1. Open Page1 in the Java Editor and scroll to the prerender method. Replace the body of the prerender method with the following code shown in bold.
    Code Sample 1: prerender method for Page1
       public void prerender() {
             try {
                // Set up the variables we will need
                Integer currentPersonId = new Integer(-1);
                // If nbrChildren is not 0 then this is a
                // postback and we have our tree already
                int nbrChildren = displayTree.getChildCount();
                if (nbrChildren == 0) {
                    // List of outer (person) nodes
                    List outerChildren = displayTree.getChildren();
                    // Erase previous contents
                    // List of inner (trip) nodes
                    List innerChildren = null;
                    // Execute the SQL query
                    // Iterate over the rows of the result set.
                    // Every time we encounter a new person, add first level node.
                    // Add second level trip nodes to the parent person node.
                    boolean hasNext = tripDataProvider.cursorFirst();
                    while (hasNext) {
                        Integer newPersonId =
                                (Integer) tripDataProvider.getValue(
                        if (!newPersonId.equals(currentPersonId)) {
                            currentPersonId = newPersonId;
                            TreeNode personNode = new TreeNode();
                            personNode.setId("person" + newPersonId.toString());
                            innerChildren = personNode.getChildren();
                        // Create a new trip node
                        TreeNode tripNode = new TreeNode();
                        tripNode.setId("trip" +
                        // Set "action" property to use for navigation
                                ("#{Page1.tripNode_action}", null));
                        hasNext = tripDataProvider.cursorNext();
            } catch (Exception ex) {
                log("Exception gathering tree data", ex);
                error("Exception gathering tree data: " + ex);
    This code reads the trip records, which are ordered by the personId. For every personId, the code creates a new level-one node in the Tree. The code then creates a level-two node (nested node) for every trip associated with that personId.

  2. Place the cursor in the Java Editor and press Alt-Shift-F to fix the class not found errors. In the Fix Imports dialog box, ensure that java.util.List appears in the Fully Qualified Name field and click OK.

  3. Run the project.

    The web browser opens and displays a Tree component with each first-level node showing the name of a person. The top-level node is expanded to show the travel dates for that person. Note that the names appear alphabetically by last name and the dates appear in chronological order, as shown in the following figure. Continue exploring the application by expanding and contracting the first-level nodes in the Tree.
    Figure 3: Dynamic Tree Node
    Figure 3: Dynamic Tree Node

What am I missing here? There isn't a tree component in the Sun JSF API/IMPL? What tree is being used?

Posted by Todd on September 18, 2006 at 02:49 AM PDT #

The Sun Java Studio Creator IDE provides, in addition to the reference implementation of the JSF components, a set of enhanced components, including a Tree. To learn more, go here: http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/about_components.html There are also AJAX components that you can add on, as described here: http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/ajaximportcomponents.html

Posted by diva#2 on September 18, 2006 at 02:54 AM PDT #

In prerender() Code Sample:

int nbrChildren = displayTree.getChildCount();

Where is displayTree declared?
I get a compilation error.

Posted by Alexandra on June 26, 2008 at 11:58 PM PDT #


Step 2 says: From the Basic section of the Palette, drag a Tree component onto the Page, type Travel Information, and press Enter. In the Properties window, set the id property to displayTree and the clientSide property to True.

When you set the id property to displayTree, that changes the name of the tree object to displayTree.

Posted by diva #2 on June 30, 2008 at 02:48 AM PDT #

Thanks Alexandra!

Posted by Guillermo on September 07, 2008 at 12:51 PM PDT #

Post a Comment:
Comments are closed for this entry.



« April 2014