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

Practical Database Programming With Java

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

808Chapter 9 Developing Java Web Services to Access Databases

2.In the NetBeans IDE, open our project WebClientSQL and click on the Files button to open the Files window.Then, right click on the web node under our project WebClientSQL and select the Paste item to paste all image files into our current project node WebClientSQL.

Now we are ready to build and run our client project to test its function.

9.7.5 Build and Run Our Client Project to Query 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, which is shown in Figure 9.39, enter a desired faculty name, such as Ying Bai, into the Faculty Name field. Then click the Select button to perform a query for this selected faculty member. The query result is returned and displayed in this page, as shown in Figure 9.39.

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 insertion into our sample SQL Server database.

9.8 BUILD JAVA WEB SERVICE TO INSERT DATA INTO THE SQL SERVER DATABASE

To perform a faculty record insertion action using our Web service, we need to add another operation or method called InsertFaculty() into our Web service project

WebServiceSQL.

Figure 9.39. The testing result for our Web client project.

9.8 Build Java Web Service to Insert Data into the SQL Server Database 809

9.8.1 Add a New Operation InsertFaculty() into Our Web Service Project

Perform the following operations to add this operation into our Web service:

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 InsertFaculty 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, and 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.40. 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.41 into this newly added operation InsertFaculty().

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

A.First, a local integer variable numInsert is created, and it is used to hold the running result of inserting a new faculty record into our sample database.

B.The SQL inserting query statement is created with seven positional parameters as the dynamic parameters for seven pieces of new faculty information to be inserted.

Figure 9.40. The complete Add Operation wizard.

810 Chapter 9 Developing Java Web Services to Access Databases

@WebMethod(operationName = "InsertFaculty")

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

//TODO write your implementation code here:

Aint numInsert = 0;

BString query = "INSERT INTO Faculty (faculty_id, faculty_name, office, " +

"phone, college, title, email) VALUES (?, ?, ?, ?, ?, ?, ?)";

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());

FnumInsert = pstmt.executeUpdate();

Gcon.close();

Hif (numInsert != 0)

return true; I else

return false;

}

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

return false;

}

}

Figure 9.41. The codes for the new operation InsertFaculty().

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 insertion query.

E.Seven setString() methods are used to set up the actual values for seven positional dynamic parameters in the inserting 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 inserting action is performed by calling the executeUpdate() method, and the inserting result is returned and stored in the local integer variable numInsert.

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

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

I.Otherwise, no row has been inserted into our sample database, and this data insertion 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 insertion process, and a false will be returned if this situation is really happened.

9.9 Build a Windows-Based Web Client Project to Consume the Web Service 811

Figure 9.42. The deployment result of our Web service project.

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

9.8.2 Deploy 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, as shown in Figure 9.42.

A problem arises when testing this Web service project 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 faculty information to that ArrayList object to call this Web service operation InsertFaculty() to perform the faculty data insertion. 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 Web service project.

Next, we can develop some Web client projects to consume this Web service to perform data insertion 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.

9.9 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 inserting action. 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 one more operation InsertFaculty() in our Web service. Otherwise,

812 Chapter 9 Developing Java Web Services to Access Databases

we would still use the old Web service that does not include this InsertFaculty() operation.

9.9.1 Refresh the Web Service Reference for Our Windows-Based Client Project

In order to call this InsertFaculty() operation in ourWeb service project WebServiceSQL, we need to refresh the Web reference in our Windows-based 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 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.

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 Windows-based client project WinClientSQL, next, let’s develop the codes in our client project to call that Web service operation InsertFaculty() to perform faculty data insertion.

9.9.2 Develop the Codes to Call Our Web Service Project

Open the 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 Insert button in this form as a trigger to start the faculty data insertion action. Therefore, double click on the Insert button to open its event method cmdInsertActionPerformed() and enter the codes that are shown in Figure 9.43 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 new faculty data array.

B.The add() method is used to pick up and add seven pieces of new faculty information into this new ArrayList instance al. Seven pieces of new faculty information are entered by the user and stored in seven text fields in this FacultyFrame window form. The toString() method is used to convert each piece of new faculty information obtained using the getText() method that returns an object data type to a String. The index is necessary since it is used to indicate the position of each parameter in this ArrayList. One point to be

9.9 Build a Windows-Based Web Client Project to Consume the Web Service 813

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

AArrayList al = new ArrayList(); al.clear();

Bal.add(0, IDField.getText().toString()); al.add(1, NameField.getText().toString()); al.add(2, OfficeField.getText().toString()); al.add(3, PhoneField.getText().toString()); al.add(4, CollegeField.getText().toString()); al.add(5, TitleField.getText().toString()); al.add(6, EmailField.getText().toString());

Ctry {

org.ws.sql.WebServiceSQLService service = new org.ws.sql.WebServiceSQLService(); org.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort();

DBoolean insert = port.insertFaculty(al);

Eif (!insert) {

 

msgDlg.setMessage("The data insertion is failed!");

 

msgDlg.setVisible(true);

 

}

F

else

 

ComboName.addItem(NameField.getText());

 

}

