BUILD JAVA WEB SERVICE PROJECTS TO ACCESS SQL

Một phần của tài liệu practical database aprogramming with java (Trang 660 - 668)

JAVA RUNTIME OBJECTS METHOD

9.5 BUILD JAVA WEB SERVICE PROJECTS TO ACCESS SQL

In this section, we will discuss how to access and perform queries and manipulations against SQL Server 2008 database using Java Web Services. To make our Web Services project simple, we will use the following components to fulfi ll this query and manipulation:

• Build different operations or methods in our Web services as interfaces to communicate with Web clients that will be built in the future to perform desired data actions.

• Use runtime object method to actually access and query our sample SQL Server 2008 database.

The structure and components used in our Web services are shown in Figure 9.19 . Now let ’ s create our fi rst Web service project WebServiceSQL to perform data query and manipulation against our sample database.

9.5.1 Create a New Java Web Application Project WebService SQLA pp

When creating a new Web service application project, we need to select a desired con- tainer to deploy our Web service. Generally, we can either deploy our Web service in a

c09.indd 787

c09.indd 787 7/20/2011 11:12:48 AM7/20/2011 11:12:48 AM

www.traintelco.com

Web container or in an EJB container. In this application, we prefer to use a Web con- tainer 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 fi nished 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 WebService SQL

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 :

Figure 9.19. The structure and components used in our Web services.

Web Services

Web Server HTTP

Request

HTTP Response

SQL Server 2008 Database Java Runtime

Object Method

Database Server Java Client

Figure 9.20. The fi nished Server and Settings wizard.

Figure 9.21. The fi nished 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 fi eld.

Leave Create Web Service from Scratch selected.

Your fi nished 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 fi rst 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 ).

c09.indd 789

c09.indd 789 7/20/2011 11:12:48 AM7/20/2011 11:12:48 AM

www.traintelco.com

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 fi eld and click on the Browse button that is next to the Return Type combo box. Type ArrayList into the Type Name fi eld, 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 fi eld. Keep the default type java.lang.String unchanged and click on the OK button to complete this new opera- tion creation process.

Your fi nished 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 fi nished Add Operation wizard.

A. First, two class - level variables, con and msgDlg , are created. The fi rst 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 - defi ned method DBConnection() that will be built later is called to set up a con- nection 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 .

Figure 9.23. The codes for the new operation QueryFaculty().

A

B C D E F G H I

J K L

@WebService()

public class WebServiceSQL { Connection 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:

ArrayList<String> result = new ArrayList<String>();

String query = "SELECT * FROM Faculty WHERE faculty_name = ?";

try {

con = DBConnection(con);

PreparedStatement pstmt =con.prepareStatement(query);

pstmt.setString(1, fname);

ResultSet rs = pstmt.executeQuery();

ResultSetMetaData rsmd = rs.getMetaData();

while (rs.next()){

for (int colNum = 1; colNum <= rsmd.getColumnCount(); colNum++) result.add(rs.getString(colNum));

}

con.close();

return result;

}

catch (Exception ex) {

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

msgDlg.setVisible(true);

return null;

} } }

c09.indd 791

c09.indd 791 7/20/2011 11:12:49 AM7/20/2011 11:12:49 AM

www.traintelco.com

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 fi x these errors, just right click on any space inside this code window, and select the Fix Imports item to fi nd and add those missed packages.

Now let ’ s build our user - defi ned method DBConnection() to set up a connection to our sample database from our Web service project.

9.5.5 Build the User - Defi ned 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 defi ne this connection method DBConnection() .

Figure 9.24. The codes for the user - defi ned method DBConnection().

A

B

C D

E

F

private Connection DBConnection(Connection conn) { try

{

//Load and register SQL Server driver

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

}

catch (Exception e) {

msgDlg.setMessage("Class not found exception!" + e.getMessage());

msgDlg.setVisible(true);

}

String url = "jdbc:sqlserver://localhost\\SQL2008EXPRESS:5000;databaseName=CSE_DEPT;";

try {

conn = DriverManager.getConnection(url,"ybai","reback1956");

}

catch (SQLException e) {

msgDlg.setMessage("Could not connect! " + e.getMessage());

msgDlg.setVisible(true);

e.printStackTrace();

}

return conn;

}

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

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 defi ned, 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 getCon- nection() method that belongs to the DriverManager class with the username and pass- word 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 fi nished 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 fi ne, a successful deployment result should be dis- played, as shown in Figure 9.25 .

c09.indd 793

c09.indd 793 7/20/2011 11:12:49 AM7/20/2011 11:12:49 AM

www.traintelco.com

3. To test this Web service, right click on our target service output fi le 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 fi nish 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 fi eld and click on the query- Faculty 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, Windows - based 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.

Figure 9.26. The tested page for our Web service.

Figure 9.27. The testing result of our Web service project.

Một phần của tài liệu practical database aprogramming with java (Trang 660 - 668)

Tải bản đầy đủ (PDF)

(791 trang)