9
Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html 1 sur 9 28/04/2008 12:16 Search: HOME / Docs & Support / NetBeans 6.0 / Web Application Documentation Building a Tree From Database Data Contributed by the NetBeans Tutorials Team December 2007 [Revision number: V6.0] This tutorial shows you how to dynamically build a tree structure from data in a database. Using NetBeans IDE 6.0, you build a two-page application, the first page of which includes a JSF 1.2 (Woodstock) Tree component. You populate the first-level nodes in the Tree with names from a database, and the second-level nodes with the trips for that person. The trip nodes are links to a second page, which displays the details for that trip. Contents - Designing the Home Page - Connecting to the Database - Building the Tree From the Database Table - Adding the Detail Page - Adding Code - Defining Page Navigation - Doing More: Binding Action Methods to Tree Nodes - A Note About the Selection of Tree Nodes This tutorial works with the following technologies and resources JavaServer Faces Components/ Java EE Platform 1.2 with Java EE 5* 1.1 with J2EE 1.4 Travel Database Required * To take advantage of NetBeans IDE 6.0's Java EE 5 capabilities, use an application server that is fully compliant with the Java EE 5 specification, such as the Sun Java System Application Server 9 (GlassFish Project). This tutorial has been tailored for use with the GlassFish V2 application server. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes . 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 Create a new Visual Web JSF application project, name it DatabaseTree, and enable the Visual Web JavaServer Faces framework. 1. 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. 2. 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. 3. Drag a Message Group component from the Palette onto an out-of-the-way place on the page, such as the 4. Documentation Basic Java Programming Java GUIs Web Applications Java EE Applications Mobile Applications SOA Applications UML Modelling Ruby Applications C/C++ Applications NetBeans Modules and Rich-Client Applications Sample Applications Demos and Screencasts Training Web Component Development with Servlet and JSP Technologies Developing JavaServer Faces Components with Ajax All Sun Microsystem Training Courses Support FAQs Sun Microsystems Support Plans More Contribute Documentation! Docs for Earlier Releases Choose page language

Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Embed Size (px)

DESCRIPTION

exemple de construction d'un arbre avec betbeans

Citation preview

Page 1: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

1 sur 9 28/04/2008 12:16

Search:

HOME / Docs & Support / NetBeans 6.0 / Web Application Documentation

Building a Tree From Database Data

Contributed by the NetBeans Tutorials Team

December 2007 [Revision number: V6.0]

This tutorial shows you how to dynamically build a tree structure from data in a database. Using NetBeans IDE 6.0, you build a two-page application, the first page of which includes a JSF 1.2 (Woodstock) Tree component. You populate the first-level nodes in the Tree with names from a database, and the second-level nodes with the trips forthat person. The trip nodes are links to a second page, which displays the details for that trip.

Contents

- Designing the Home Page

- Connecting to the Database

- Building the Tree From the Database Table

- Adding the Detail Page

- Adding Code

- Defining Page Navigation

- Doing More: Binding Action Methods to Tree Nodes

- A Note About the Selection of Tree Nodes

This tutorial works with the following technologies and resources

JavaServer Faces Components/Java EE Platform

1.2 with Java EE 5*

1.1 with J2EE 1.4

Travel Database Required

* To take advantage of NetBeans IDE 6.0's Java EE 5 capabilities, use an application server that is fully compliant

with the Java EE 5 specification, such as the Sun Java System Application Server 9 (GlassFish Project).

This tutorial has been tailored for use with the GlassFish V2 application server. If you are using a different server,

consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the

supported servers and Java EE platform, see the Release Notes.

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

Create a new Visual Web JSF application project, name it DatabaseTree, and enable the Visual Web

JavaServer Faces framework.

1.

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.

2.

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.

3.

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

Documentation

Basic Java Programming

Java GUIs

Web Applications

Java EE Applications

Mobile Applications

SOA Applications

UML Modelling

Ruby Applications

C/C++ Applications

NetBeans Modules and

Rich-Client Applications

Sample Applications

Demos and Screencasts

Training

Web Component Development

with Servlet and JSP

Technologies

Developing JavaServer Faces

Components with Ajax

All Sun Microsystem Training

Courses

Support

FAQs

Sun Microsystems Support Plans

More

Contribute Documentation!

Docs for Earlier Releases

Choose page language

Page 2: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

2 sur 9 28/04/2008 12:16

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.

Open the Services window, expand the Databases node and verify that the Travel database is connected.

If the jdbc node for the TRAVEL database's badge is broken and you cannot expand the node, the IDE is not