G

catch (Exception ex){

 

System.out.println("exception: " + ex);

 

}

}

Figure 9.43. The codes for the Insert button event method.

noted is the order of adding these text fields, which must be identical with order of columns in our Faculty table.

C.A try catch block is used to perform the calling of ourWeb service operation InsertFaculty() to perform this faculty data inserting action. First, a new Web service instance service is created based on our Web service class WebServiceSQLService. Then the getWebServiceSQLPort() method is executed to get the current port used by our Web service. This port is returned and assigned to a new Port instance port.

D.The Web service operation InsertFaculty() is executed with the ArrayList instance al that has been filled with seven pieces of new faculty information as the argument of this method. The running result of that operation is returned and assigned to a Boolean variable insert.

E.If the value of the variable insert is false, which means that no row has been inserted into our Faculty table, and this insertion has been failed, the msgDlg instance is used to show this situation.

F.Otherwise, if the value of the insert variable is true, which means that this data insertion is successful, the newly inserted faculty name will be added into the Faculty Name combo box ComboName using the addItem() method.

G.The catch block is used to track and display any possible exception during this Web service operation execution.

Now let’s build and run our client project to call and test our Web service to perform faculty data inserting action.

814 Chapter 9 Developing Java Web Services to Access Databases

Figure 9.44. The seven pieces of newly inserted faculty information.

9.9.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, 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 a new faculty record with seven pieces of new faculty information shown below into seven text fields, which is shown in Figure 9.44.

• Faculty ID:

T56789

• Name:

Tom Jeff

• Title:

Professor

• Office:

MTC-150

• Phone:

750-378-1500

• College:

University of Miami

• Email:

tjeff@college.edu

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 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 new faculty record has been inserted. To do that using the Services window in the NetBeans IDE, perform the following operations:

9.10 Build a Web-Based Client Project to Consume the Web Service 815

Figure 9.45. The opened Faculty table in the NetBeans IDE.

1.Open the Services window and expand the Databases node.

2.Right click on our SQL Server database URL: jdbc:sqlserver://localhost\ SQL2008EXPRESS: 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.45.

It can be found that the new faculty record with the faculty_id of T56789, which is located at the last row and has been highlighted in dark color, has been successfully inserted into our database.

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.

To do this checking in second way, go to the Faculty Name combo box, and you can find that the new faculty name Tom Jeff has been added into this box. Click it to 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 newly inserted faculty. Just click on the OK button for that message box, and you can find that seven pieces of newly inserted faculty information have been retrieved and displayed in this form window. Our data insertion is successful!

It is highly recommended to remove this newly 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.

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.10 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 insertion action. First, let’s refresh

816 Chapter 9 Developing Java Web Services to Access Databases

the Web service reference used for our Web-based client project to allow it to use the updated Web service operations.

9.10.1 Refresh the Web Service Reference for Our Web-Based Client Project

In order to call the InsertFaculty() operation 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.

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 operation InsertFaculty() to perform faculty data insertion.

9.10.2 Develop the Codes to Call Our Web Service Project

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 Insert commandButton in our JSF page FacultyPage.jsp and the Insert() method in our Java managed bean class FacultyMBean.java has been established. Therefore, we can concentrate on the coding for the Insert() 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 Insert() method in this class to fulfill this data insertion function.

Browse to the Insert() method and drag the Web service operation InsertFaculty under the WebService References node and place it inside the Insert() method. A piece of codes is created and added into this method, as shown in Figure 9.46.

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 insertion requirements. Enter the codes that are shown in Figure 9.47 into this method.

Let’s have a closer look at this piece of new 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 new faculty data array.

9.10 Build a Web-Based Client Project to Consume the Web Service 817

public String Insert() {

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.insertFaculty(fdata); System.out.println("Result = "+result);

E} catch (Exception ex) {

//TODO handle custom exceptions here

}

return null;

}

Figure 9.46. The automatically created codes by dragging the operation node.

public String Insert() {

A ArrayList al = new ArrayList();

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);

Bal.clear();

Cal.add(0, facultyID); al.add(1, name); al.add(2, office); al.add(3, phone); al.add(4, college); al.add(5, title); al.add(6, email);

try { // Call Web Service Operation

org.ws.sql.WebServiceSQL port = service.getWebServiceSQLPort(); // TODO initialize WS operation arguments here

DBoolean insert = port.insertFaculty(al);

Eif (!insert) {

msgDlg.setMessage("The data insertion 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.47. The modified codes for the Insert() method.

B.The clear() method is executed to make sure that the ArrayList instance is clean before a new faculty record is collected.

C.The add() method is used to pick up and add seven pieces of new faculty information into this new ArrayList instance al. Seven pieces of new faculty information are entered by the user in the JSF page FacultyPage.jsp, and stored in seven properties defined in this managed bean.

D.The InsertFaculty() operation in our Web service is called with the ArrayList instance that contains seven pieces of new faculty information as the argument. The execution result of this faculty data insertion is returned and assigned to the local Boolean variable insert.

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