Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
778
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

878 Chapter 9 Developing Java Web Services to Access Databases

private void cmdSelectActionPerformed(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 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

}

}

Figure 9.110. The automatically created and added codes.

private void cmdSelectActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

A ArrayList<String> al = new ArrayList<String>(); String[] cResult = new String[6];

try { // Call Web Service Operation

org.ws.oracle.WebServiceOracleService service = new org.ws.oracle.WebServiceOracleService(); org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();

// TODO process result here

Bal = (ArrayList)port.queryCourseID(ComboName.getSelectedItem().toString());

Cfor (int col = 0; col < al.size(); col++)

cResult[col] = al.get(col).toString();

DCourseList.setListData(cResult);

E} catch (Exception ex) { msgDlg.setMessage("exception is: " + ex);

msgDlg.setVisible(true);

}

}

Figure 9.111. The modified codes for the cmdSelectActionPerformed() method.

ComboName combo box. The query result is returned and assigned to the local ArrayList instance al.

C.A for loop is used to pick up each course_id and assign it to each element in the cResult[] array.

D.The converted query result is sent to the Course ID List variable, CourseList, to have it displayed in there using the setListData() method.

E.The catch block is used to track and display any possible exception during this course_id query process.

Now we have finished the coding process for calling the Web service operation QueryCourseID() to query all course_id based on the selected faculty member. 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_id query function. Select the CourseFrame as our main class and click on the OK button to the Run Project dialog to run our project.

9.15 Build a Windows-Based Web Client Project to Consume the Web Service 879

Figure 9.112. The running result of the course_id query.

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, as shown in Figure 9.112.

You can try to query course_id for other faculty members. Our client project in querying course_id is successful.

Next, let’s take care of the coding for the CourseListValueChanged() method to query the detailed course information for a selected course_id from the Course ID List.

9.15.4.2 Build Codes for the CourseListValueChanged() Method to Get Course Details

The function of this method is that when a user clicks a course_id from the Course ID

List box, the detailed course information, such as the course title, credit, classroom, schedule, and enrollment for the selected course_id, will be retrieved and displayed in six text fields in this CourseFrame form window.

Perform the following operations to build the codes for this method to perform this function:

1.Open our client project WinClientOracle if it has not been opened, and open our main GUI CourseFrame.java by double clicking on it.

2.Click on the Design button on the top of the window to open the GUI window, and

right click on our Course ID List Listbox and select Events > ListSelection > valueChanged item to open this method.

3.Go to the Projects window and browse to our Web Service References node; expand this node until all of our five Web service operations are exposed. Drag the QueryCourse operation and place it into this method.

4.A piece of codes is created and added into this method, as shown in Figure 9.113.

880 Chapter 9 Developing Java Web Services to Access Databases

private void CourseListValueChanged(javax.swing.event.ListSelectionEvent 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 courseID = "";

//TODO process result here

Djava.util.List<java.lang.Object> result = port.queryCourse(courseID); System.out.println("Result = "+result);

E} catch (Exception ex) {

//TODO handle custom exceptions here

}

}

Figure 9.113. The automatically created and added codes.

private void CourseListValueChanged(javax.swing.event.ListSelectionEvent evt) { // TODO add your handling code here:

AArrayList<String> al = new ArrayList<String>();

BJTextField[] cField = {CourseIDField, CourseField, CreditField, ClassroomField, ScheduleField, EnrollField};

Cif(!CourseList.getValueIsAdjusting() ) {

String courseid = (String)CourseList.getSelectedValue();

D if (courseid != null){

try { // Call Web Service Operation

org.ws.oracle.WebServiceOracleService service = new org.ws.oracle.WebServiceOracleService(); org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();

// TODO initialize WS operation arguments here

Eal = (ArrayList)port.queryCourse(courseid);

Ffor (int col = 0; col < al.size(); col++)

cField[col].setText(al.get(col).toString()); G } catch (Exception ex) {

msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);

}

}

}

}

Figure 9.114. The modified codes for the CourseListValueChanged() method.

It is unnecessary to explain the function of this piece of codes line by line since all 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 query requirements. Enter the codes that are shown in Figure 9.114 into this method, and the modified codes have been highlighted in bold.

Let’s have a closer look at this piece of new added codes to see how it works.

A.An ArrayList instance al is created first, and it is used to collect the query result stored in an ArrayList object that is returned from the execution of the Web service operation

QueryCourse().

B.A JTextField array cField[] is created and initialized with six text fields in this CourseFrame form. The purpose of this array is to store queried course details and display them in these six text fields.

C.Since the JList component belongs to the javax.swing package, not java.awt package, therefore, a clicking on an entry in the CourseList box causes the itemStateChanged() method to fire twice. Once when the mouse button is depressed, and once again when it

9.15 Build a Windows-Based Web Client Project to Consume the Web Service 881

is released. Therefore, the selected course_id will be appeared twice when it is selected. To prevent this from occurring, the getValueIsAdjusting() method is used to make sure that no item has been adjusted to be displayed twice. Then the selected course_id is assigned to a local String variable courseid by calling the getSelectedValue() method of the CourseList Box class.