connected to the database. To connect to the TRAVEL database, right-click the jdbc node for TRAVEL and

choose Connect from the pop-up menu. If the Connect dialog box appears, enter travel for the Password,

select Remember Password During This Session, and click OK.

Note: If you are using Apache Tomcat, copy the derbyClient.jar file to the

<tomcat_install>/common/lib directory before you try to connect to the database.

1.

Expand the jdbc node for the TRAVEL database, then expand the Tables node as seen in the following figure.

Figure 2: Travel Database

2.

Drag the TRIP node onto the Visual Designer.

The Navigator window shows a tripDataProvider node in the Page1 section and a tripRowSet node in the

SessionBean1 section.

3.

In the Navigator window, expand the SessionBean1 node, right-click the tripRowSet node, and choose Edit SQL

Statement.

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

4.

From the Services window, drag the Travel > Tables > PERSON node and drop it next to the Trip table diagram

in the Query Editor, as shown in Figure 3.

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.

8.

Page 3: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

3 sur 9 28/04/2008 12:16

Figure 3: Query Editor

Building the Tree From the Database Table

Now you add a request bean property to store information for use by both pages in the application. You then add code

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

Open Page1 so that the Navigator window is visible. In the Navigator window, right-click the RequestBean1

node and choose Edit Java Source.

1.

Under the constructor public class RequestBean1 extends AbstractRequestBean, declare the

property as follows:

private Integer personId;

2.

Right-click in the Java Editor and select Refactor > Encapsulate Fields.3.

In the Encapsulate Fields dialog, check the boxes to create getter and setter methods as shown in the figure

below. Make sure that the variable declaration for field visibility is private and accessor visibility public, and

click Refactor.

Figure 4: Text File Upload

4.

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:

5.

Page 4: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

4 sur 9 28/04/2008 12:16

Code Sample 1: prerender Method for Page1

