>> More Visual Web Pack Documentation
Performing Inserts, Updates, and Deletes
| May 2007 [Revision number: V5.5.1-1] |
|
|
This tutorial shows you how to use NetBeans Visual Web Pack to build a web application that can create, retrieve, update, and delete database rows. The application provides a drop-down list of master data along with a synchronized detail table. Users of the application can add to, update, and delete the records in the detail table and from its associated database.
This tutorial uses concepts introduced in other, more basic tutorials. If you do not have basic knowledge of the IDE and its design components, consider first reading introductory tutorials such as Getting Started With NetBeans Visual Web Pack and Using Databound Components to Access a Database. |
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 |
| BluePrints Ajax Component Library |
Not required |
* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.
This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and later, and with Tomcat 5.5.17.
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.
Creating the Project
In this tutorial, you create a single-page web application. You begin by laying out the page, which includes a person and corresponding trips, as shown in the following figure.
Figure 1: Initial Page Layout |
Designing the Page
- Create a new visual web application and name it
InsertUpdateDelete.
- From the Basic section of the Palette, drag a Drop Down List component to the upper left corner of the page. In the Properties window, change its
id property to personDD.
-
Drag a Message Group component from the Basic Palette and place it to the right of the Drop Down List.
The Message Group component displays validation and conversion errors, as well as messages written to the Java Server Faces context by the info and error methods. These messages can prove helpful if you need to debug your project.
- Place a Table component below the other two components.
Configuring the Drop Down List
-
Open the Runtime 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. When the Connect dialog box appears, enter travel for the Password, check Remember Password For This Session, and click OK. If you do not see a jdbc node for the TRAVEL database, see the NetBeans Visual Web Pack 5.5 Installation Instructions for information about making the database available to the IDE.
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.
Expand the jdbc node for the TRAVEL database, then expand the Tables node.
Note: The jdbc node for the TRAVEL database will be called the Travel node in the rest of this tutorial.
-
Drag the PERSON node onto the Drop Down List in the Visual Designer.
The Outline window shows a personDataProvider node in the Page1 section and a personRowSet node in the SessionBean1 section.
-
Right-click the Drop Down List and choose Auto-Submit on Change from the pop-up menu.
This setting causes the page to be sent to the server whenever a new value is chosen from the list.
-
Right-click the Drop Down List and choose Configure Virtual Forms from the pop-up menu.
In the resulting dialog box, note that personDD is shown in the upper left corner of the window to show that the Drop Down List has been selected.
-
Click New and Enter person in the Name column. Double-click the field under the Participate column and set it to Yes, and then do the same for the Submit column, as shown in the following figure.
Figure 2: Configuring Virtual Forms |
By using a virtual form, the application avoids unnecessary validations for data in the Table.
- Click OK.
-
Click the Show Virtual Forms button in the Visual Designer toolbar, as shown in Figure 3.
By viewing virtual forms, you can see the relationship between components in the Visual Designer and any virtual forms that you have configured.
Figure 3: Showing Virtual Forms |
Configuring the Table
- Drag the Travel > Tables > TRIP node from the Runtime window and drop it on the Table component in the Visual Designer. If the Choose Target dialog box displays, make sure table1 is selected and click OK.
-
Right-click the Table and choose Table Layout from the pop-up menu.
The dialog box shows the fields that are available from the tripDataProvider that you just created and lets you control which fields to display in the table.
-
Use the < button to remove TRIP.TRIPID, TRIP.PERSONID, and TRIP.LASTUPDATED from the Selected list on the right, as shown in the following figure.
Figure 4: Binding Table to Data Provider |
- Click the Options tab and change the Title to
Trips Summary.
-
Click OK.
Your Table component in the Visual Designer should now look like the following figure. Note that if your columns are not in the order shown, you can rearrange them by reopening the Table Layout dialog box, clicking the Columns tab, and using the Up and Down buttons.
Figure 5: Page1 Table Layout |
-
In the Outline window, right-click tripRowSet under SessionBean1 and choose Edit SQL Statement from the pop-up menu.
The SQL Query Editor opens.
-
In the grid area near the center of the window, right-click in the PERSONID row and choose Add Query Criteria, as shown in the following figure.
Figure 6: Adding Query Criteria |
-
In the dialog box, set the Comparison drop-down list to =Equals and select the Parameter radio button, and then click OK.
Figure 7: Add Query Criteria Dialog Box |
The characters "=?" appear in PERSONID's Criteria field, and the criteria "WHERE TRAVEL.TRIP.PERSONID=?" appears at the end of the SQL statement in the SQL Pane at the bottom of the editor.
- Close the SQL Editor for tripRowSet.
Changing the Column Components
You now change the column contents to be editable fields in preparation for adding the ability to insert new trips into the database. When you do so, you take advantage of the compound nature of the Table component by nesting other components inside it.
-
Right-click the Table component and choose Table Layout.
The Table Layout dialog box opens.
-
In the Columns tab, select TRIP.DEPDATE from the Selected list on the right. In the Column Details area at the bottom of the dialog box, change the Component Type from Static Text to Text Field, as shown in the following figure.
Figure 8: Changing the Appearance of a Column |
- Perform the same action for TRIP.DEPCITY and TRIP.DESTCITY.
- Select TRIP.TRIPTYPEID in the Selected list and change the Component Type from Static Text to Drop Down List.
-
Click OK.
Note: If the table columns are too wide after performing the above steps, you can resize them by selecting the first component in each column and dragging its selection handles.
-
Drag the Travel > Tables > TRIPTYPE node onto the Drop Down List in the Table component. If the Choose Target dialog opens, make sure dropDown1 is selected and click OK.
This action creates the triptypeDataProvider.
Configuring the Virtual Form for the Table
Next you create a virtual form for the input components in the table. The virtual form ensures that when a change to the personDD drop-down list submits the page, the input components aren't put through validation and conversion. The correct information is displayed in the table whenever the user chooses a new person from the drop-down list.
- In the Visual Designer, use Ctrl-Click in the table to select the three Text Field components in the three columns containing text fields and the Drop Down List component in the TRIPTYPEID column.
- Right-click one of the selected components and choose Configure Virtual Forms from the pop-up menu.
- In the Configure Virtual Forms dialog box, make sure the three Text Fields and the Drop Down List are listed in the upper left corner of the window. If they are not all listed as shown in the following figure, close the dialog box, reselect them, and try again. When they are correctly listed, click New.
-
Change the name of the new virtual form to save and the Participate setting to Yes, as shown in the following figure, and then click OK.
Figure 9: Configuring Virtual Forms for Table Elements |
Adding Event and Initialization Code
You now associate the personDD Drop Down List with the Table component to enable the following behavior: When the user selects a person from the list, that person's trips will appear in the table.
- Double-click the personDD Drop Down List to create a value change event method and to open the Java Editor on that method.
-
In the value change event method, note the comment line // TODO: Replace with your code. Replace this line with the bold text in Code Sample 1, and then press Ctrl-Shift-F to reformat your code.
| Code Sample 1: Drop Down List Event Handler |
public void personDD_processValueChange(ValueChangeEvent event) {
Object selectedPersonId = personDD.getSelected();
try {
personDataProvider.setCursorRow(
personDataProvider.findFirst("PERSON.PERSONID",
selectedPersonId));
getSessionBean1().getTripRowSet().setObject(1, selectedPersonId);
tripDataProvider.refresh();
form1.discardSubmittedValues("save");
} catch (Exception e) {
error("Cannot switch to person " + selectedPersonId);
log("Cannot switch to person " + selectedPersonId, e);
}
}
|
At the end of the try clause, the statement form1.discardSubmittedValues("save") ensures that whenever the user selects a new person from the drop-down list, current trip information shown in the table will be replaced by new information related to the chosen person. Recall that the user interface elements in the table that display the trip information all participate in the virtual form named save. Note also that the event handler does not throw exceptions. Instead, it logs them in the server.log file. The event handler also calls an error method that, in the event of an error, displays a message in the Message Group component.
-
Scroll in the Java source to the prerender method, or, if you prefer, type Ctrl-F to open the Find dialog box and search for prerender. Add the following code in bold to the method.
| Code Sample 2: Prerender Method |
public void prerender() {
if ( personDD.getSelected() == null ) {
Object firstPersonId = null;
try {
personDataProvider.cursorFirst();
firstPersonId = personDataProvider.getValue("PERSON.PERSONID");
personDD.setSelected(firstPersonId);
getSessionBean1().getTripRowSet().setObject(
1, firstPersonId);
tripDataProvider.refresh();
} catch (Exception e) {
error("Cannot switch to person " +
firstPersonId);
log("Cannot switch to person " +
firstPersonId, e);
}
}
}
|
- Right-click in the Java Editor and choose Reformat Code to make the code align correctly.
Testing Your Application – Part 1
Build, deploy, and run the project by clicking the Run Main Project button
on the main toolbar. When the page loads into your web browser, the drop-down list is populated with names, and the table is filled with data. When you select a different name from the list, the trips associated with that name appear in the table.
Figure 10: Deployed Application, Test 1 |
Adding an Insert Feature
In this section, you add a feature that makes it possible to add a trip to the table by inserting a rowset into the database. First, you provide Message components for the Table's Text Fields. These components ensure that the user sees errors when entering incorrect information. Then you add a Button to the page that enables users to add new rows to the data buffer.
- Click the Design button to view Page1 in the Visual Designer.
- From the Basic section of the Palette, drag a Message component onto the topmost Text Field in each of the first three columns of the Table.
- Select the first Message component. In the Properties window, scroll to the
for property and choose textField1 from the drop down list. When the Message is correctly associated with the Text Field, the Message text changes to show the association, as shown in Figure 11.
-
Set the
for property of the second Message component to textField2.
-
Set the for property of the third Message component to textField3.
Figure 11: Associating Message Components With Text Fields |
- From the Basic section of the Palette, drag a Button component onto Page1 and place it above the Table component near the top of the second column, as shown in Figure 12.
- Change the text from
Button to Add Trip.
- In the Properties window, change the button's
id property to add.
- In the Visual Designer, double-click the button to open the Java Editor with the insertion point in the
add_action event handler method for the button.
Add the following code shown in bold to the button's event handler method:
| Code Sample 3: Add Trip Action Code |
public String add_action() {
try {
RowKey rk = tripDataProvider.appendRow();
tripDataProvider.setCursorRow(rk);
tripDataProvider.setValue("TRIP.TRIPID", new Integer(0));
tripDataProvider.setValue("TRIP.PERSONID", personDD.getSelected());
tripDataProvider.setValue("TRIP.TRIPTYPEID", new Integer(1));
} catch (Exception ex) {
log("Error Description", ex);
error(ex.getMessage());
}
return null;
}
|
-
Right-click in the Java Editor and choose Fix Imports to resolve the RowKey not found error.
The IDE adds the following package to the Page1.java block of import statements:
import com.sun.data.provider.RowKey;
Testing Your Application – Part 2
Build, deploy, and run the project by clicking the Run Main Project button. The page loads into your web browser, and the Add Trip button appears, as shown in the following figure. Each time you click the button, a new empty row is appended to the bottom of the table. You are able to edit the information in the row, but because you have not yet provided a mechanism for saving the rowset, your changes will be lost when you choose a different name from the drop-down list.
Figure 12: Deployed Application, Test 2 |
Modifying the Page to Save Rowsets
In this section, you add a second rowset to the project. The rowset is used to calculate the maximum trip ID that has been used.
- Click Design in the editor window to return to Page1 in the Visual Designer.
-
From the Runtime window, select the Databases > Travel > Tables > TRIP table and drag it onto the SessionBean1 node in the Outline window.
Figure 13: Dragging TRIP Table Onto SessionBean1 |
This action opens the Add New Data Provider dialog box.
-
Click the Create SessionBean1/tripRowSet1 radio button, change the data provider name to maxTripRowSet, and click OK.
Note: Rowsets appear twice in the dialog box. This is a known issue and should be ignored. It does not affect the application in this tutorial.
Figure 14: Adding New Data Provider to SessionBean1 |
This action creates maxTripDataProvider and maxTripRowSet in SessionBean1.
- In the Outline window, double-click SessionBean1 > maxTripRowSet to open the Query Editor. Click in the Source Code pane (third from the top). Delete the existing SQL query you find there and enter the following query:
SELECT MAX(TRAVEL.TRIP.TRIPID)+1 AS MAXTRIPID FROM TRAVEL.TRIP
You will use the MAXTRIPID value in the action handler for the Save button, which you will add next.
Close the Query Editor.
Note: This query is not supported by the Query Editor's graphical editor. If you see an alert dialog box complaining of a lexical error, you can safely dismiss it by clicking Continue.
Saving User Changes Into the Database
- Drop a Button component above the Table component near the top of the first column. For positioning, see the Save Changes button in Figure 15.
- Change the Button text from
Button to Save Changes.
- In the Properties window, change the
id property to save.
- Right-click the Save Changes Button and choose Configure Virtual Forms from the pop-up menu.
- In the Configure Virtual Forms dialog box, make sure
save is shown in the list in the upper left corner so that your changes in this window apply to the Save Changes Button. Then, select the save virtual form, change the Submit value to Yes, and click OK.
- In the Visual Designer, double-click the Save Changes Button to open the Java Editor. In the Java Editor, the insertion point is located in the
save_action event handler method for the button.
-
Add the following code shown in bold to the button's event handler method:
| Code Sample 4: Save Action Code |
public String save_action() {
try {
// Get the next key, using result of query on MaxTrip data provider
CachedRowSetDataProvider maxTrip =
getSessionBean1().getMaxTripDataProvider();
maxTrip.refresh();
maxTrip.cursorFirst();
int newTripId = ((Integer) maxTrip.getValue("MAXTRIPID")).intValue();
// Navigate through rows with data provider
if (tripDataProvider.getRowCount() > 0) {
tripDataProvider.cursorFirst();
do {
if (tripDataProvider.getValue("TRIP.TRIPID").equals
(new Integer(0))) {
tripDataProvider.setValue("TRIP.TRIPID",
new Integer(newTripId));
newTripId++;
}
} while (tripDataProvider.cursorNext());
};
tripDataProvider.commitChanges();
} catch (Exception ex) {
log("Error Description", ex);
error("Error :"+ex.getMessage());
}
return null;
}
|
Testing Your Application – Part 3
Build, deploy, and run the project by clicking the Run Main Project button. The application should work as follows:
- You can add a trip and save it. The trip then appears in the table and persists. If you choose a different person and then return to this person, you see the trip you added.
- You can edit existing trip information and save your changes.
- If you enter something other than a date in the Date field, the application provides an error message.
- You can click Add Trip more than once before saving, as an easy way to add multiple rows at once. Any rows that are still empty when you save your changes are saved as empty rows.
- If you switch to a different person before clicking Save Changes, all your updates are lost.
- If you modify some values and then click one of the column headers to sort by that column, the Table component remembers the pending changes, which can then be saved.
Adding a Delete Feature
In this section, you add a delete feature to the table. Using this feature, users will be able to delete a trip by removing a row from the database. As implemented in this tutorial, the action of the Delete button is immediate and does not require the Save Changes button to delete the row from the database. In fact, because the Delete button event handler uses the commitChanges method, it also saves all pending changes just as the Save Changes button does.
Adding a Delete Button to Each Row
-
Click Design in the editor window to return to Page1 in the Visual Designer, and then right-click the Trips Summary table and choose Table Layout from the pop-up menu.
The Table Layout dialog box opens.
- If necessary, click the Columns tab, then click New to add a new column to the table.
-
With the new column name selected in the Selected list, make the following changes in the Column Details area:
- Header and Footer Text: Delete any default text from the Header and Footer text fields and leave them blank.
- Component type:
Button
- Value Expression:
Delete
- Width: Delete any default value and leave blank.
- Horizontal Align:
Center
- Vertical Align:
Middle
- Click OK.
- Select the topmost Delete button in the table, and in the Properties window, set the
id property to delete.
Adding Event Code
- Double-click the first button in the Delete column to open the Java Editor in the
delete_action event handler method.
-
Add the following code shown in bold to the button's event handler method:
| Code Sample 5: Delete Action Code |
public String delete_action() {
form1.discardSubmittedValues("save");
try {
RowKey rk = tableRowGroup1.getRowKey();
if (rk != null) {
tripDataProvider.removeRow(rk);
tripDataProvider.commitChanges();
tripDataProvider.refresh();}
} catch (Exception ex) {
log("ErrorDescription", ex);
error(ex.getMessage());
}
return null;
}
|
Testing Your Application – Part 4
Build, deploy, and run the project by clicking the Run Main Project button. The following figure shows the running application.
When deployed, you should be able to delete a row from the table to remove it from the database. The delete action will also commit all pending changes to the database.
Figure 15: Testing Your Application, Part 4 |
Adding a Revert Feature
Now, add a revert feature to the page. Using this feature, users will be able to abandon their edits and revert to the previously saved data. Note that the revert feature will not bring back saved or deleted rows; both the Save Changes and Delete buttons commit changes to the database.
Adding a Revert Changes Button
- Click Design in the editor window to return to Page1 in the Visual Designer, and then drag a Button component from the Palette onto Page1. Place the new Button to the right of the Add Trip Button.
- Change the button text to
Revert Changes.
- In the Properties window, change the Button component's
id property to revert.
- Double-click the Revert Changes Button to open the Java Editor in the
revert_action method.
-
Add the code in bold in the following code sample to the revert_action method.
| Code Sample 6: Revert Action Code |
public String revert_action() {
form1.discardSubmittedValues("save");
try {
tripDataProvider.refresh();
} catch (Exception ex) {
log("Error Description", ex);
error(ex.getMessage());
}
return null;
}
|
Configuring a Virtual Form
The application as presently configured exhibits some undesirable behavior. For example, if the user enters an invalid date in the first column of an existing row and then clicks the Add button, the operation fails because a conversion error on the date rejects the form submission. The desired behavior when the user clicks the Add button is to forego processing the input fields in the table so that a new row can be added regardless of pending edits to existing rows.
Similarly, when the user clicks the Revert button, the intention is to abandon all edits, so edits should also be ignored in that case. However, when the user clicks the Delete button, you still want validation to happen because this button not only deletes a row, it also submits any pending changes, requiring that input fields be processed first.
To ensure that the input fields on the page forego processing (including validation checks) when the user clicks the Add or Revert button, you will make these buttons submit a virtual form. In this case, you can make both buttons submit the same virtual form because they need to submit a virtual form that has no participants.
-
In the Visual Designer, Ctrl-Click to select the Add and Revert buttons, and then right-click and choose Configure Virtual Forms from the pop-up menu.
In the Configure Virtual Forms window, add and revert should appear in the upper left corner to show that those buttons have been selected.
-
In the Configure Virtual Forms window, click New, name the new virtual form add/revert, and set Submit to Yes. Click OK.
Figure 16: Configuring Virtual Form for Add, Revert, and Delete Buttons |
Testing Your Application—Part 5
Build, deploy, and run the project by clicking the Run Main Project button. Figure 17 below shows the running application.
When deployed, you should be able to perform the following functions:
Figure 17: Testing Your Application, Part 5 |
Summary
In this tutorial, you associated a Table component, Text Field components, and Drop Down List components with information in a database. You set properties on components and added prerender and event code to insert, update, and delete data from the database and revert changes entered on the form. You used virtual forms, which allowed your application to use just a single page and allowed submitted data to bypass validation checks when adding a row or reverting changes.
See Also:
This page was last modified: May 24, 2007