
Practical Database Programming With Java
.pdf
788 Chapter 9 |
Developing Java Web Services to Access Databases |
|||
|
Web Server |
SQL Server |
||
HTTP |
|
2008 |
||
Request |
|
Database |
||
Java Client |
Web Services |
Java Runtime |
Database |
|
Object Method |
Server |
|||
|
|
HTTP
Response
Figure 9.19. The structure and components used in our Web services.
Figure 9.20. The finished Server and Settings wizard.
Web container or in an EJB container. In this application, we prefer to use a Web container since we are creating a Java EE 6 application.
Perform the following operations to create our Web application project
WebServiceSQLApp:
1.Launch NetBeans IDE and choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category.
2.Name the project WebServiceSQLApp and click on the Browse button to select a desired location for the project. In this application, we used the C:\Chapter 9 as our project location. Click on the Next button to continue.
3.Select GlassFish v3 as our Web container and Java EE 6 Web as the Java EE version; your finished Server and Settings wizard should match the one that is shown in Figure 9.20. Click on the Finish button to complete this new application creation process.
Now that a Web application has been created with a selected Web container, next, we can create our new Web service project WebServiceSQL.
9.5.2 Create a New Java SOAP-Based Web Service Project
WebServiceSQL
The function of this Web service is to perform data queries and manipulations to our sample SQL Server 2008 database and return the result. Perform the following operations to create this new Web service project WebServiceSQL:

9.5 Build Java Web Service Projects to Access SQL Server Database 789
Figure 9.21. The finished Name and Location wizard.
1.In the opened Projects window, right click on our new created project WebServiceSQLApp and select the New > Other menu item to open the New File wizard.
2.Select Web Services from the Categories list and Web Service from the File Types list, and click on the Next button.
3.Name the Web service WebServiceSQL and type org.ws.sql into the Package field. Leave Create Web Service from Scratch selected.
Your finished Name and Location wizard should match the one that is shown in Figure 9.21. Click on the Finish button to complete this process.
Before we can add any operation to this Web service project, we need first to add a JDialog class into our project, and we need to use this component to display the debug information during the testing process for our Web service project.
9.5.3 Add Desired Operations to the Web Service
Now let’s handle adding a JDialog component into our Web service project.
To save time, you can copy a JDialog class MsgDialog.java from most projects we built in the previous sections. For example, you can copy this JDialog class from our Web application project, JavaWebDBJSPSQL, and paste it into our current Web service, exactly, into the org.ws.sql node in our Web service project.
To do this copy and paste action, right click on this MsgDialog.java node from the project JavaWebDBJSPSQL and choose Refactor > Copy item. Select our current project WebServiceSQLApp from the Project combo box, select org.ws.sql from the To Package combo box, and click on the Refactor button to paste this JDialog into our project.The project JavaWebDBJSPSQL can be found at the folder DBProjects\Chapter 8 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

790 Chapter 9 Developing Java Web Services to Access Databases
Next, let’s handle the addition of new operations and coding for the newly added operations or methods in our Web service.
9.5.4 Add New Operations to Our Web Services to Perform Data Query
The main purpose of using the Web service in this section is to query data from the Faculty table in our sample database;therefore,we need to add one new operation QueryFaculty() to the Web service project.
Perform the following operations to add a new operation QueryFaculty() into our
Web service project:
1.Click on the Design button on the top of the window to open the Design View of our Web service project WebServiceSQL.
2.Click on the Add Operation button to open the Add Operation wizard.
3.Enter QueryFaculty into the Name field and click on the Browse button that is next to
the Return Type combo box. Type ArrayList into the Type Name field, and select the item ArrayList (java.util) from the list, and click on the OK button.
4.Click on the Add button and enter fname into the Name parameter field. Keep the default type java.lang.String unchanged and click on the OK button to complete this new operation creation process.
Your finished Add Operation wizard should match the one that is shown in Figure 9.22.
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.23 into this newly added operation. Let’s have a closer look at this piece of codes to see how it works.
Figure 9.22. The finished Add Operation wizard.

