Sie sind auf Seite 1von 13

Using Databound Components to Access Databases

April 2006 [Revision number: V2.1-1]


Copyright 2006 Sun Microsystems, Inc.

In this tutorial, you use the Sun Java Studio Creator integrated development environment (IDE) to create and deploy a web application that displays master-detail data from a database that is bundled with the IDE. In the application, you select a person from a drop-down list, and the application displays a table that shows all the trip records for that person. Contents - Creating a Page That Includes a Drop Down List Component - Connecting the Component to a Database - Adding a Table Component - Modifying the SQL Query - Controlling the Rows That Are Displayed Before you use this tutorial, you must have the Java Studio Creator IDE installed on your system. Familiarize yourself with the basic parts of the IDE. Getting Started With Java Studio Creator is a useful introduction to the Sun Java Studio Creator development environment. NOTE: This tutorial uses the database software that is bundled with the IDE. To learn how to use other types of database software with the IDE, see the Creating Database Server Types and Data Sources tutorial.

Creating a Page That Includes a Drop Down List Component


In this tutorial, you build a Travel Center application as shown in the following figure.

Figure 1: Travel Center Web Application You begin by creating the home page and adding a Drop Down List component to the page.

1. Create a new project and name it DataboundComponents. The IDE creates a default home page named Page1 and displays the page in the Visual Designer. 2. If the Basic node in the Palette window is not expanded, expand it now. 3. Drag a Label component onto the left side of the page, type Select Name: and press Enter. 4. Drag a Drop Down List component to the right of the Label component. 5. In the Properties window, change the id to personIdDD. 6. Ctrl-Shift-Drag from the Drop Down List component to the Label component to associate the two components. The for property for the Label component is now set to personIdDD. 7. Drag a Message Group component from the Palette window onto an out-of-the-way place on the page, such as the upper-right corner of the page. This component is useful for diagnosing programming errors. You can make diagnostic messages appear in this component by calling the info(String), error(String), warn(String), or fatal (String) method. The Message Group component displays the value of the String argument. In addition, messages about runtime errors, validation errors, and conversion errors appear in this component by default.

Connecting the Component to a Database


Next, you use the Bind to Data dialog box, shown in the following figure, to configure the Drop Down List component to get items from a database table.

Figure 2: Bind to Data Dialog Box for a Drop Down List Component There are two layers between the component and the database table: the RowSet layer and the Data Provider layer. The RowSet layer makes the connection to the database, executes the queries, and manages the result set. The Data Provider layer provides a common interface for accessing many types of data, from rowsets, to Array objects, to

Enterprise JavaBeans objects. Typically, the only time that you work with the RowSet object is when you need to set query parameters. In most other cases, you should use the Data Provider to access and manipulate the data. You can lower your learning curve by using the Data Provider API, because the same APIs work no matter what kind of data you are wrapping (that is, which Data Provider implementation you are using). 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 Visual Designer, right-click the Drop Down List component and choose Bind to Data from the contextual menu. The Bind to Data dialog box appears. 3. If necessary, click the Bind to Data Provider tab to bring it to the front. 4. Click Add Data Provider. 5. In the Add Data Provider dialog box, select Data Sources > Travel > Tables > PERSON and click Add. The Outline window now shows a personDataProvider node in the Page1 section and a personRowSet node in the SessionBean1 section. 6. In the Bind to Data dialog box, select PERSON.PERSONID in the Value Field list to make the component's getSelected method return the PERSON.PERSONID for the current selection. 7. Select PERSON.NAME in the Display Field list to cause the browser to populate the drop-down list with values from the PERSON.NAME database column. 8. Click OK. The text abc appears in the Drop Down List component. The abc text indicates that the display field is bound to a String object, which, in this case, is a database column of the SQL type varchar. 9. Click Run Main Project in the main toolbar. The IDE saves all changes and then builds, deploys, and runs the web application. First, the Output window appears at the bottom of the IDE. The IDE writes compilation and deployment preparation information to this window. (So if there are any problems with a build, check the Output window first.) Next, a dialog box displays the status of the deployment. After the deployment is complete, the IDE opens a web browser for the application. When the browser renders the page, it populates the drop-down list with data from the NAME column of the PERSON table.

Adding a Table Component


Next, you add a Table component to your application and connect the component to a database table. 1. From the Palette, drag a Table component and place it below the Drop Down List component. 2. Right-click the Table component and choose Bind to Data from the pop-up menu. 3. In the Table Layout dialog box, click Add Data Provider.

