Practical Database Programming With Java
.pdf
888 Chapter 9 Developing Java Web Services to Access Databases
Figure 9.122. The updated course information for the course CSE-549.
updated. But the second way, which is to select the course_id whose course details have been updated from the Course ID List Listbox to get course details, is an easy way to confirm this course data updating.
Now let’s use the second way to test this course data updating. Just click any other course_id, such as CSC-132B, from the Course ID List Listbox. Then click on the course_id CSE-549 whose details have been updated, to retrieve all course details. It can be found that this course is really updated based on the updating information shown in Figure 9.122.
Our course data updating using Web service is successful.
Generally it is recommended to recover this updated course in the Course table in our sample database to keep our database neat and clean. However, we will keep this course right now since we need to use this record to perform the course deleting action in the following section.
9.15.4.5 Build Codes for the Delete Button Method to Delete Courses
The function of this method is to delete an existing course record from our Course table as the Delete button is clicked by the user.The existing course record will be permanently deleted from the Course table in our sample Oracle database when this method is complete.
On the opened Design view of the CourseFrame form window, double click on the Delete button to open this method. Perform the following operations to add the Web service operation DeleteCourse() into this method:
1.Browse to the Web Service References node under our client project WinClientOracle.
2.Expand our Web service until all our five Web service operations have been exposed.
3.Drag the DeleteCourse operation and place it inside the cmdDeleteActionPerformed() method.
9.15 Build a Windows-Based Web Client Project to Consume the Web Service 889
private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
try { // Call Web Service Operation
Aorg.ws.oracle.WebServiceOracleService service = new org.ws.oracle.WebServiceOracleService();
Borg.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();
//TODO initialize WS operation arguments here
Cjava.lang.String cid = "";
//TODO process result here
Djava.lang.Boolean result = port.deleteCourse(cid); System.out.println("Result = "+result);
E} catch (Exception ex) {
//TODO handle custom exceptions here
}
}
Figure 9.123. The automatically created and added codes.
private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
ABoolean delete = false;
try { // Call Web Service Operation
org.ws.oracle.WebServiceOracleService service = new org.ws.oracle.WebServiceOracleService(); org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();
Bdelete = port.deleteCourse(CourseIDField.getText());
Cif (!delete)
System.out.println("Error in course deleting..."); D } catch (Exception ex) {
msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);
}
}
Figure 9.124. The modified codes for the cmdDeleteActionPerformed() method.
4.A piece of codes is automatically created and added into this method, which is shown in Figure 9.123.
Now let’s do some modifications to this piece of codes and add some codes to meet our course record deleting requirements. Enter the codes that are shown in Figure 9.124 into this method, and the modified codes have been highlighted in bold.
Let’s have a closer look at this piece of newly added codes to see how it works.
A.A local variable delete is created first, and this variable is a Boolean variable used to hold the running result of the execution of the Web service operation DeleteCourse().
B.The Web service operation DeleteCourse() is called to delete an existing course record from our Course table based on the selected course_id. The running result is returned and assigned to the local variable delete.
C.If a false is returned, which means that this course data deleting has failed, the system println() method is used to indicate this situation.
D.The catch block is used to track and display any possible exception during this data deleting process.
890 Chapter 9 Developing Java Web Services to Access Databases
Now we have finished the coding process for calling and executing our last Web service operation DeleteCourse() to delete an existing course record from the Course table based on the selected course_id. Click on the Clean and Build Main Project button to build our project. Click on the Run Main Project button to run our client project to test this course data deleting function.
On the opened client project, keep the default faculty member Ying Bai unchanged and click on the Select button to query all course_id taught by this selected faculty. Immediately, you can find that all four courses or four course_id taught by this faculty have been returned and displayed in the Course ID List box. To delete an existing course CSE-549, just click on this course_id from the Course ID List Listbox and click on the Delete button.
To confirm this course deleting action, two ways can be utilized. First, you can open our Course table to check whether this course has been deleted from our database. Another way, which is easy, is to use the Select button to try to retrieve this deleted course from our database. To do that, just keep the selected faculty member Ying Bai in the Faculty Name combo box unchanged and click on the Select button. It can be found from the returned courses, exactly all course_id taught by the selected faculty, that no CSE-549 is existed.
Our course record deleting using Web service is successful.
Generally, it is recommended to recover any deleted record from our database to keep our sample database neat and clean. However, since this course CSE-549 is added by us for testing purposes, therefore, we do not need to recover this course from our Course table.
At this point, we have finished all developing and building processes to consume our Web service using a Windows-based client project. A complete Windows-based client project that is used to consume our Web service to query and manipulate data against our Oracle database, WinClientOracle, 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 this Web service.
9.16 BUILD A WEB-BASED WEB CLIENT PROJECT TO CONSUME THE WEB SERVICE
To save time and space, we can use some components in a Web application project JavaWebDBJSPOracle we developed in Chapter 8 to build our Web-based client consuming project WebClientOracle in this section. In fact, we will use the CoursePage.jsp file in that project and a Java managed bean class to query and manipulate course data in our sample Oracle database.
The structure of this Web-based client project is shown in Figure 9.125. First, let’s create our Web-based client project WebClientOracle.
9.16.1 Create a Web-Based Client Project WebClientOracle
Perform the following operations to create a new Web application project
WebClientOracle:
9.16 Build a Web-Based Web Client Project to Consume the Web Service 891
|
Web Server |
|
||
|
HTTP |
|
Oracle |
|
|
Request |
|
Database |
|
Web-Based |
Java Managed |
Web Services |
Database |
|
Client |
Bean |
Server |
||
|
||||
HTTP
Response
Figure 9.125. The architecture of our Web-based client project.
1. |
Launch NetBeans IDE and go to File > New Project item to open the New Project |
|
|
wizard. Select the Java Web from the Categories list and Web Application from the |
|
|
Projects list, then click o the Next button to go to the next wizard. |
|
2. |
Enter WebClientOracle into the Project |
Name field as this new project’s name. Make |
|
sure that the desired folder in which you want to save this project is included in the |
|
|
Project Location field and the Set |
as Main Project checkbox has been |
|
checked, then click on the Next button. |
|
3.In the opened Server and Settings wizard, make sure that the GlassFish v3 server has been selected as the Web server for this Web application, and the Java EE 6 Web has been selected for this application. Refer to Section 5.3.5.2.2 in Chapter 5 to add this server to the NetBeans IDE if you have not done this. Click on the Next button to continue.
4.Select the JavaServer Faces as the Framework for this application and click on the Finish button to complete this new Web application creation process.
Since we need a JavaServer Face as a view to query and manipulate data against the Course table in our sample database, we need to add the CoursePage.jsp we built in the project JavaWebDBJSPOracle in Chapter 8 into our current project. Perform the following operations to complete this Web page addition process:
1.Open the JSP Files folder that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1), copy the CoursePage.jsp file from that folder.
2.In the NetBeans IDE, open our project WebClientOracle and click on the Files button to open the Files window. Then right click on the web node under our current project WebClientOracle and select the Paste item to paste this JSF page into our current project.
Next, we need to create a Java managed bean class CourseBean.java and copy the codes from the managed bean CourseBean.java we built in the Web application project JavaWebDBJSPOracle, and paste them into our managed bean class CourseBean.java in our Web-based client project.
9.16.2 Create a Java Managed Bean CourseBean and Add the JDialog Class MsgDialog
Perform the following operations to create this Java managed bean and add a MsgDialog class into our current project:
1.Right click our Web-based client project WebClientOracle from the Projects window and select New > Other item to open the New File wizard.
892 Chapter 9 Developing Java Web Services to Access Databases
2. On the opened wizard, select JavaServer Faces from the Categories and JSF Managed Bean from the File Types list, respectively. Then click on the Next button.
3.Name this managed bean as CourseBean, enter webclient into the Package field, and select the session from the Scope combo box.Then click on the Finish button to complete this JSF managed bean creation process.
4.Double click on our new created managed bean CourseBean.java to open its code window.
5.Now open the Web application project JavaWebDBJSPOracle we built in Chapter 8. You can find and download this project from the folder DBProjects\Chapter 8 at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
6.Expand the package JavaWebDBJSPOracle and copy all codes inside the managed bean class CourseBean (exclude the imported packages at the top of this file).
7.In our opened managed bean CourseBean.java, paste all copied codes inside this class.
Now perform the following operations to add an MsgDialog class into our current project:
1.Launch the NetBeans IDE and open the Web application project JavaWebDBJSPSQL. You can find and download this project from the folder DBProjects\Chapter 8 at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
2.Expand the package JavaWebDBJSPSQL and copy the file MsgDialog.java.
3.Open our Web-based client project WebClientOracle and right click on the webclient node and select the Paste item to paste this class into our project.
Next, let’s do some modifications to the Java managed bean class to make it our bean class.
Perform the following modifications to this class:
1.Remove the first EJB injection line @EJB from this file.
2.Remove the second line, which is the session bean declaration statement private CourseSessionBean courseSessionBean; from the class file.
3.Remove all codes inside the following methods except the last line return null:
A.Select()
B.Details()
C.Update()
D.Delete()
4.Remove the default constructor public CourseBean() {}.
5.Add an import statement, import java.util.List;, to the top of this file.
6.Click on the Clean and Build Main Project button to compile the project.
Before we can develop the codes for the Java managed bean to perform course data query and manipulation, we need first to add a Web service reference to our current Web-based client project to enable our client to recognize our Web service and its operations.
9.16 Build a Web-Based Web Client Project to Consume the Web Service 893
9.16.3 Create a Web Service Reference for Our Web-Based Client Project
Perform the following operations to set up a Web service reference for our client project:
1.Right click on our client project WebClientOracle from the Projects window, and select the New > Other item to open the New File wizard.
2.On the opened New File wizard, select Web Services from the Categories and Web
Service Client from the File Types list, respectively. Click on the Next button to continue.
3.Click on the Browse button for the Project field and expand our Web application project WebServiceOracleApp, and click on our Web service project WebServiceOracle to select it. Then click on the OK button to select this Web service. Your finished Web Service Client wizard should match the one that is shown in Figure 9.126.
4.Click on the Finish button to complete this Web service reference setup process.
Immediately, you can find that a new node named Web Service References has been created and added into our client project. Expand this node and you can find the associated Web service port and all our five Web service operations under that node.
A point to be noted is that you must deploy our Web service project first before you can add this Web Reference to any client project.
Figure 9.126. The finished New Web Service Client wizard.
894 Chapter 9 Developing Java Web Services to Access Databases
Since the action and value attributes of all tags in our CoursePage.jsp have been bound to the associated properties and methods defined in our Java managed bean CourseBean, we only need to develop the codes for those methods defined in the Java managed bean CourseBean one by one to perform data actions against the Course table in our sample database by calling the associated operations defined in our Web service project.
9.16.4 Develop the Codes to Call Our Web Service Project
The relationship between each method defined in our Java managed bean and each operation in our Web service is shown in Table 9.12.
Let’s start from the first method Select() defined in our managed bean CourseBean to query all course_id based on the selected faculty member.
9.16.4.1 Build Codes for the Select Button Method to Query CourseIDs
The function of this method is to query all course_id taught by the selected faculty member from the Course table when the Select button is clicked by the user. The queried result is returned and displayed in a Select-One-Listbox in the CoursePage. jsp page.
First, let’s add our Web service operation QueryCourseID() into this Select() method by performing the following operations:
1.Open the code window of our Java managed bean CourseBean.java and browse to the
Select() method.
2.Browse to the Web Service References node under our client project
WebClientOracle.
3.Expand our Web service until all our five Web service operations have been exposed.
4.Drag the QueryCourseID operation and place it inside the Select() method.
5.A piece of codes is automatically created and added into this method, which is shown in Figure 9.127.
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 course record query requirements. Enter the codes that are shown in Figure 9.128 into this method, and the modified codes have been highlighted in bold.
Table 9.12. The relationship between each bean method and each operation
Method in CourseBean |
Web Service Operation |
Function |
|
Select() |
QueryCourseID() |
Query all course_id taught by the selected faculty |
|
Details() |
QueryCourse() |
Query detailed information for selected course_id |
|
Update() |
UpdateCourse() |
Update an existing course record in the Course table |
|
Delete() |
DeleteCourse() |
Delete a course record from the Course table |
9.16 Build a Web-Based Web Client Project to Consume the Web Service 895
public String Select() {
Atry { // Call Web Service Operation
Borg.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();
//TODO initialize WS operation arguments here
Cjava.lang.String fname = "";
//TODO process result here
Djava.util.List<java.lang.Object> result = port.queryCourseID(fname); System.out.println("Result = "+result);
E} catch (Exception ex) {
//TODO handle custom exceptions here
}
return null;
}
Figure 9.127. The automatically created and added codes.
public String Select() {
AArrayList<String> cList = new ArrayList<String>(); courseList = new ArrayList();
try { // Call Web Service Operation
org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort(); // TODO process result here
BcList = (ArrayList)port.queryCourseID(getFacultyName());
Cfor (int col = 0; col < cList.size(); col++) {
SelectItem courseid = new SelectItem(cList.get(col).toString()); courseList.add(courseid.getValue());
}
D } catch (Exception ex) { msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);
}
E return null;
}
Figure 9.128. The modified codes for the Select() method.
Let’s have a closer look at this piece of modified codes to see how it works.
A.Two ArrayList instances are created first since we need to use them to perform the course_id query and store queried result.
B.The Web service operation QueryCourseID() is called to get all course_id taught by the selected faculty member that works as an argument for this operation. The queried result is returned and assigned to the first ArrayList instance cList.
C.A for loop is used to pick up each queried course_id and add it into the courseList Listbox in our CoursePage.jsp page. Here, a tricking issue is that you must convert the courseList that is a List instance to an ArrayList object, and then you can use the add() method to add all queried course_id into this courseList since the List is an abstract class. Otherwise, you may encounter some null reference exception when your project runs.
896 Chapter 9 Developing Java Web Services to Access Databases
Figure 9.129. The course_id queried result for the selected faculty member.
D.The catch block is used to track and display any possible exception during this course_id query process.
E.Finally, a null is returned. Since we never use this returning value in this application, it is not important to us.
During the coding process, you may encounter some real-time compiling errors. Most of these errors are introduced by missing some packages that contain classes or components used in this file. To fix these errors, just right click on this code window and select the Fix Imports item to load and import those missed packages to the top of this code window.
Now we have finished all coding process for the course_id query action. Let’s build and run our Web-based client project to test its function. Click on the Clean and Build Main Project button to build our client project. If everything is fine, deploy our client project by right clicking on our client project WebClientOracle and choose the
Deploy item.
Run our client project by right clicking on our JSF page CoursePage.jsp from the Projects window and choose the Run File item.
On the opened JSF page, which is shown in Figure 9.129, enter a desired faculty name, such as Ying Bai, into the Faculty Name field. Then click the Select button to query all course_id taught by this selected faculty member. The query result is returned and displayed in the courseList Listbox on this page, as shown in Figure 9.129.
Our Web client project to consume our Web service operation QueryCourseID() is successful! A complete Web client project WebClientOracle 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 discuss how to consume the Web service operation QueryCourse() to get detailed course information for a given course_id from our sample Oracle database.
9.16 Build a Web-Based Web Client Project to Consume the Web Service 897
9.16.4.2 Build Codes for the Detail Button Method to Get Course Details
Now let’s do the coding for the Details() method in our Java managed bean CourseBean. java to call a Web service operation QueryCourse() to get detailed course information for a given course_id.
The function of this method is to query detailed course information for a given course_id via the Web service operation QueryCourse() as the Details button in our JSF page CoursePage.jsp is clicked by the user. The queried result is returned and displayed in five text fields in that page.
First, let’s add our Web service operation QueryCourse() into this Details() method by performing the following operations:
1.Open the code window of our Java managed bean CourseBean.java and browse to the
Details() method.
2.Browse to the Web Service References node under our client project WebClientOracle.
3.Expand our Web service until all our five Web service operations have been exposed.
4.Drag the QueryCourse operation and place it inside the Details() method.
5.A piece of codes is 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.
Now let’s do some modifications to this piece of codes and add some codes to meet our course details query requirements. Enter the codes that are shown in Figure 9.130 into this method, and the modified codes have been highlighted in bold.
Let’s have a closer look at this piece of modified codes to see how it works.
A.An ArrayList instance al is created first since we need to use it to collect and store the result of querying the detailed course information from our Course table.
B.We need to check whether a valid course_id has been selected by the user from the CourseList Listbox in our JSF page. If a valid course_id has been chosen, the Web service
public Boolean Details() {
AArrayList<String> al = new ArrayList<String>();
try { // Call Web Service Operation
org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();
Bif (selectedItem != null) {
al = (ArrayList)port.queryCourse(selectedItem);
CcourseName = al.get(1).toString(); credit = al.get(2).toString(); classroom = al.get(3).toString(); schedule = al.get(4).toString();
enrollment = al.get(5).toString();
}
D } catch (Exception ex) { msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);
}
E return null;
}
Figure 9.130. The modified codes for the Details() method.