9.5 Build Java Web Service Projects to Access SQL Server Database 791
@WebService()
public class WebServiceSQL {
AConnection con = null;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
public class WebServiceSQL { @WebMethod(operationName = "TestQuery")
public ArrayList TestQuery(@WebParam(name = "fname") String fname) {
//TODO write your implementation code here:
BArrayList<String> result = new ArrayList<String>();
CString query = "SELECT * FROM Faculty WHERE faculty_name = ?"; try {
Dcon = DBConnection(con);
EPreparedStatement pstmt =con.prepareStatement(query);
Fpstmt.setString(1, fname);
GResultSet rs = pstmt.executeQuery();
HResultSetMetaData rsmd = rs.getMetaData();
Iwhile (rs.next()){
for (int colNum = 1; colNum <= rsmd.getColumnCount(); colNum++) result.add(rs.getString(colNum));
}
Jcon.close();
Kreturn result;
}
Lcatch (Exception ex) { msgDlg.setMessage("exception is: " + ex); msgDlg.setVisible(true);
return null;
}
}
}
Figure 9.23. The codes for the new operation QueryFaculty().
A.First, two class-level variables, con and msgDlg, are created. The first variable is used to hold the connection instance to our sample database, and the second is used to track and display the debug information when this Web service project is tested later.
B.An ArrayList instance result is created, and this is an array list instance used to collect and store our query result, and return to the consumption project. The reason we used this ArrayList, not List is because the former is a concrete class, but the latter is an abstract class, and a runtime exception may be encountered if an abstract class is used as a returned object to the calling method.
C.The SQL query statement is created with a positional parameter as the dynamic parameter for the query criterion faculty_name.
D.The user-defined method DBConnection() that will be built later 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.
E.A new PreparedStatement instance pstmt is declared and created to perform the query.
F.The setString() method is used to set up the actual value that is our input faculty name for the positional parameter faculty_name.
G.The query is performed by calling the executeQuery() method, and the query result is returned and stored in a ResultSet object rs.

792Chapter 9 Developing Java Web Services to Access Databases
H.To get more related information about the queried database, the getMetaData() method is executed, and the result is stored in a ResultSetMetaData instance rsmd.
I.A while and a for loop are used to pick up each column from the queried result that is stored in the ResultSet object rs. In fact, the while loop only runs one time since only one matched faculty row will be returned. The getColumnCount() method is used as the upper-bound of the for loop, since it returns the total number of queried columns in the matched faculty row.
J.The close() method is executed to disconnect the connection to our database.
K.The queried result is returned.
L.The catch block is used to track and display any exception occurred during this data query process, and a null will be returned if this situation really happened.
During the coding process, you may encounter some in-time compiling errors. The main reason for those errors is that some packages are missed. To fix these errors, just right click on any space inside this code window, and select the Fix Imports item to find and add those missed packages.
Now let’s build our user-defined method DBConnection() to set up a connection to our sample database from our Web service project.
9.5.5 Build the User-Defined Method DBConnection()
To make our Web service project simple, we will use the Java runtime object method to perform this database connection function. In the opened code window of our Web service project, enter the codes that are shown in Figure 9.24 into this service to create and define this connection method DBConnection().
private Connection DBConnection(Connection conn) {
Atry
{
//Load and register SQL Server driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
Bcatch (Exception e) {
msgDlg.setMessage("Class not found exception!" + e.getMessage()); msgDlg.setVisible(true);
}
CString url = "jdbc:sqlserver://localhost\\SQL2008EXPRESS:5000;databaseName=CSE_DEPT;";
Dtry {
conn = DriverManager.getConnection(url,"ybai","reback1956");
}
E catch (SQLException e) {
msgDlg.setMessage("Could not connect! " + e.getMessage()); msgDlg.setVisible(true);
e.printStackTrace();
}
F return conn;
}
Figure 9.24. The codes for the user-defined method DBConnection().

9.5 Build Java Web Service Projects to Access SQL Server Database 793
Let’s have a closer look at this piece of codes to see how it works.
A.A try catch block is used to perform this database connection function. First, the SQL Server JDBC driver is loaded using the forName() method.
B.The catch block is used to track and detect any possible exception for this JDBC driver loading process. The debug information will be displayed using the msgDlg object if any exception occurred.
C.Our sample SQL Server database connection URL is defined, and it is used to set up a connection to our sample database. Refer to Section 6.2.1.2.4 in Chapter 6 to get more details about this connection URL.
D.Another try block is used to set up a connection to our sample database using the getConnection() method that belongs to the DriverManager class with the username and password as arguments.
E.The catch block is used to detect and display any possible exception during this connection process.
F.The established connection object is returned to the calling method.
At this point, we have finished all coding development for our Web service used to perform queries to our Faculty table. Now let’s build and deploy our Web service project.
9.5.6 Deploy the Web Service Project and Test the Data Query Function
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.25.
Figure 9.25. The deployment result of our Web service project.

794 Chapter 9 Developing Java Web Services to Access Databases
Figure 9.26. The tested page for our Web service.
3.To test this Web service, right click on our target service output file WebServiceSQL under the Web Services node in our project, and select the Test Web Service item.
4.Enter the appropriate username and password to our GlassFish v3 server, such as admin and reback, which are the username and password we used when we load and install our GlassFish v3 server in Section 5.3.5.2.1 in Chapter 5. Click on the OK button to finish this GlassFish v3 server login process.
5.The tested page is opened and displayed as shown in Figure 9.26.
6.Enter a desired faculty name such as Ying Bai into the text field and click on the queryFaculty button to call our Web service. The running result is shown in Figure 9.27.
It can be found that the all seven pieces of queried faculty information for the selected faculty member have been retrieved, and the data query for our Faculty table is successful using our Web service.
Next, we can develop some Web client projects to consume this Web service to perform data query from the Faculty table in our sample database. In fact, as we discussed in Section 9.3.5, we can develop different kinds of Web client projects to consume a Web service. In the following sections, we will discuss two popular client projects, Windowsbased and Web-based clients, to consume our Web service to perform queries to our
Faculty table.
First, let’s discuss how to build a Windows-based client project to consume our Web service.

9.6 Build a Windows-Based Web Client Project to Consume the Web Service 795
Figure 9.27. The testing result of our Web service project.
9.6 BUILD A WINDOWS-BASED WEB CLIENT PROJECT TO CONSUME THE WEB SERVICE
To save time and space, we can use a Windows-based project SQLSelectObject we developed in Section 6.4 in Chapter 6 to build this client project. The project can be found from the folder DBProjects\Chapter 6 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
9.6.1 Copy the FacultyFrame and MsgDislog Components
as GUIs
Perform the following operations to create a GUI for our Windows-based client project WinClientSQL to consume our Web service:
1.Launch NetBeans IDE and choose the File > New Project item.
2.Select Java and Java Application from the Categories and the Projects lists, respectively. Click on the Next button.

796 Chapter 9 Developing Java Web Services to Access Databases
Figure 9.28. The finished Name and Location wizard.
3.Name the project as WinClientSQL and select a desired folder to save this project. Uncheck the Create Main Class checkbox. Your finished Name and Location wizard should match the one that is shown in Figure 9.28.
4.Go to the Wiley ftp site (refer to Figure 1.2 in Chapter 1), load and open the project
SQLSelectObject from the folder DBProjects\Chapter 6.
5.On the opened project, right click on the Faculty Frame file FacultyFrame.java under the project package node, and select the Refactor > Copy item to copy this form file.
6.On the opened Copy Class—FacultyFrame wizard, select our new project WinClientSQL from the Project combo box and remove the 1 after the FacultyFrame from the New Name field.
7.Your finished Copy Class—FacultyFrame wizard should match the one that is shown in Figure 9.29.
8.Click on the Refactor button to make a refactoring copy for this frame file.
9.Return to our new project WinClientSQL, and you can find that a copied FacultyFrame. java file has been pasted in the default package in our project.
Since we may need to use this form to test the faculty data query, insertion, updating, and deleting actions via our Web service project, now let’s perform some modifications to our copied FacultyFrame form window to make it as our desired GUI in this project.
Open our copied FacultyFrame form window and perform the following modifications to make this form as our desired GUI:
1.Remove the Query Method combo box and its label.
2.Add two more Text Fields and the associated labels shown in Table 9.1.

9.6 Build a Windows-Based Web Client Project to Consume the Web Service 797
Figure 9.29. The finished Copy Class wizard.
Table 9.1. Newly added objects in the FacultyFrame form
Type |
Variable Name |
Text |
Label |
Label1 |
FacultyID |
Text Field |
IDField |
|
Label |
Label2 |
Name |
Text Field |
NameField |
|
Your modified FacultyFrame form window should match the one that is shown in Figure 9.30.
Perform a similar operation to copy the MsgDialog.java file and paste it into our new client project. Next, let’s develop the codes to call our Web service to perform this faculty data query. However, before we can begin the coding process, we must first set up or create a Web service reference for our WinClientSQL project to enable our project to recognize that Web service and to call it when it is instructed to do that.
9.6.2 Create a Web Service Reference for Our Windows-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 WinClientSQL 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 WebServiceSQLApp, and click on our Web service project WebServiceSQL to select it.