Practical Database Programming With Java
.pdf
828 Chapter 9 Developing Java Web Services to Access Databases
private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
AArrayList al = new ArrayList();
Bal.clear();
Cal.add(0, NameField.getText().toString()); al.add(1, OfficeField.getText().toString()); al.add(2, PhoneField.getText().toString()); al.add(3, CollegeField.getText().toString()); al.add(4, TitleField.getText().toString()); al.add(5, EmailField.getText().toString()); al.add(6, ComboName.getSelectedItem());
………
Figure 9.56. The newly added codes for the cmdUpdateActionPerformed() method.
to start the faculty data updating action. Therefore, double click on the Update button to open its event method cmdUpdateActionPerformed(), and enter the codes that are shown in Figure 9.56 into this method.
Let’s have a closer look at this piece of codes to see how it works.
A.First, a new ArrayList instance al is created and initialized. This variable is used to pick up and reserve the input-updated faculty data array.
B.Then, the ArrayList instance al is cleaned up by calling the clear() method to make sure that this object is clean before the updated parameters can be added into this instance.
C.The add() method is used to pick up and add six pieces of updated faculty information into this new ArrayList instance al. These six pieces of updated faculty information are entered by the user and stored in six text fields in this FacultyFrame window form. The toString() method is used to convert each piece of these updated faculty information obtained using the getText() method that returns an Object data type to a String. The last or the seventh parameter is the original faculty name stored in the ComboName combo box. The index is necessary since it is used to indicate the position of each parameter in this ArrayList. One point to be noted is the order of adding these six text fields, which must be identical with order of columns in our Faculty table.
Now let’s add the codes that are related to calling the UpdateFaculty() operation in our Web service and created automatically by the NetBeans IDE by dragging this operation node into this method. Perform the following operations to complete this code creation process:
1.Expand the Web Service References node in our client project WinClientSQL and all subnodes under this node until the WebServiceSQLPort.
2.Drag the UpdateFaculty operation under this node and place it into our opened method cmdUpdateActionPerformed(), exactly under the codes we created in Figure 9.56.
3.A piece of codes shown in Figure 9.57 has been automatically created and added into this method.
It is unnecessary to explain the function of this piece of codes line by line since all of coding lines have been illustrated by the built-in comments.
9.12 Build a Windows-Based Web Client Project to Consume the Web Service 829
………
try { // Call Web Service Operation
Aorg.ws.sql.WebServiceSQLService service = new org.ws.sql.WebServiceSQLService();
Borg.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();
//TODO initialize WS operation arguments here
Cjava.util.List<java.lang.Object> fdata = null;
//TODO process result here
Djava.lang.Boolean result = port.updateFaculty(fdata);
System.out.println("Result = "+result);
}catch (Exception ex) {
//TODO handle custom exceptions here
………
Figure 9.57. The automatically created codes by NetBeans IDE.
private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
ArrayList al = new ArrayList(); al.clear();
al.add(0, NameField.getText().toString()); al.add(1, OfficeField.getText().toString()); al.add(2, PhoneField.getText().toString()); al.add(3, CollegeField.getText().toString()); al.add(4, TitleField.getText().toString()); al.add(5, EmailField.getText().toString());
al.add(6, ComboName.getSelectedItem().toString());
try { // Call Web Service Operation
org.ws.sql.WebServiceSQLService service = new org.ws.sql.WebServiceSQLService(); org.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();
// TODO initialize WS operation arguments here
ABoolean update = port.updateFaculty(al);
Bif (!update) {
|
msgDlg.setMessage("The data updating is failed!"); |
|
msgDlg.setVisible(true); |
|
} |
C |
else |
|
ComboName.addItem(NameField.getText()); |
|
} |
D |
catch (Exception ex){ |
|
System.out.println("exception: " + ex); |
|
} |
}
Figure 9.58. The complete codes for the cmdUpdateActionPerformed() method.
Now let’s do some modifications to this piece of codes and add some codes to meet our data updating requirements. Enter the codes that are shown in Figure 9.58 into this method. The modified codes have been highlighted in bold.
Let’s have a closer look at this piece of codes to see how it works.
A.The Web service operation UpdateFaculty() is executed with the ArrayList instance al, which has been filled with six pieces of updated faculty information as the argument of
830 Chapter 9 Developing Java Web Services to Access Databases
this method. The running result of that operation is returned and assigned to a Boolean variable update.
B.If the value of the variable update is false, which means that no row has been updated in our Faculty table and this data updating has been failed, the msgDlg instance is used to show this situation.
C.Otherwise, if the value of the update variable is true, which means that this data updating action is successful, the updated faculty name will be added into the Faculty Name combo box ComboName using the addItem() method.
D.The catch block is used to track and display any possible exception during this Web service operation execution.
Next, let’s build the codes to perform the faculty data deleting action.
9.12.2.2 Build the Codes to Call the DeleteFaculty() Operation
Open our Windows-based client project WinClientSQL and double click on our main class FacultyFrame.java to open it. Click on the Design button to open the graphic user interface. In this client project, we want to use the Delete button in this form as a trigger to start the faculty data deleting action. Therefore, double click on the Delete button to open its event method cmdDeleteActionPerformed().
Now let’s insert the codes that are related to calling the DeleteFaculty() operation in our Web service and created automatically by the NetBeans IDE by dragging this operation node into this method. Perform the following operations to complete this code creation process:
1.Expand the Web Service References node in our client project WinClientSQL and all subnodes under this node until the WebServiceSQLPort.
2.Drag the DeleteFaculty operation under this node and place it into our opened method cmdDeleteActionPerformed(). A piece of codes shown in Figure 9.59 has been automatically created and added into this method.
It is unnecessary to explain the function of this piece of codes line by line since all of coding lines have been illustrated by the built-in comments.
………
try { // Call Web Service Operation
Aorg.ws.sql.WebServiceSQLService service = new org.ws.sql.WebServiceSQLService();
Borg.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();
//TODO initialize WS operation arguments here
Cjava.lang.String fname = "";
//TODO process result here
Djava.lang.Boolean result = port.deleteFaculty(fname); System.out.println("Result = "+result);
}catch (Exception ex) {
//TODO handle custom exceptions here
}
………
Figure 9.59. The automatically created codes by NetBeans IDE.
9.12 Build a Windows-Based Web Client Project to Consume the Web Service 831
private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
try { // Call Web Service Operation
org.ws.sql.WebServiceSQLService service = new org.ws.sql.WebServiceSQLService(); org.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();
// TODO initialize WS operation arguments here
ABoolean delete = port.deleteFaculty(ComboName.getSelectedItem().toString());
Bif (!delete) {
msgDlg.setMessage("The data deleting is failed!"); msgDlg.setVisible(true);
}
}
C catch (Exception ex){ System.out.println("exception: " + ex);
}
}
Figure 9.60. The complete codes for the cmdDeleteActionPerformed() method.
Now let’s do some modifications to this piece of codes and add some codes to meet our data deleting requirements. Enter the codes that are shown in Figure 9.60 into this method. The modified codes have been highlighted in bold.
Let’s have a closer look at this piece of codes to see how it works.
A.The Web service operation DeleteFaculty() is executed with the selected faculty name as the argument of this method. The running result of that operation is returned and assigned to a Boolean variable delete.
B.If the value of the variable delete is false, which means that no row has been deleted from our Faculty table and this data deleting has failed, the msgDlg instance is used to show this situation.
C.The catch block is used to track and display any possible exception during this Web service operation execution.
At this point, we have completed all coding development for our Windows-based client project for the data updating and deleting actions. Now let’s build and run our client project to call and test our Web service to perform faculty data updating and deleting actions.
9.12.3 Build and Run Our Client Project to Update and Delete Faculty Record via Web Service
Click on the Clean and Build Main Project button to build our client project. If everything is fine, click on the Run Main Project button to run our client project.
The FacultyFrame form window is displayed. First, let’s perform a faculty query action. Select a desired faculty member, such as Ying Bai, from the Faculty Name combo box, and click on the Select button to query the detailed information for this faculty via our Web service WebServiceSQL. The queried result is displayed in seven text fields.
Now enter an updating faculty record with six pieces of updated faculty information shown below into six text fields, which is shown in Figure 9.61.
832 Chapter 9 Developing Java Web Services to Access Databases
Figure 9.61. Six pieces of updated faculty information.
•Name: Susan Bai
•Title: Professor
•Office: MTC-200
•Phone: 750-378-2000
•College: Duke University
•Email: sbai@college.edu
Click on the Update button to try to call our Web service operation UpdateFaculty() to update this faculty record in the Faculty table in our sample database.
To confirm this data updating action, two methods can be used. First, we can open our Faculty table using either the Services window in the NetBeans IDE or the SQL Server 2008 Management Studio to check whether this faculty record has been updated. To do that using the Services window in the NetBeans IDE, perform the following operations:
1.Open the Services window and expand the Databases node.
2.Right click on our SQL Server database URL: jdbc:sqlserver://localhost\SQL2008 EXPRESS: 5000; databaseName=CSE_DEPT [ybai on dbo], and select the Connect item to connect to our database.
3.Expand our sample database CSE_DEPT and Tables.
4.Right click on the Faculty table and select the View Data item.
Your opened Faculty table is shown in Figure 9.62. It can be found that the faculty record with the faculty_id of B78880, which is located at row 4, and has been highlighted in dark color, has been successfully updated in our database.
The second way to confirm this data updating, which is simpler, is to use the Select button in this form to perform a query to try to retrieve the updated faculty record.
A second way to check this is to go to the Faculty Name combo box, and you can find that the updated faculty name Susan Bai has been added into this box. Click it to
9.12 Build a Windows-Based Web Client Project to Consume the Web Service 833
Figure 9.62. The opened Faculty table in the NetBeans IDE.
Table 9.6. The original faculty record in the Faculty table
faculty_id |
faculty_name |
office |
phone |
college |
title |
||
B78880 |
Ying Bai |
MTC-211 |
750-378-1148 |
Florida Atlantic University |
Associate Professor |
ybai@college.edu |
select it and click on the Select button. Do not worry about the exception message for the faculty image, since we did not insert any image for this new inserted faculty. Just click on the OK button for that message box and you can find that six pieces of updated faculty information have been retrieved and displayed in this form window. Our data updating is successful!
It is highly recommended to recover this updated faculty record to the original one in our database since we want to keep our database clean. Refer to Table 9.6 to recover this original faculty record. You can recover this record by opening the SQL Server 2008
Management Studio to add it or performing another updating action in this form to recover it.
Next, let’s test the faculty record deleting action via our Web service operation DeleteFaculty(). First, let’s perform another updating action to recover the updated faculty member Ying Bai using the data shown in Table 9.6. Enter these six pieces of original faculty information into those six text fields and click on the Update button.
Then keep the faculty member Ying Bai selected in the Faculty Name combo box, and click on the Delete button to try to call our Web service operation DeleteFaculty() to delete this faculty record from our sample database.
To confirm this data deleting action, two ways can be used. First, you can perform a faculty data query operation by selecting the deleted faculty member Ying Bai from the
Faculty Name combo box, and clicking on the Select button to try to retrieve this faculty record from our database. You can find that the querying faculty record cannot be found from our sample database and cannot be displayed in this form, and this means that our data deleting is successful.
834 Chapter 9 Developing Java Web Services to Access Databases
Another way to confirm this data deleting is to open the Faculty table in our sample database.
A point to be noted is that as you perform reupdating actions, you must perform the both updating actions in a short period of time, which means that you have to perform the second updating within a short period of time after you do the first updating action.
To make our sample database clean and neat, it is highly recommended to recover this deleted faculty member and related records in our Faculty, LogIn, Course, and
StudentCourse tables. An easy way to do this recovery is to use the Microsoft SQL Server 2008 Management Studio. Refer to deleted records shown in Tables 9.2–9.5 in Section 9.11.3 to add or insert them back to the related tables to complete this data recovery.
A point to be noted is that as you perform data recovery, the recovery order is very important. It means that you have to first recover the faculty data in the Faculty table, and then the data in other tables, since the Faculty table is a primary table.
A complete Windows-based client project WinClientSQL can be found from the folder DBProjects\Chapter 9 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
Next let’s build a Web-based client project to consume our Web service to insert a new faculty record into the Faculty table in our sample database.
9.13 BUILD A WEB-BASED CLIENT PROJECT TO CONSUME THE WEB SERVICE
We can still use a Web-based client project WebClientSQL we built in Section 9.7 to consume our Web service to perform the faculty data updating and deleting actions. First, let’s refresh the Web service reference used for our Web-based client project to allow it to use the updated Web service operations.
9.13.1 Refresh the Web Service Reference for Our Web-Based Client Project
In order to call the UpdateFaculty() and DeleteFaculty() operations in our Web service project WebServiceSQL, we need to refresh the Web reference in our Web-based client project WebClientSQL to use the updated Web service project. Perform the following operations to refresh the Web service reference:
1.Open our Web-based client project WebClientSQL and expand the Web Service References node.
2.Right click on our Web service WebServiceSQLService and choose the Delete item to remove this old Web reference.
9.13 Build a Web-Based Client Project to Consume the Web Service 835
3.Right click on our Web-based client project WebClientSQL and select the New > Web Service Client item to open the New Web Service Client wizard.
4.On the opened wizard, click on the Browse button that is next to the Project field and expand our Web application WebServiceSQLApp. Then choose our Web service WebServiceSQL by clicking on it, and click on the OK button.
5.Click on the Finish button to complete this Web service reference refreshing process.
Now that we have refreshed or updated the Web service reference for our Web-based client project WebClientSQL, next, let’s develop the codes in our client project to call that Web service operations UpdateFaculty() and DeleteFaculty() to perform faculty data updating and deleting actions.
First, let’s take care of the data updating operation UpdateFaculty().
9.13.2 Develop the Codes to Call Our Web Service Operation UpdateFaculty()
The main coding process is in the Java managed bean class FacultyMBean.java.
As we know, a binding relationship between the action attribute of the Update command Button in our JSF page FacultyPage.jsp and the Update() method in our Java managed bean class FacultyMBean.java has been established. Therefore, we can concentrate on the coding for the Update() method in our Java managed bean.
Open our Web-based client project WebClientSQL, and double click on the FacultyMBean.java from the Projects window to open this managed bean class file. Let’s do the coding for the Update() method in this class to fulfill this data updating function.
Browse to the Update() method and drag the Web service operation UpdateFaculty under the Web Service References node and place it inside the Update() method. A piece of codes is created and added into this method, as shown in Figure 9.63.
It is unnecessary to explain the function of this piece of codes line by line since all of coding lines have been illustrated by the built-in comments.
Now let’s do some modifications to this piece of codes and add some codes to meet our data updating requirements. Enter the codes that are shown in Figure 9.64 into this method.
public String Update() {
Atry { // Call Web Service Operation
Borg.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();
//TODO initialize WS operation arguments here
Cjava.util.List<java.lang.Object> fdata = null;
//TODO process result here
Djava.lang.Boolean result = port.updateFaculty(fdata); System.out.println("Result = "+result);
E} catch (Exception ex) {
//TODO handle custom exceptions here
}
return null;
}
Figure 9.63. The automatically created codes by dragging the operation node.
836 Chapter 9 Developing Java Web Services to Access Databases
public String Update() {
A ArrayList al = new ArrayList();
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
Bal.clear();
Cal.add(0, name); al.add(1, office); al.add(2, phone); al.add(3, college); al.add(4, title); al.add(5, email); al.add(6, facultyName);
try { // Call Web Service Operation
org.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort(); // TODO initialize WS operation arguments here
DBoolean update = port.updateFaculty(al);
Eif (!update) {
msgDlg.setMessage("The data updating is failed!"); msgDlg.setVisible(true);
}
F} catch (Exception ex) {
//TODO handle custom exceptions here msgDlg.setMessage("exception: " + ex);
msgDlg.setVisible(true);
}
G return null;
}
Figure 9.64. The modified codes for the Update() method.
Let’s have a closer look at this piece of newly added codes to see how it works.
A.First, a new ArrayList instance al is created and initialized. This variable is used to pick up and reserve the input updating faculty data array.
B.The clear() method is executed to make sure that the ArrayList instance is clean before a updating faculty record is collected.
C.The add() method is used to pick up and add six pieces of updating faculty information into this new ArrayList instance al. Six pieces of updating faculty information are entered by the user in the JSF page FacultyPage.jsp and stored in six properties defined in this managed bean. The last parameter, the seventh one, is the original faculty name.
D.The UpdateFaculty() operation in our Web service is called with the ArrayList instance that contains six pieces of updated faculty information as the argument. The execution result of this faculty data updating is returned and assigned to the local Boolean variable update.
E.If the returned Boolean variable update is false, which means that this data updating has failed, the msgDlg instance is used to indicate this situation.
F.The catch block is used to catch any possible exception during this data updating process.
G.Finally, a null is returned since it is not important to our application.
Next,let’sbuildthecodesfortheDelete()methodinourmanagedbeanFacultyMBean. java to call our Web service operation DeleteFaculty() to perform the faculty data deleting action.
9.13 Build a Web-Based Client Project to Consume the Web Service 837
9.13.3 Develop the Codes to Call Our Web Service Operation DeleteFaculty()
As we know, a binding relationship between the action attribute of the Delete command Button in our JSF page FacultyPage.jsp and the Delete() method in our Java managed bean class FacultyMBean.java has been established. Therefore, we can concentrate on the coding for the Delete() method in our Java managed bean.
Open our Web-based client project WebClientSQL and double click on the FacultyMBean.java from the Projects window to open this managed bean class file. Let’s do the coding for the Delete() method in this class to fulfill this data deleting function.
Browse to the Delete() method and drag the Web service operation DeleteFaculty under the Web Service References node and place it inside the Delete() method. A piece of codes is created and added into this method, as shown in Figure 9.65.
It is unnecessary to explain the function of this piece of codes line by line since all of coding lines have been illustrated by the built-in comments.
Now let’s do some modifications to this piece of codes and add some codes to meet our data deleting requirements. Enter the codes that are shown in Figure 9.66 into this method.
Let’s have a closer look at this piece of new added codes to see how it works.
A.First a MsgDialog instance msgDlg is created, and this instance is used to track and display any possible exception during the data deleting action.
B.The DeleteFaculty() operation in our Web service is called with the original faculty name as the argument. The execution result of this faculty data deleting is returned and assigned to the local Boolean variable delete.
C.If the returned Boolean variable delete is false, which means that this data deleting has failed, the msgDlg instance is used to indicate this situation.
D.The catch block is used to catch any possible exception during this data deleting process.
E.Finally, a null is returned since it is not important to our application.
Now, let’s build and run our Web client project to call our Web service operations to perform the faculty data updating and deleting actions.
public String Delete() {
Atry { // Call Web Service Operation
Borg.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();
//TODO initialize WS operation arguments here
Cjava.lang.String fname = "";
//TODO process result here
Djava.lang.Boolean result = port.deleteFaculty(fname); System.out.println("Result = "+result);
E} catch (Exception ex) {
//TODO handle custom exceptions here
}
return null;
}
Figure 9.65. The automatically created codes by dragging the operation node.