4. In the Add Data Provider dialog box, select Data Sources > Travel > Tables > TRIP and click Add. The Selected list in the Table Layout box now shows all the table's columns. You use the Selected list to specify which columns should appear in the Table component. 5. Select the first entry (TRIP.TRIPID) in the Selected list. Ctrl-Click the second entry (TRIP.PERSONID) and the last entry (TRIP.TRIPTYPEID) to select those entries too. 6. Click the < button. The selected entries are removed from the Selected list. Three entries remain in the Selected list, as shown in the following figure:
r r r

TRIP.DEPDATE TRIP.DEPCITY TRIP.DESTCITY

Figure 3: Bind to Data Dialog Box for a Table Component 7. Click OK. The Visual Designer now displays three columns in the Table component, as shown in the following figure.

Figure 4: Table Column Display

Modifying the SQL Query


Next, you modify the SQL query in the tripRowSet object so that the query also returns data from the TRIPTYPE table. You also modify the Table component to display the trip type description. 1. In the Outline window, expand the SessionBean1 node if it is not already expanded.

Figure 5: SessionBean1 Section in Outline Window 2. In the SessionBean1 section of the Outline window, right-click the tripRowSet node and choose Edit SQL Statement. The Query Editor appears in the editing area, with a tripRowSet tab. Tip: If the Output window is open, close it to give you more room to work with the Query Editor. 3. Drag the Travel > Tables > TRIPTYPE node from the Servers window and drop it on the Design View, as shown in Figure 6. Another table diagram appears with a link between the two table diagrams. This link represents a join. Notice how the IDE has modified the select statement in the Source Code pane. 4. Clear the checkbox for TRIPTYPEID in the TRIPTYPE table. This action removes the column from the result set and from the SQL query that is in the Source Code pane, as shown in the following figure.

Figure 6: The Query Editor 5. Leave the Query Editor open. 6. Click the Page1 tab in the editing area. 7. In the Visual Designer, right-click the Table component and choose Table Layout. The Table Layout dialog box appears. Because you have changed the SQL query for the tripRowSet, there are more columns that you can display. 8. Add the TRIPTYPE.DESCRIPTION column to the Selected list. 9. Click OK. A fourth column appears in the Table component.

Controlling the Rows That Are Displayed


When you added a Data Provider for the TRIP table, the IDE created a RowSet object with an SQL query that returns all the rows for all the columns in the table. If you deploy and run the application at this point, the Table component shows all the trip information in the TRIP table. For this application, the Table component must display only the trip information for the person whose name is selected from the Drop Down List component. You constrain the information that is displayed in the table by editing the query for the tripRowSet object to create a master-detail relationship between the Drop Down List component and the Table component.

1. Click the tripRowSet (SessionBean1) tab in the editing area to switch to the Query Editor. 2. In the Design Grid of the Query Editor, right-click any cell in the PERSONID row and choose Add Query Criteria. 3. Set the Comparison drop-down list to =Equals and select the Parameter radio button. 4. Click OK. You see =? in the Criteria column for PERSONID, which adds the following WHERE clause in the SQL query. Code Sample 1: WHERE Clause in the SQL Query WHERE TRAVEL.TRIP.PERSONID = ?

5. In the Design Grid of the Query Editor, choose Ascending from the drop-down list in the Sort Type cell in the DEPDATE row. The IDE automatically sets the Sort Order and adds the sort clause to the SQL query. 6. Close the Query Editor. 7. In the Visual Designer, double-click the Drop Down List component. The source for the Page1 class opens in the Java Editor, and the cursor is placed inside the body of the personIdDD_processValueChange method. The IDE creates this event handler method stub the first time that you double-click the Drop Down List component. 8. Replace the body of the personIdDD_processValueChange method with the following code shown in bold. Code Sample 2: Value Change Event Handling for the Drop Down List Component public void personIdDD_processValueChange(ValueChangeEvent event) { try { getSessionBean1().getTripRowSet().setObject( 1, personIdDD.getSelected()); tripDataProvider.refresh(); } catch (Exception e) { error("Cannot switch to person " + personDataProvider.getValue( "PERSON.PERSONID")); log("Cannot switch to person " + personDataProvider.getValue( "PERSON.PERSONID"), e); } }

This code binds the value of the PERSONID for the currently selected NAME in the drop-down list to the parameter in the prepared SQL statement for the tripRowSet object, executes the query, and gets the new result set. The setObject method replaces the ? in the query with the value of the PERSONID. The refresh method submits the new query and refreshes the result set. To learn more about either method, right-click the method call and choose Show Javadoc from the pop-up menu. In addition, the Data Provider Reference and the RowSet Reference are available from the Dynamic Help window. The log method sends a message and the associated stack trace to the application server's log to assist in discovering and diagnosing user problems. You can view the server's log by right-clicking Deployment Server in the Servers window and choosing View Server Log from the pop-up menu. 9. Press Ctrl-Shift-F to reformat the code. 10. Click in the Navigator window and type prerender. As soon as you start typing, a Quick Search dialog box appears, as shown in the following figure. The IDE highlights in the Navigator the first matching entry. Note that the Navigator window and the Outline window share the same space. You can bring a window to the front by clicking its header.