public void prerender() { // If the Request Bean's personId is set, t hen // we just came back from the Trip page // and had displayed a selected trip. // We use the personId later to determine w hether // to expand a person's node Integer expandedPersonId = getRequestBean1( ).getPersonId(); 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 alread y int nbrChildren = displayTree.getChildC ount();

if (nbrChildren == 0) { // List of outer (person) nodes List outerChildren = displayTree.ge tChildren(); // Erase previous contents outerChildren.clear(); // List of inner (trip) nodes List innerChildren = null; // Execute the SQL query tripDataProvider.refresh(); // Iterate over the rows of the res ult set. // Every time we encounter a new pe rson, add first level node. // Add second level trip nodes to t he parent person node. boolean hasNext = tripDataProvider. cursorFirst(); while (hasNext) { Integer newPersonId = (Integer) tripDataProvi der.getValue( "TRIP.PERSONID"); if (!newPersonId.equals(current PersonId)) { currentPersonId = newPerson Id; TreeNode personNode = new T reeNode(); personNode.setId("person" + newPersonId.toString()); personNode.setText( (String)tripDataPro vider.getValue( "PERSON.NAME")); // If the request bean pass ed a person id, // expand that person's nod e personNode.setExpanded(newP ersonId.equals (expandedPersonId)) ; outerChildren.add(personNod e); innerChildren = personNode. getChildren(); }

// Create a new trip node TreeNode tripNode = new TreeNod e(); tripNode.setId("trip" + tripDataProvider.getVal ue("TRIP.TRIPID").toString()); tripNode.setText( tripDataProvider.getVal ue("TRIP.DEPDATE").toString()); tripNode.setUrl("/faces/Trip.js p?tripId=" + tripDataProvider.getVal ue("TRIP.TRIPID").toString()); innerChildren.add(tripNode); hasNext = tripDataProvider.curs orNext(); } }

} 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. Finally, the code binds the second-level trip node to the tripNode_action method, which

you create later in this section.

Right-click in the source and choose Fix Imports from the popup menu to fix the class not found errors. In the

Fix All Imports dialog box, ensure that java.util.List appears in the List field and click OK.

6.

Run the project.

The web browser opens and displays a Tree component with each first-level node showing the name of a

person, as shown in the following figure. Expand a node 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. In the next section, you add code to navigate to a second page when the user clicks a trip

node. The second page shows the details for the trip that the user selected.

7.

Page 5: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

5 sur 9 28/04/2008 12:16

Figure 5: Dynamic Tree Node

Adding the Detail Page

Here you add a second page to the application, as shown in the following figure. This page uses a Property Sheet

component to dynamically show the details of the trip that the user selected on the first page.

Figure 6: Detail Page

Open the Projects window, right-click the Web Pages node and choose New > Visual Web JSF Page from the

pop-up menu. Name the new page Trip.

1.

Open the Services Window and drag the Tables > TRIP node onto the Visual Designer for the Trip page.

The Navigator window shows a tripDataProvider node in the Trip section and a tripRowSet1 node in the

SessionBean1 section.

2.

In the Navigator Window, right-click the tripRowSet1 node and choose Edit SQL Statement.3.

In the Design Grid of the Query Editor, right-click any cell in the TRIPID row and choose Add Query Criteria. In

the dialog box, set the Comparison drop-down list to =Equals and select the Parameter radio button. Click OK.

You see =? in the Criteria column for TRIPID, which adds the following WHERE clause in the SQL query.

WHERE TRAVEL.TRIP.TRIPID = ?

4.

Open the Trip Page in the Visual Designer. From the Basic section of the Palette, drag a Hyperlink component

on the page, type Home, and press Enter.

5.

In the Properties window for the Hyperlink component, click the ellipsis button for the action property,

select hyperlink1_action from the drop-down list, and click OK.

The IDE adds the hyperlink1_action event handler to the Java source.

6.

Drag a Message Group component from the Palette to the page and place it to the right of the Hyperlink

component.

7.

From the Layout section of the Palette, drag a Property Sheet component onto the page. Place it below the

Hyperlink component.

The Property Sheet component provides a container for laying out the trip information. The Property Sheet

component contains a Property Sheet Section, which in turn contains a Property component.

8.

Page 6: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

6 sur 9 28/04/2008 12:16

Select Property Sheet Section 1. In the Properties window, set the label property to Trip Details.

Note: If the project source level is set to 1.4, the property sheet label is not updated after you change it in the

Properties window.

9.

In the Outline window, expand propertySheet1 > section1 and then select the property1 node. In the

Properties window, set the label property to Departure Date: and press Enter.

10.

In the Outline window, select section1, right-click, and choose Add Property from the pop-up menu. In the

Properties window, set the label property to Departure City: and press Enter.

11.

Drag a Static Text component from the Palette and drop it on the property1 node in the Outline window.

The Static Text becomes a subnode of property1. The Static Text also appears in the Visual Designer.

12.

Right-click the Static Text component and choose Bind to Data from the pop-up menu. If necessary, click the

Bind to Data Provider tab to bring that tab to the front. In the dialog box, select TRIP.DEPDATE in the Data

field, as shown in the following figure, and click OK.

The current date appears in the Static Text component in the Visual Designer.

Figure 7: Bind to Data Dialog Box

13.

Add a Static Text component to property2. Bind the Static Text to TRIP.DEPCITY.14.

Adding Code

Here you add code so that the Trip page can get the tripid stored in Page1 and Page1 can get the personid stored in

the Trip page.

Open the Trip page in the Java Editor and scroll to the prerender method. Add the following code (shown in

bold) so that the method gets the tripId that was stored in Page1.

Code Sample 2: prerender Method for Trip page

public void prerender() {

// Get the person id from the request parameters String parmTripId = (String) getExternalContext().getRequestParameterMap ().get("tripId");

if (parmTripId != null) { Integer tripId = new Integer(parmTripId ); try { getSessionBean1().getTripRowSet1(). setObject(1, tripId); tripDataProvider.refresh(); } catch (Exception e) { error("Cannot display trip " + trip Id); log("Cannot display trip " + tripId , e); } }else { error("No trip id specified."); } }

The setObject method sets the trip query's first argument to the tripId. That is, the method replaces the ? in

the query with the tripId. This query only has one argument so you only have to call setObject once. The call

to tripDataProvider1.refresh() calls CachedRowSet.release() and resets the

CachedRowSetDataProvider's cursor. It does not execute the CachesRowSet at this time.

1.

Scroll to the hyperlink1_action method. Add the following code (shown in bold) to pass the personId to

Page1:

2.

Page 7: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

7 sur 9 28/04/2008 12:16

Code Sample 3: hyperlink1_action Method for Trip Page

public String hyperlink1_action() { getRequestBean1().setPersonId( (Integer)tripDataProvider.getValue( "trip.personid")); return null; }

Defining Page Navigation

Finally, you specify the navigation from the Tree nodes on Page1 to the Trip page.

RIght-click anywhere in the Design view of the Visual Designer and choose Page Navigation.1.

Click the connector port on the Page1.jsp icon and drag a connector to the Trip.jsp icon.2.

Expand the Trip.jsp icon and drag a connector from the Hyperlink component to the Page1.jsp icon. The

following figure shows the page navigation setup.

Figure 8 : Page Navigation

3.

Run the application. On the Home page, expand an traveler name and click a trip date.

The Trip page opens with details for that trip, as shown in the following figure.

Figure 9: Detail Page at Runtime

4.

On the Trip page, click the Home link. Note that on the Home page, the first-level node of the last trip you

selected is still expanded.

5.

Continue exploring the application by expanding and contracting the first-level Tree nodes and clicking the trip

dates.

6.

Doing More: Binding Action Methods to Tree Nodes

If you are using the JavaServer Faces 1.2 Tree component (that is, the Java EE Version setting for your project is the

Java EE 5 platform), then you can bind action methods to the tree nodes, and, in the action method, call the Tree

component's getSelected() method to determine which node was clicked, as illustrated in the following steps.

Add a tripId property to the Request Bean of type Integer.1.

Add the following method to the Java source for Page1:

Code Sample 4: tripNode_action Method for Page1

2.

Page 8: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

8 sur 9 28/04/2008 12:16

public String tripNode_action() { // Get the id of the currently selected tree node String nodeId = displayTree.getSelected(); // Find the tree node component with the giv en id TreeNode selectedNode = (TreeNode) this.getForm1().findCompo nentById(nodeId); try { // Node's id property is composed of "tr ip" plus the trip id // Extract the trip id and save it for t he next page Integer tripId = Integer.valueOf(selecte dNode.getId().substring(4)); getRequestBean1().setTripId(tripId); } catch (Exception e) { error("Can't convert node id to Integer: " + selectedNode.getId().substring(4 )); return null; } return "case1"; }

In the page 1 prerender method, replace the following code with the code in Code Sample 5.

tripNode.setUrl("/faces/Trip.jsp?tripId=" +

tripDataProvider.getValue("TRIP.TRIPID").toString());

Code Sample 5: Tweaking the prerender Method

ExpressionFactory exFactory = getApplication().getExpressionFactory(); ELContext elContext = getFacesContext().getELContext(); tripNode.setActionExpression( exFactory.createMethodExpression( elContext, "#{Page1.tripNode_action}", String.class, new Class<?>[0]));

3.

Press Alt-Shift-F to fix imports.4.

In the Trip page prerender() method, replace the body with the following code:

Code Sample 6: prerender Method for Trip Page

public void prerender() { Integer tripId = getRequestBean1().getTripId(); try { getSessionBean1().getTripRowSet1().s etObject(1, tripId); tripDataProvider1.refresh(); } catch (Exception e) { error("Cannot display trip " + tripI d); log("Cannot display trip " + tripId, e); } }

5.

Run the application.6.

A Note About the Selection of Tree Nodes

If your project is a J2EE 1.4 project, here are some things you should know about the selection of Tree nodes:

The JavaServer Faces 1.1 Tree component cannot use the getSelected method or the

getCookieSelectedTreeNode method to determine which node was selected. If users have their browser

cookies turned off, these methods will not return the correct values. Also, for browsers with the cookies turned

on, the cookie might return the wrong value the first time the user visits a page and clicks a node. If there are

leftover cookies from a previous visit, the previously selected value might be returned. Because the JavaServer

Faces 1.2 version of the Tree component does not use cookies to save the selected value, this is not an issue

for the 1.2 version.

The highlighting of Tree nodes is not cleared between sessions. If you run the program in this tutorial more

than once, the node that was selected in the last session is highlighted in the new session when the page first

opens. This problem is due to the use of cookies to transmit the selected node ID.

Summary

In this tutorial, you built a tree structure from data in a database. You built a two-page application, the first page of

which included a Tree component. You populated the first-level nodes in the Tree with names from a database, and

the second-level nodes with the trips for that person. You linked each trip on the first page to a second page, which

displayed the details for that trip.

See Also

Using Databound Components to Access a Database

Page 9: Building a Tree From a Database Data - NetBeans IDE 6 0 Tutorial

Building a Tree From a Database Data - NetBeans IDE 6.0 Tutorial http://www.netbeans.org/kb/60/web/databasetree.html

9 sur 9 28/04/2008 12:16

Bookmark this page

Send Us Your Feedback

Shop SiteMap About Us Contact Legal By use of this website, you agree to the NetBeans Policies and Terms of Use

Performing Inserts, Updates, and Deletes

>> More NetBeans Web Application Documentation

This page was last modified: December 3, 2007

Companion Projects:

Powered by