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

Practical Database Programming With Java

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

818Chapter 9 Developing Java Web Services to Access Databases

E.If the returned Boolean variable insert is false, which means that this data insertion 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 insertion process.

G.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 operation to perform the faculty data inserting action.

9.10.3 Build and Run Our Client Project to Insert Faculty Data via Web Service

Click on the Clean and Build Main Project button to build our client project. If everything is fine, right click on our JSF page FacultyPage.jsp from the Projects window and choose the Run File item to run our client project.

On the opened JSF page, first, let’s perform a faculty record query by entering a desired faculty name, such as Ying Bai, into the Faculty Name field, and then click on the Select button to get details for this selected faculty member. To insert a new faculty record, enter seven pieces of new faculty information shown below into the associated seven text fields, as shown in Figure 9.48.

Faculty ID: T56789

Name:

Tom Jeff

Title:

Professor

Office:

MTC-150

Phone:

750-378-1500

College:

University of Miami

Email: tjeff@college.edu

Figure 9.48. Seven pieces of new inserted faculty information.

9.11 Build Java Web Service to Update and Delete Data from the SQL Server Database 819

Figure 9.49. The confirmation of a new faculty record insertion.

Click on the Insert button to try to call our Web service operation InsertFaculty() to insert this new faculty record into the Faculty table in our sample database.

To confirm this data insertion, two ways can be used. The first way is to open our Faculty table using either the Services window in the NetBeans IDE or the SQL Server 2008 Management Studio to check whether this new faculty record has been inserted. The second way to confirm this data insertion, which is simpler, is to use the Select button in this form to perform a query to try to retrieve the inserted faculty record.

The second way to do this checking, first, you can perform another query for the selected faculty, such as Ying Bai, and then go to the Faculty Name combo box and type the new inserted faculty name Tom Jeff into this box. Click on the Select button to try to retrieve it. Now you can find that seven pieces of new inserted faculty information have been retrieved and displayed in this page, as shown in Figure 9.49.

It is highly recommended to remove this new inserted faculty record from our database since we want to keep our database clean. You can delete this record by opening the SQL Server 2008 Management Studio to do it.

Our Web client project to consume our Web service WebServiceSQL is successful! A complete Web client project WebClientSQL 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 build a Web service to perform data updating and deleting against our sample SQL Server database.

9.11 BUILD JAVA WEB SERVICE TO UPDATE AND DELETE DATA FROM THE SQL SERVER DATABASE

To perform data updating and deleting actions against our sample SQL Server database via Web service is straightforward, and we can add two more new operations

820 Chapter 9 Developing Java Web Services to Access Databases

UpdateFaculty() and DeleteFaculty() into our Web service project WebServiceSQL we built in the previous sections. First, let’s concentrate on the faculty data updating action.

As we discussed in the previous sections, the key point to perform a faculty data updating is that in most real applications, all pieces of faculty information should be updated except the faculty_id, since it is much easier to insert a new faculty record with a new faculty_id than updating a record with an updated faculty_id because of the complexity in cascaded updating relationships we built in Chapter 2 when we create our sample database. Therefore, in this section, we will concentrate on the updating a faculty record based on an existing faculty_id.

9.11.1 Add a New Operation UpdateFaculty() to Perform the Faculty Data Updating

Perform the following operations to add a new operation UpdateFaculty() into our Web service project WebServiceSQL:

1.Launch NetBeans IDE and open our Web service project WebServiceSQLApp, and select our Web service main class file WebServiceSQL.java from the Projects window.

2.Click on the Design button on the top of the window to open the Design View of our Web service project WebServiceSQL.

3.Click on the Add Operation button to open the Add Operation wizard.

4.Enter UpdateFaculty into the Name field and click on the Browse button that is next to

the Return Type combo box. Type boolean into the Type Name field and select the item Boolean (java.lang) from the list, and click on the OK button.