Figure 7: Quick Search in the Navigator Window 11. Press Enter. The Java Editor displays the prerender method. 12. Replace the body of the prerender method with the following code shown in bold.

Code Sample 3: Sychronizing the Master-Detail Data When the Page Is First Displayed public void prerender() { if ( personIdDD.getSelected() == null ) { try { personDataProvider.cursorFirst(); getSessionBean1().getTripRowSet().setObject( 1, personDataProvider.getValue("PERSON.PERSONID")); tripDataProvider.refresh(); } catch (Exception e) { error("Cannot switch to person " + personDataProvider.getValue("PERSON.PERSONID")); log("Cannot switch to person " + personDataProvider.getValue("PERSON.PERSONID"), e); } } }

This code, which is invoked before a web browser starts to display the page, handles the situation when the page is first accessed. 13. Press Ctrl-Shift-F to reformat the code. 14. Click Design in the editing toolbar to return to the Visual Designer. 15. Right-click the Drop Down List component and choose Auto-Submit on Change. In the Properties window, the following code appears in the onchange property. Code Sample 4: onchange Property Code common_timeoutSubmitForm(this.form, 'personIdDD');

Now when the user changes the drop-down list selection in the running web application, the web browser automatically submits the page. 16. Click Run Main Project in the main toolbar. The IDE saves all changed files, rebuilds the application, and redeploys the application to the server. Choose another name in the drop-down list and note that the trip table is updated to show the trips for the newly selected person. 17. Select a person from the Drop Down List component to see how the Table component synchronizes the master and detail data. Click the DESTCITY column header to see how the Table component sorts the rows.