D.Before we can proceed to the course query operation, first we need to confirm that the selected courseid is not a null value. A null value would be returned if the user did not select any course_id from the CourseList box; instead, the user just clicked on the Select button to try to find all courses taught by other faculty members. Even the user only clicked on the Select button without touching any course_id in the CourseList box; however, the system still considers that a null course_id has been selected and thus a null value will be returned. To avoid that situation from occurring, an if selection structure is used to make sure that no null value has been returned from the CourseList box.

E.The Web service operation QueryCourse() is called to perform this course data query to collect detailed course information for the selected course_id.The query result is returned and assigned to the local ArrayList instance al. A cast (ArrayList) is necessary for this assignment since the data type of al is an ArrayList<String> in this method.

F.A for loop is used to pick up each piece of detailed course information and assign it to each text field in the cField[] array using the setText() method.

G.The catch block is used to track and display any possible exception during this course_id query process.

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 the coding process for calling the Web service operation QueryCourse() to query detailed course information 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 query 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 get course details for a selected course_id, just click on that course_id from the Course ID List. Figure 9.115 shows an example of course details for a course_id that is CSE-438.

You can try to click the different course_id to get related detailed course information. Our client project in querying detailed course information is successful.

A point to be noted is that before you can run any client project to consume a Web service, make sure that the Web service has been successfully deployed and the Glassfish v3 server is running. To confirm this, just build and deploy the Web service one more time before you run the client project to consume it, especially if you just start or restart the NetBeans IDE since the server will be stopped when the IDE is exited.

882 Chapter 9 Developing Java Web Services to Access Databases

Figure 9.115. Running result for an example course_id CSE-438.

Next, let’s take care of the coding for the cmdInsertActionPerformed() method to insert a new course record into the Course table in our sample database.

9.15.4.3 Build Codes for the Insert Button Method to Insert Courses

The function of this method is to insert a new course record as the Insert button is clicked by the user. The new course record will be inserted into 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 Insert button to open this method. Perform the following operations to add the Web service operation InsertCourse() into this method:

1.Browse to the Web Service References node under our client project WinClientOracle.

2.Expand our Web service and its port until all our five Web service operations have been exposed.

3.Drag the InsertCourse operation and place it inside the cmdInsertActionPerformed() method.

4.A piece of codes is created and added into this method, as shown in Figure 9.116.

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 new course record insertion requirements. Enter the codes that are shown in Figure 9.117 into this method, and the modified codes have been highlighted in bold.

Let’s have a closer look at this piece of new added codes to see how it works.

A.Two local variables, insert and al, are created first. The first one is a Boolean variable used to hold the running result of the execution of the Web service operation InsertCourse(),

9.15 Build a Windows-Based Web Client Project to Consume the Web Service 883

private void cmdInsertActionPerformed(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.util.List<java.lang.Object> cdata = null;

//TODO process result here

Djava.lang.Boolean result = port.insertCourse(cdata);

System.out.println("Result = "+result);

E} catch (Exception ex) {

//TODO handle custom exceptions here

}

}

Figure 9.116. The automatically created and added codes.

private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

ABoolean insert = false; ArrayList al = new ArrayList();

Bal.clear();

Cal.add(0, CourseIDField.getText()); al.add(1, CourseField.getText()); al.add(2, CreditField.getText()); al.add(3, ClassroomField.getText()); al.add(4, ScheduleField.getText()); al.add(5, EnrollField.getText());

al.add(6, ComboName.getSelectedItem().toString());

try { // Call Web Service Operation

org.ws.oracle.WebServiceOracleService service = new org.ws.oracle.WebServiceOracleService(); org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();

Dinsert = port.insertCourse(al);

Eif (!insert)

System.out.println("Error in course insertion..."); F } catch (Exception ex) {

msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);

}

}

Figure 9.117. The modified codes for the cmdInsertActionPerformed() method.

and the second is an ArrayList instance used to store a new course record to be inserted into the Course table in our sample database.

B.The ArrayList instance al is cleaned up using the clear() method to make sure that the al is empty before it can store any data.

C.A group of add() methods are used to add seven pieces of new course information into the ArrayList instance. One point to be noted is that the order in which to add these course parameters must be identical with the order of assigning these parameters to the Course object in the session bean method newCourse() in our Web service project WebServiceOracle. Refer to that method to make sure that both orders are identical. An optional way to do this assignment is to create a JTextField array and use a for loop.

D.The Web operation InsertCourse() is called to insert this new course record stored in the argument al into the Course table via our Web service. The execution result that is a Boolean variable is returned and assigned to the local variable insert.

884Chapter 9 Developing Java Web Services to Access Databases

E.If a false is returned, which means that this course data insertion has been failed, the system println() method is used to indicate this situation.

F.The catch block is used to track and display any possible exception during this data insertion process.

Now we have finished the coding process for calling the Web service operation InsertCourse() to insert a new course record into the Course table based on the selected faculty member. 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 insertion 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 insert a new course, enter six pieces of new course information shown below into six text fields.

Course ID:

CSE-549

Course:

Fuzzy Systems

Schedule: T-H: 1:30–2:45 PM

Classroom: TC-302