5.Click on the Add button and enter fdata into the Name parameter field. Then click on the drop-down arrow of the Type combo box, select the Choose item to open the Find Type wizard. Type arraylist into the top field and select the ArrayList (java.util) data type, and click on the OK button to select an ArrayList as the data type for the input parameter.

Your finished Add Operation wizard should match the one that is shown in Figure 9.50. Click on the OK button to complete this new operation creation process.

Figure 9.50. The complete Add Operation wizard.

9.11 Build Java Web Service to Update and Delete Data from the SQL Server Database 821

@WebMethod(operationName = "UpdateFaculty")

public Boolean UpdateFaculty(@WebParam(name = "fdata") ArrayList fdata) {

//TODO write your implementation code here:

Aint numUpdated = 0;

BString query = "UPDATE Faculty SET faculty_name=?, office=?, phone=?, college=?, title=?, email=? " +

"WHERE faculty_name= ?";

try {

Ccon = DBConnection(con);

DPreparedStatement pstmt =con.prepareStatement(query);

Epstmt.setString(1, fdata.get(0).toString()); pstmt.setString(2, fdata.get(1).toString()); pstmt.setString(3, fdata.get(2).toString()); pstmt.setString(4, fdata.get(3).toString()); pstmt.setString(5, fdata.get(4).toString()); pstmt.setString(6, fdata.get(5).toString()); pstmt.setString(7, fdata.get(6).toString());

FnumUpdated = pstmt.executeUpdate();

Gcon.close();

Hif (numUpdated != 0)

return true; I else

return false;

}

J catch (Exception ex) { msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);

return false;

}

}

Figure 9.51. The codes for the new operation UpdateFaculty().

Click on the Source button on the top of this window to open the code window of our Web service project. Let’s perform the coding for this newly added operation.

On the opened code window, enter the codes that are shown in Figure 9.51 into this newly added operation UpdateFaculty().

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

A.A local integer variable numUpdated is created first, and this variable is used to hold the running result of execution of the data updating operation.

B.The updating query string is created with six positional parameters. The query criterion is the faculty name that is the seventh positional parameter and placed after the WHERE clause.

C.The user-defined method DBConnection() is called to set up a connection between our Web service and our sample database. A connection instance con is returned after the execution of this method.

D.A new PreparedStatement instance pstmt is created to perform this updating query.

E.Seven setString() methods are used to set up the actual values for seven positional dynamic updated parameters in the updating query statement. One point to be noted is that the order of these setString() methods must be identical with the order of columns in our Faculty table.

F.The updating action is performed by calling the executeUpdate() method, and the updating result is returned and stored in the local integer variable numUpdated.

822Chapter 9 Developing Java Web Services to Access Databases

G.The database connection is closed by executing the close() method, since we have completed our data updating action and need to disconnect with our database.

H.The executeUpdate() method will return an integer to indicate whether this data updating is successful or not. If a nonzero value is returned, which means that at least one row has been updated in our Faculty table and this data updating action is successful, a true is returned to the client project.

I.Otherwise, no row has been updated in our sample database, and this data updating has failed. A false is returned for this situation.

J.The catch block is used to track and display any exception occurred during this data updating process, and a false will be returned if this situation is really happened.

Next, let’s take care of the data deleting action against our sample database using Web service operation DeleteFaculty().

9.11.2 Add a New Operation DeleteFaculty() to Perform the Faculty Data Deleting

Perform the following operations to add a new operation DeleteFaculty() into our Web service project WebServiceSQL:

1.Launch NetBeans IDE and open our Web application project WebServiceSQLApp, and select our Web service main class file WebServiceSQL.java from the Projects window.

2.Click on the Design button on the top of the window to open the Design View of our Web service project WebServiceSQL.

3.Click on the Add Operation button to open the Add Operation wizard.

4.Enter DeleteFaculty into the Name field and click on the Browse button that is next to

the Return Type combo box. Type boolean into the Type Name field, and select the item Boolean (java.lang) from the list, and click on the OK button.

5.Click on the Add button and enter fname into the Name parameter field to add a new parameter for this operation. Keep the default data type java.lang.String unchanged for this new added parameter fname.