Doing More
Try It. Add a Static Text component to the right of the Drop Down List component. Right-click the Static Text component, choose Bind to Data, and bind the component to PERSON.JOBTITLE. Run the program and choose a different name from the drop-down list. Notice that the job title does not change. This is because the application needs to synchronize the personDataProvider with the selected item from the drop-down list. Add the code shown below in bold to the prerender method and run the application again. The job titles should now match the selected name. Code Sample 5: Synchronizing personDataProvider With Selected Person public void prerender() { if ( personIdDD.getSelected() == null ) { try { personDataProvider.cursorFirst(); getSessionBean1().getTripRowSet().setObject( 1, personDataProvider.getValue("PERSON.PERSONID")); tripDataProvider.refresh(); } catch (Exception e) { error("Cannot switch to person " + personDataProvider.getValue("PERSON.PERSONID")); log("Cannot switch to person " + personDataProvider.getValue("PERSON.PERSONID"), e); } } else { try { // Synchronize data provider with current selection personDataProvider.setCursorRow( personDataProvider.findFirst( "PERSON.PERSONID", personIdDD.getSelected())); } catch (Exception e) { error("Cannot switch to person " + personIdDD.getSelected()); log("Cannot switch to person " + personIdDD.getSelected(), e); } } }

Try It. Play with the table's layout options. Right-click the Table component and choose Table Layout from the popup menu. Change the Header Text to Departure Date, Departure City, Destination City, and Description. Use the Options table in the dialog box to set the table's title to Trips. Select Enable Pagination and set the Page Size to 3. Run the application and see how your changes affect the way the table is displayed. Note: If you use the pagination option, add the following code after the tripDataProvider.refresh() statement in the personIdDD_processValueChange method: tableRowGroup1.setFirst(0);. This ensures that the first page is always displayed when a new name is selected from the drop-down list. Try It. Build a web application with a Drop Down List component and a Table component. Make the Drop Down List component display TRIPTYPE.DESCRIPTION. Make the Table component show all the TRIP records that have the same TRIPTYPEID as the selected TRIPTYPE. Try It. You might wonder whether the duplicate code in the prerender and personIdDD_processValueChange methods causes a double refreshing of the detail rowset. The answer is no. To illustrate, add a log(method-name) statement to the constructor, the prerender method, and the personIdDD_processValueChange. In the Servers window, right-click Deployment Server and choose View

10

Server Log. Run the program and select a new name. In the server log (in the Output window), you see that the methods are invoked in the following order: 1. 2. 3. 4. constructor prerender constructor personIdDD_processValueChange

When the browser first requests the page, the application creates an instance of Page1 and calls prerender. The server sends the response (the HTML page) and the Page1 instance is destroyed. The application does not call the value change event handler, because the application only generates value change events when a page is submitted (in this case, when a new person is selected). When you choose a new name from the drop-down list, the browser submits the page. The application creates a new instance of Page1 and restores the values from the previous instance (they are passed in the request). Because this is a post-back (a submission), and because the name has changed, the application generates a value change event. Thus personIdDD_processValueChange gets called and the application refreshes the rowset. After the value change event handlers are called, the application calls the prerender method. Because the dropdown now has a selected value, the application skips over the if section in the prerender method. To learn more about the lifecycle of a web application that uses JavaServer Faces components, see Event Processing LifeCycle in Sun Java Studio Creator 2.

Summary
The steps for binding a component to a database table are as follows: 1. You bind a component to a database table by dropping the database table's node on the component, or by choosing Bind to Data from the pop-up menu and selecting an existing Data Provider from the drop-down list. 2. You use the Bind to Data dialog box to configure the database columns that the component displays and, for a list-type component, what column it returns. You can also use the Table Layout menu action to configure which database table columns the Table component displays. 3. To modify a query for a RowSet object, you open the Query Editor on the RowSet object from the Outline window. 4. You call the RowSet object's setObject method to set the values for the query parameters. You call the data provider's refresh method to execute the query and refresh the result set. 5. Use the Auto-Submit on Change menu action to cause a page to be submitted automatically whenever a component's value changes. 6. Do the following steps to synchronize a detail component with a master component: 1. Add code to the Page Bean's prerender method to call the detail RowSet object's setObject method to set the query parameters to some default, such as the first person in a drop-down list. Then call the refresh method to execute the query. 2. Bind the master component to a processValueChanged method. Have this method call the detail RowSet object's setObject method to set the new query parameters. Then call the refresh method to execute the query.

11

See Also: q Working With Data Providers tutorial q Performing Inserts, Updates, and Deletes tutorial q Data Provider Reference in the IDE's Dynamic Help window q JDBC Rowset Reference in the IDE's Dynamic Help window

More Developer Resources: For more tutorials, articles, tips, forums, updates, and expert advice for developers, visit the Java Studio Creator developer resources on the Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.

This page was last modified: April 27, 2006

Sun and Third-party Trademarked Terminology


The following Sun trademarked terms might be used in the Sun Java(tm) Studio Creator tutorials:
q q q q q q q q q

Sun Java Studio Creator integrated development environment (IDE) Sun Java System Application Server version number (Application Server) Java Platform, Standard Edition technology (Java SE(tm) platform) JavaServer(tm) Faces technology JavaServer Pages(tm) technology (JSP(tm) technology) Sun Java System Web Server version number (Web Server) Java Database Connectivity software (JDBC software) Enterprise JavaBeans(tm) specification (EJB(tm) specification) Solaris(tm) Operating System software (Solaris OS software)

The following third-party trademarked terms might be used in the Sun Java Studio Creator tutorials:
q q

UNIX(R) software SPARC(R) processor

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries. U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.This product is covered and controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited. Note: Sun is not responsible for the availability of third-party web sites mentioned in this document and does not endorse

12

and is not responsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will not be responsible or liable for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services available on or through any such sites or resources.

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, tats-Unis. Tous droits rservs. Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs la technologie incorpore dans le produit qui est dcrit dans ce document. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plus des brevets amricains lists l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires ou les applications de brevet en attente aux tats-Unis et dans les autres pays. L'utilisation est soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo Java Coffee Cup sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans d'autres pays.Ce produit est soumis la lgislation amricaine en matire de contrle des exportations et peut tre soumis la rglementation en vigueur dans d'autres pays dans le domaine des exportations et importations. Les utilisations, ou utilisateurs finaux, pour des armes nuclaires,des missiles, des armes biologiques et chimiques ou du nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou rexportations vers les pays sous embargo amricain, ou vers des entits figurant sur les listes d'exclusion d'exportation amricaines, y compris, mais de manire non exhaustive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une faon directe ou indirecte, aux exportations des produits ou des services qui sont rgis par la lgislation amricaine en matire de contrle des exportations et la liste de ressortissants spcifiquement dsigns, sont rigoureusement interdites. Sun Microsystems n'est pas responsable de la disponibilit de tiers emplacements d'enchanement mentionns dans ce document et n'approuve pas et n'est pas responsable ou iresponsable d'aucun contenu, de la publicit, de produits, ou d'autres matriaux dessus ou fournis par de tels emplacements ou ressources. Sun ne sera pas responsable ou iresponsable d'aucuns dommages ou perte causs ou allgus pour tre caus par ou en liaison avec l'utilisation de ce produit ou la confiance dans des tels contenu, marchandises, ou services disponibles sur ou par des tels emplacements ou ressources.

13

Das könnte Ihnen auch gefallen