Credit:

3

Enrollment:

25

Your finished CourseFrame window is shown in Figure 9.118.

Click on the Insert button to insert this new course record into the Course table in our sample database.

To test this new course insertion, there are more than one way can be used. The first way is to open the Course table to confirm this new course insertion. But the second way,

Figure 9.118. The new course record to be inserted.

9.15 Build a Windows-Based Web Client Project to Consume the Web Service 885

Figure 9.119. The confirmation of new inserted course CSE-549.

which is to use the Select button to perform a course query for the selected faculty, is an easy way. To use the second way to confirm this course insertion, keep the selected faculty member Ying Bai in the Faculty Name combo box unchanged, and just click on the Select button to query all course_id taught by this faculty. Immediately, you can find that our new inserted course CSE-549 has been retrieved and displayed in the Course ID List Listbox, which is shown in Figure 9.119.

To get detailed course information for this new inserted course, first click on any other course_id from this Listbox, then click on CSE-549 from the Course ID List Listbox. Six pieces of new inserted course information for the course CSE-549 are retrieved and displayed in six text fields, as shown in Figure 9.119.

Our new course insertion using Web service is successful.

Generally, it is recommended to remove this new inserted course from the Course table in our sample database to keep our database neat and clean. However, we will keep this inserted course right now since we need to use this record to perform the course updating and deleting actions in the following sections.

Next, let’s discuss how to perform a course updating action to update an existing course in our sample database via Web service.

9.15.4.4 Build Codes for the Update Button Method to Update Courses

The function of this method is to update an existing course record as the Update button is clicked by the user. The existing course record will be updated in 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 Update button to open this method. Perform the following operations to add the Web service operation UpdateCourse() into this method:

886Chapter 9 Developing Java Web Services to Access Databases

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 UpdateCourse operation and place it inside the cmdUpdateActionPerformed() method.

4.A piece of codes is automatically created and added into this method, which is shown in Figure 9.120.

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 updating requirements. Enter the codes that are shown in Figure 9.121 into this method, and the modified codes have been highlighted in bold.

private void cmdUpdateActionPerformed(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.util.List<java.lang.Object> cdata = null;

//TODO process result here

Djava.lang.Boolean result = port.updateCourse(cdata); System.out.println("Result = "+result);

E} catch (Exception ex) {

//TODO handle custom exceptions here

}

}

Figure 9.120. The automatically created and added codes.

private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

ABoolean update = false; ArrayList al = new ArrayList();

Bal.clear();

Cal.add(0, CourseIDField.getText()); al.add(1, CourseField.getText()); al.add(2, CreditField.getText()); al.add(3, ClassroomField.getText()); al.add(4, ScheduleField.getText()); al.add(5, EnrollField.getText());

al.add(6, ComboName.getSelectedItem().toString());

try { // Call Web Service Operation

org.ws.oracle.WebServiceOracleService service = new org.ws.oracle.WebServiceOracleService(); org.ws.oracle.WebServiceOracle port = service.getWebServiceOraclePort();

Dupdate = port.updateCourse(al);

Eif (!update)

System.out.println("Error in course updating..."); F } catch (Exception ex) {

msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);

}

}

Figure 9.121. The modified codes for the cmdUpdateActionPerformed() method.

9.15 Build a Windows-Based Web Client Project to Consume the Web Service 887

This piece of codes is very similar to that we built for the Insert button’s method. Let’s have a closer look at this piece of new added codes to see how it works.

A.Two local variables, update and al, are created first. The first one is a Boolean variable used to hold the running result of the execution of the Web service operation UpdateCourse(), and the second is an ArrayList instance used to store a updating course record to be updated in the Course table in our sample database.

B.The ArrayList instance al is cleaned up using the clear() method to make sure that the al is empty before it can store any data.

C.A group of add() methods are used to add six pieces of updated course information into the ArrayList instance (The first parameter is a course_id that works as an updating criterion and will not be updated.). One point to be noted is that the order in which to add these course parameters must be identical with the order of assigning these parameters to the Course object in the session bean method setCourse() in our Web service project WebServiceOracle. Refer to that method to make sure that both orders are identical. An optional way to do this assignment is to create a JTextField array and use a for loop.

D.The Web operation UpdateCourse() is called to update this existing course record via our Web service. The execution result, which is a Boolean variable, is returned and assigned to the local variable update.

E.If a false is returned, which means that this course data updating has failed; the system println() method is used to indicate this situation.

F.The catch block is used to track and display any possible exception during this data updating process.

Now, we have finished the coding process for calling one of our Web service operations, UpdateCourse(), to update an existing course record in the Course table based on the selected faculty member. 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 updating 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 update an existing course CSE-549, enter six pieces of updated course information shown below into six text fields.

Course ID:

CSE-549

Course:

Modern Controls

Schedule: M-W-F: 11:00–11:50 AM

Classroom: TC-206

Credit:

3

Enrollment:

18

Your finished CourseFrame window is shown in Figure 9.122.

Click on the Update button to update this course record in the Course table in our sample database.

To test this course record updating action, there are more than one way that can be used. The first way is to open the Course table to confirm that this course has been

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]