Your finished Add Operation wizard should match the one that is shown in Figure 9.52. Click on the OK button to complete this new operation creation process.

Click on the Source button on the top of this window to open the code window of our Web service project. Let’s perform the coding for this newly added operation.

On the opened code window, enter the codes that are shown in Figure 9.53 into this newly added operation DeleteFaculty().

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

A.A local integer variable numDeleted is created first, and this variable is used to hold the running result of execution of the data deleting operation.

B.The deleting query string is created with one positional parameter, which is the original faculty name that works as the query criterion and is placed after the WHERE clause.

C.A try catch block is used for this data deleting action. First, the user-defined method DBConnection() is called to set up a connection between our Web service and our sample database. A connection instance con is returned after the execution of this method.

9.11 Build Java Web Service to Update and Delete Data from the SQL Server Database 823

Figure 9.52. The complete Add Operation wizard.

@WebMethod(operationName = "DeleteFaculty")

public Boolean DeleteFaculty(@WebParam(name = "fname") String fname) {

//TODO write your implementation code here:

Aint numDeleted = 0;

BString query = "DELETE FROM Faculty WHERE faculty_name = ?"; try {

Ccon = DBConnection(con);

DPreparedStatement pstmt =con.prepareStatement(query);

Epstmt.setString(1, fname);

FnumDeleted = pstmt.executeUpdate();

Gcon.close();

Hif (numDeleted != 0)

return true; I else

return false;

}

J catch (Exception ex) { msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);

return false;

}

}

Figure 9.53. The codes for the new operation DeleteFaculty().

D.A new PreparedStatement instance pstmt is created to perform this deleting query.

E.The setString() method is used to set up the actual value for the positional dynamic parameter in the deleting query statement.

F.The deleting action is performed by calling the executeUpdate() method, and the deleting result is returned and stored in the local integer variable numDeleted.

G.The database connection is closed by executing the close() method, since we have completed our data deleting action and need to disconnect with our database.

824Chapter 9 Developing Java Web Services to Access Databases

H.The executeUpdate() method will return an integer to indicate whether this data deleting is successful or not. If a nonzero value is returned, which means that at least one row has been deleted from our Faculty table and this data deleting action is successful, a true is returned to the client project.

I.Otherwise, no row has been deleted from our sample database, and this data deleting has failed. A false is returned for this situation.

J.The catch block is used to track and display any exception occurred during this data deleting process, and a false will be returned if this situation is really happened.

At this point, we have completed all coding development for the data updating and deleting actions. Now let’s build and run our Web service project to test its functions.

9.11.3 Deploy and Test the Web Service Project

Perform the following operations to build and deploy our Web service project:

1.Click on the Clean and Build Main Project button to build our Web service.

2.Right click on our Web application WebServiceSQLApp and select the Deploy item to deploy our Web service. If everything is fine, a successful deployment result should be displayed.

A problem arises when testing the UpdateFaculty() operation of this Web service using the tester page, which is the input parameter array fdata. As we know, the fdata has a data type of ArrayList, and it needs to (1) create an ArrayList instance, and then (2) assign a group of updated faculty information to that ArrayList object to call this Web service operation UpdateFaculty() to perform the faculty data updating. However, it is difficult to do those two operations manually by using this tester page. Therefore, we need to create some Web client projects to consume and test this updating operation later.

To test the DeleteFaculty() operation, just right click on our Web service output file WebServiceSQL under the Web Services node from the Projects window, and choose the Test Web Service item to open the tester page, which is shown in

Figure 9.54.

Enter a desired faculty name to be deleted from the Faculty table in our sample database, such as Ying Bai, into the text field that is next to the deleteFaculty button, and click on the deleteFaculty button to perform this faculty data deleting action.

The testing result is shown in Figure 9.55. A true is returned, and this indicates that our data deleting action is successful.

To confirm this data deleting action, open our Faculty table by going to the Services window and expand the Databases node, and our connection URL, and finally our sample database CSE_DEPT. Expand our database schema dbo and right click on the Faculty table. Select the View Data item from the pop-up menu to open our Faculty table. On the opened Faculty table, you can find that the faculty record with the faculty name of Ying Bai has been removed from this table.

Recall that when we built our sample SQL Server database CSE_DEPT in Chapter 2, we set up a cascaded updating and deleting relationships among our five tables. Therefore, not only is a single faculty record whose name is Ying Bai has been deleted

9.11 Build Java Web Service to Update and Delete Data from the SQL Server Database 825

Figure 9.54. The tester page for our Web service project WebServiceSQL.

Figure 9.55. The testing result of the deleting operation.

826 Chapter 9 Developing Java Web Services to Access Databases

from the Faculty table when we perform this data deleting action, but also all columns related to this faculty member in other tables,such as the LogIn,Course,and StudentCourse, have also been deleted because of this cascaded relationship.

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. For your convenience, we show these deleted records in Tables 9.2–9.5, and you can add or insert them back to the related tables to complete this data recovery.

Next, we can develop some Web client projects to consume this Web service to perform data updating and deleting actions to the Faculty table in our sample database.

First, let’s discuss how to build a Windows-based client project to consume our Web service.

Table 9.2. The deleted record in the Faculty table

faculty_id

faculty_name

office

phone

college

title

email

B78880

Ying Bai

MTC-211

750-378-1148

Florida Atlantic University

Associate Professor

ybai@college.edu

 

 

 

 

 

 

 

Table 9.3. The deleted records in the Course table

course_id

course

credit

classroom

schedule

enrollment

faculty_id

CSC-132B

Introduction to Programming

3

TC-302

T-H: 1:00-2:25 PM

21

B78880

CSC-234A

Data Structure & Algorithms

3

TC-302

M-W-F: 9:00-9:55 AM

25

B78880

CSE-434

Advanced Electronics Systems

3

TC-213

M-W-F: 1:00-1:55 PM

26

B78880

CSE-438

Advd Logic & Microprocessor

3

TC-213

M-W-F: 11:00-11:55 AM

35

B78880

 

 

 

 

 

 

 

Table 9.4. The deleted records in the LogIn table

user_name

pass_word

faculty_id

student_id

ybai

reback

B78880

NULL

 

 

 

 

Table 9.5. The deleted records in the StudentCourse table

s_course_id

student_id

course_id

credit

major

1005

J77896

CSC-234A

3

CS/IS

1009

A78835

CSE-434

3

CE

1014

A78835

CSE-438

3

CE

1016

A97850

CSC-132B

3

ISE

1017

A97850

CSC-234A

3

ISE

9.12 Build a Windows-Based Web Client Project to Consume the Web Service 827

9.12 BUILD A WINDOWS-BASED WEB CLIENT PROJECT TO CONSUME THE WEB SERVICE

We can still use the Windows-based client project WinClientSQL we built in Section 9.6 to consume the Web service to perform faculty data updating and deleting actions. One point to be noted is that although a Web reference to our Web service has been established in Section 9.6, we still need to refresh this Web reference, since our Web service project has been modified by adding two more operations UpdateFaculty() and DeleteFaculty() in our Web service. Otherwise, we would still use the old Web service that does not include these two operations.

9.12.1 Refresh the Web Service Reference for Our Windows-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 client project to use the updated Web service project. Perform the following operations to refresh the Web service reference:

1.Open our Windows-based client project WinClientSQL and set it as our current project by right clicking on it and choosing the Set as Main Project item. Then expand the Web Service References node under our current project.

2.Right click on our Web service WebServiceSQLService and choose the Delete item to remove this old Web reference.

3.Right click on our Windows-based client project WinClientSQL 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 Windowsbased client project WinClientSQL, 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.

9.12.2 Develop the Codes to Call Our Web Service Project

First let’s build the codes to perform the faculty data updating action.

9.12.2.1 Build the Codes to Call the UpdateFaculty() 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 Update button in this form as a trigger

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