Create a Web Service Reference for Our Window-Based Client Project – Develop Java Web Services to Access Databases

9.6.2  Create a Web Service Reference for Our Window-Based Client Project

Perform the following operations to set up a Web service reference for our client project:

1) Build and deploy our Web Service application project, WebAppFaculty, first to make sure that the Web Service is available to our client project.

2) Right-click on our client project WinClientFaculty _ Select in the Projects window, and select the New > Other item to open the New File wizard.

3) In 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.

4) Click on the Browse button for the Project field and expand our Web application proj-ect WebAppFaculty, and click on our Web service WebServiceFaculty to select it. Then click on the OK button to select this Web service. Your finished Web Service Client wizard should match the one shown in Figure 9.33.

5) Click on the Finish button to complete the Web service reference setup process.

Immediately, you can see a new node named Web Service References has been created and added to our client project. Expand this node, and you can see the associated Web service port and our Web service operations, such as QueryFaculty() and QueryImage(), under that node.

FIGURE 9.33  The finished New Web Service Client wizard.

Now let’s develop the code to call the Web service to perform the data query from the Faculty Table in our sample database.

9.6.3  Develop the Code to Call Our Web Service Project

The coding process is divided into two parts: the modification to the original code and creation of new code. First let’s do some modifications to the original code in the FacultyFrame class. Perform the following code modifications to make this project our Web consuming project:

1) Double-click on our new copied FacultyFrame.java file from our project to open it.
2) Click on the Source button at the top to open the code window.

3) Go to the constructor of this class, and remove all three query methods from the ComboMethod object.

4) Open the SelectButtonActionPerformed() event handler and remove all code inside this event handler.

Now let’s develop some new code to perform the faculty data query by calling our Web service operations.

In the Design view of the FacultyFrame form window, double-click on the Select button to open its event method, SelectButtonActionPerformed(). Then enter the code shown in Figure 9.34 into this method. The new added and modified code is in bold.
Let’s have a closer look at this piece of code to see how it works.

A. Some useful packages and classes related to Java development, such as image, imageio, swing and File, are imported first since we need to use some related classes defined in those packages to perform data and image queries and display in this Form.

B. A new ArrayList instance, al, is created to receive and hold the query result.
C. A try-catch block is used to call our Web service to perform the faculty data query operation. First a new Web service instance, service, is created based on our Web ser-vice class, WebServiceFaculty _ Service. Starting with NetBeans IDE 7, the syntax to create a new service has changed, and an underscore is used between the service class name and the Service keyword to represent the service class. Similarly, a service port is also generated by calling a system method, getWebServiceFacultyPort(), to get the current port used by our Web service. This port is returned and assigned to a new port instance, port.

FIGURE 9.34   The modified code for the SelectButtonActionPerformed() method.

Build and Run Our Client Project to Query Faculty Data via Web Service – Develop Java Web Services to Access Databases

9.6.4   Build and Run Our Client Project to Query Faculty Data via Web Service

Prior to building and running our client project, make sure that our Web Service application project, WebAppFaculty, has been built and deployed. 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.

A message box may pop up to request the main starting class. Just select our FacultyFrame class as the starting class, and click on the OK button to run the project. The FacultyFrame form window is displayed, as shown in Figure 9.36.

Select a desired faculty member, such as Debby Angles, from the Faculty Name combo box, and click on the Select button to query the detailed information for this faculty member via our Web service WebServiceFaculty. The queried result is displayed in the form, as shown in Figure 9.36. You can try to select any other faculty member to test the faculty data query function to confirm the correctness of our client and service projects.

Next let’s build a Web-based client project to consume our Web service WebServiceFaculty to perform a faculty data query action.

FIGURE 9.36   The run result of our client project.

FIGURE 9.37   The architecture of our Web-based client project.

9.7   BUILD A WEB-BASED CLIENT PROJECT TO CONSUME THE WEB SERVICE

To save time and space, we can use some components in the Web application project JavaWebOracleSelect we developed in Chapter 8 to build our Web-based client-consuming proj-ect WebClientFaculty _ Select in this section. In fact, we will use the Faculty.jsp and FacultyProcess.jsp files to build this Web-based consuming project to query faculty data from our sample Oracle database.

The structure of this Web-based client project is shown in Figure 9.37.

Create a Web-Based Client Project WebClientFaculty _ Select – Develop Java Web Services to Access Databases

9.7.1  Create a Web-Based Client Project WebClientFaculty _ Select

Perform the following steps to create a new Web application project, WebClient Faculty _ Select:

1) Launch NetBeans IDE 12.0 and go to File > New Project to open the New Project wizard. Expand the Java with Ant folder and select Java Web from the Categories list and Web Application from the Projects list. Click theNext button to go to the next wizard.
2) Enter WebClientFaculty _ Select into the Project Name field as this new proj-ect’s name. Select a desired folder, such as C:\Class DB Projects\Chapter 9, to save this project in the Project Location field, and click on the Next button.

3) In the opened Server and Settings wizard, make sure that GlassFish Server has been selected as the Web server for this Web application and Java EE 7 Web ver-sion has been also selected for this project. Click on the Next button to continue.

4) In the next wizard, Frameworks, just click on the Finish button to complete the new Web application creation process.

Since we need a Faculty page as a view to query data from the Faculty Table in our sample database, we need to add the Faculty.jsp and FacultyProcess.jsp files we built in the proj-ect JavaWebOracleSelect in Chapter 8 into our current project. Perform the following opera-tions to complete the Web page addition process:

1) Open the NetBeans IDE 12.0 and the project JavaWebOracleSelect that is located in the Class DB Projects\Chapter 8 folder in the Students folder on the CRC Press ftp site, and copy two files, Faculty.jsp and FacultyProcess.jsp, from the Web Pages folder.

2) Open our new project, WebClientFaculty _ Select, and paste the two copied files from step 1 into the folder Web Pages under our new project, WebClientFaculty _ Select.

Next we need to create a Java managed bean class, FacultyMBean.java, copy the code from the managed bean FacultyQuery.java we built in the Web application project JavaWebOracleSelect and paste it into our managed bean class FacultyMBean.java in our Web-based client project.

9.7.2  Create a Java Managed Bean Class, FacultyMBean

Perform the following operations to create the Java managed bean in our current project:

1) Right-click our Web-based client project, WebClientFaculty _ Select, in the Projects window and select New > Java Class item to open the New Java Class wizard.

2) In the opened wizard, enter FacultyMBean into the Class Name field and enter web-client into the Package field.
3) Then click on the Finish button to complete the Java managed bean creation process.
4) Double-click on our new created managed bean, FacultyMBean.java, to open its code window.

5) Now open the Web application project JavaWebOracleSelect we built in Chapter 8. You can find and download this project in the folder Class DB Projects\Chapter 8 in the Students folder at the CRC Press ftp site (refer to Figure 1.2 in Chapter 1).

6) Expand the package JavaWebOracleSelectPackage and copy all code inside the man-aged bean class FacultyQuery.java (exclude the imported packages at the top of this file).
7) In our opened managed bean FacultyMBean.java, paste all copied code inside this class.

Let’s first do some initial modifications to the FacultyMBean.java class file to make it our new Java Bean class (more modifications will be made later):

1) Change the class name from FacultyQuery to FacultyMBean. Change the construc-tor’s name from FacultyQuery() to FacultyMBean().
2) Remove the class MsgDialog and its object msgDlg code line, since we need to use theSystem.out.println() to replace it.
3) Replace all msgDlg.setMessage() and msgDlg.setVisible() with System. out.println() method.

4) Remove all original code inside the FacultyMBean class constructor.

Modify Three Files to Make Them Work for Our Web Client Project 2 – Develop Java Web Services to Access Databases

Finally, let’s modify our model class FacultyMBean.java. First let’s concentrate on the QueryFaculty() method. The function of this method is to:

1) Call our Web service operation QueryFaculty() to pick up a matching faculty record from the Faculty Table in our sample database.
2) Assign each queried column to the associated property defined in our Java managed bean class FacultyMBean.java.

Open the file FacultyMBean.java and perform the modifications as shown in Figure 9.38. The modified lines are in bold. This is the first part of the code of this class file. The second part’s code will be shown later. Let’s have a closer look at this piece of code to see how it works.

A. The class name is changed from FacultyQuery to FacultyMBean.

B. The type of the faculty image object is changed from the Blob to the byte[[] array.
C. A new instance of our Web Service class is generated with a new Web Service port.
D. Our second operation in our Web Service project, QueryImage(), is executed to get the selected faculty image and assign it to the image byte array fbimg, which is used later.

Also, delete the whole body for the method CloseDBConnection() from this Java Bean class. Now let’s take a look at our second part of code for this model class file, which is shown in Figure 9.39. The modified parts are in bold. In fact, only the contents of one method, getFacul-tyImage(), are modified. The function of this method is to convert the faculty image file from the byte[] array to a specified image format, base64Image, to enable it to be displayed in the Faculty Image box in our view class Faculty.jsp page. The setBase64Image() method is to set this converted image to the property base64Image defined in this class, which can be used by the
image source tag in our view class later.

FIGURE 9.38   The completed code for the QueryFaculty() method.

At this point, we have completed all modifications for our three files. Before we can continue to build our project to call our Web Service, that is, to call related operations in our Web Service project to perform faculty data query from our sample database, we need to add our Web Service as a reference to our client project to enable the latter to recognize the former.

Now let’s add a Web reference to our current Web-based client project to enable our client to know our Web service and its operations.

Modify Three Files to Make Them Work for Our Web Client Project – Develop Java Web Services to Access Databases

9.7.3  Modify Three Files to Make Them Work for Our Web Client Project

We need to modify the following three class files to make them work for our client project:

1) Modify our view class, Faculty.jsp, to display the selected faculty image and to termi-nate our Web client project when the Back button is clicked by the user.

2) Modify our control class, FacultyProcess.jsp, to make decisions to perform appro-priate operations by calling related methods in our Java Bean class or our model class, and setup the correct mapping between our view and model classes.

3) Modify our Java Bean or model class, FacultyMBean.java, to handle all operations required by our control class by calling related Web service operations.

First let’s modify our view class Faculty.jsp file. Open this file and go to codeline 127, where the image source tag is assigned by the selected faculty image. Change that line from

src=“data:image/jpg;base64,${FacultyQuery.base64Image}” to src=“data:image/jpg;base64,${FacultyMBean.base64Image}”

since our new created Java Bean class is named FacultyMBean, not FacultyQuery, which was used by the previous project, JavaWebOracleSelect, we built in Chapter 8.

The next modification is to change one code line in the bottom of the JSP file, Faculty.jsp, to safely terminate our Web consume client project. Open this JSP file Faculty.jsp and browse to the bottom of that file, around line 520. Replace the original line:

with the following line:

The reason for this change is because the Faculty.jsp page in our previous projects will be returned to the Selection.jsp page if this Back button is clicked by the user, but in this Web Client project, WebClientFaculty _ Select, we only rebuild the Faculty.jsp page without using any other pages; thus, we need to modify the code in the Back button event handler to terminate this project.

Now let’s modify the FacultyProcess.jsp file to make it our new control class:

1) Replace the import package name <%@ page import=“JavaWebDBJSPSQLPackage

.” %> with our new package <%@ page import=“webclient.” %> in codeline 10.

2) Replace the original constructor line (line 20), FacultyQuery fQuery = new FacultyQuery(); with our new Java Bean class FacultyMBean fQuery = new FacultyMBean();.

3) Go to code line 40 and change the FacultyQuery to FacultyMBean, and the result of that code line should be:

request.setAttribute(“FacultyMBean”, fQuery);

4) Remove the entire block else if (request.getParameter(“Back”)!= null) {} located at the bottom, at lines 122–125, since we do not want to use the Back button to return to any other page.

Add a Web Service Reference to Our Web-Based Client Project – Develop Java Web Services to Access Databases

9.7.4  Add a Web Service Reference to Our Web-Based Client Project

Perform the following operations to set up a Web service reference for our client project:

1) Build and deploy our Web Service application project WebAppFaculty built in section 9.5.

2) Right-click on our client project WebClientFaculty _ Select in the Projects window, and select the New > Other item to open the New File wizard.

3) In the opened New File wizard, select Web Services from the Categories and Web Service Client from the File Types list. Click on the Next button to continue.
4) Click on the Browse button for the Project field and expand our Web application project WebAppFaculty, and click on our Web service project WebServiceFaculty to select it. Then click on the OK button to select this Web service. Your finished Web Service Client wizard is shown in Figure 9.40. Click on the Finish button to complete this process.

FIGURE 9.39   The second part of the code for the Java Bean class file.

FIGURE 9.40   The finished New Web Service Client wizard.

Immediately you can see a new node named Web Service References has been created and added into our client project. Expand this node, and you can see the associated Web service port and our Web service operations, QueryFaculty() and QueryImage(), under that node.

Before we can build and run our Web client project to consume our Web Service, the last job we need to do is to set up the startup page, Faculty.jsp, to enable the Java Runner to know the start-ing point. Perform the following operations to complete this job:

1) Right-click on our client project, WebClientFaculty _ Select, in the Projects window, and select the Properties item at the bottom line from the popup menu to open that wizard.
2) In the opened wizard, click on the Run node.
3) Enter ./Faculty.jsp into the Relative URL box on the right to make it our start page.

4) Click on the OK button to complete this process.

Now we are ready to build and run our client project to test its function. However before we can do that, make sure that our Web Service project WebAppFaculty has been built and deployed successfully.

Build and Run Our Client Project to Query Faculty Data via Web Service – Develop Java Web Services to Access Databases

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 every-thing is fine, click on the Run Project button on the top (green arrow) to run our client project.

On the opened Web page, which is shown in Figure 9.41, 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.41. Click on the Back button to terminate this project if you like.

Our Web client project used to consume our Web service WebServiceFaculty is success-ful! A complete Web client project, WebClientFaculty _ Select, can be found in the project folder Class DB Projects\Chapter 9 in the Students folder on the CRC Press 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 Oracle database.

9.8  BUILD JAVA WEB SERVICES TO INSERT DATA INTO THE ORACLE DATABASE

To perform a faculty record insertion to our sample database using our Web service, we need to add another operation called InsertFaculty() into our Web service project, WebServiceFaculty.

FIGURE 9.41   The test result for our Web client project.

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 12.0 and open our Web application project, WebAppFaculty, and open our Web service main class file, WebServiceFaculty.javainthe Projects window.
2) Click on the Design button at the top of the window to open the Design View of our Web service class file WebServiceFaculty.java.
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, 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 dropdown 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 shown in Figure 9.42. Click on the OK button to complete the new operation creation process.

Click on the Source button on the top of this window to open the code window of our Web service class file. Let’s build the code for this new added operation.
In the opened code window, enter the code shown in Figure 9.43 into this new added operation, InsertFaculty().
Let’s have a closer look at this piece of code to see how it works.

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

FIGURE 9.42  The complete Add Operation wizard.

Build and Run Our Client Project to Query Faculty Data via Web Service 2 – Develop Java Web Services to Access Databases

FIGURE 9.43   The code for the new operation, InsertFaculty().

B. An instance of the FileInputStream class, fis, is generated, and it is used to convert the inserted faculty image to a FileInputStream format and inserted into the database
later.
C. A new File instance, fimage, is also declared and initialized with the path or loca-tion of the inserted faculty image, which is located at the eighth position with an index of 7 in the input ArrayList that contains all eight pieces of inserted faculty information.

D. The INSERT query string is generated with eight pieces of inserted faculty information represented by eight position parameters.

E. A try-catch block is used to start this insertion action. First a valid database connec-tion is established by calling a user-defined method, DBConnection().
F. A new instance of PreparedStatement class, pstmt, is declared with seven setString() methods to set up the actual values for seven positional dynamic parameters in the insert query statement. One point to be noted is that the order of these setString() methods must be identical to the order of columns in our Faculty Table.

G. Another try-catch block is used to convert the inserted faculty image to the FileInputStream format and make it ready to be written into the database.

H. The catch block is used to check any possible exception for this conversion.

I. The exception information will be recorded into a system log file if one occurs.

J. The converted faculty image is written into the eighth positional dynamic parameter via a setBinaryStream() system method.
K. The insert action is performed by calling the executeUpdate() method, and the insert result is returned and stored in the local integer variable numInsert.

L. Some used instances, including the PreparedStatement and Connection classes, are closed since we have completed our data insertion and need to disconnect our database.
M. The executeUpdate() method will return an integer to indicate whether this data insertion is successful. If a non-zero value is returned, which means that at least one row has been inserted into our Faculty Table and this data insert action is successful, a true is returned to the client project.

N. Otherwise, no row has been inserted into our sample database, and the data insertion fails. A false is returned for that situation.
O. The catch block is used to track and display any exception during this data insert opera-tion, and a false will be returned if one occurs.

You may experience some compiling errors during this coding process, which is normal, and all of these errors are due to missing imported packages. To fix them, just right-clickany place inside the code window and select the Fix Imports item from the popup menu.

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

Deploy the Web Service Project – Develop Java Web Services to Access Databases

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 WebAppFaculty 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.44.

FIGURE 9.44   The deployment result of our Web service project.

A problem arises when testing this Web service project using the tester page, which is the input parameter array, fdata. As we know, fdata has a data type of ArrayList, and it needs to 1) create an ArrayList instance and then 2) assign a set of faculty information to that ArrayList object to call the 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 a Web client project to consume and test this Web service project.

We can develop a client project 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 Window-based client project to consume our Web service.

9.9  BUILD A WINDOW-BASED CLIENT PROJECT TO CONSUME THE WEB SERVICE

We can still use the Window-based client project WinClientFaculty _ Select we built in Section 9.6 to consume the Web service to perform the faculty data insert action. One point to be noted is that although a Web reference to our Web service was 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(). Otherwise we may encounter an exception, since the origi-nal Web service that does not include the InsertFaculty() operation.
To make things clear, we can copy the project WinClientSelect, rename it as our new Windows-based client project WinClientFaculty _ Insert and use this project to consume our Web Service project to insert a new faculty record into the Faculty Table in our sample database.

Perform the following operations to rename the project:

1) Right-click on our original Windows-based client project, WinClientFaculty _ Select, and select the Copy item from the popup menu to open the Copy Project wizard.
2) Change the project name to WinClientFaculty _ Insert in the Project Name box, and click on the Copy button to complete the project copy operation.

Now you may find that our copied project contained some errors with red error indicators. The reason for that is because of our Web Service, since we need to update our Web Service Reference for the new project WinClientFaculty _ Insert.

Refresh the Web Service Reference for Our Window-Based Client Project 2 – Develop Java Web Services to Access Databases

FIGURE 9.45   The code for the Insert button event handler.

H. The add() method is used to pick up and add eight pieces of new faculty information into this new ArrayList instance, al. These eight pieces of new faculty information are entered by the user and stored in seven text fields and a File Chooser in the 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 noted is the order of adding these text fields, which must be identical to the order of data columns in our Faculty Table.
I. A try-catch block is used to call our Web service operation, InsertFaculty(), to perform the faculty data insert action. First a new Web service instance, service, is created based on our Web service class, WebServiceFaculty _ Service. Then the getWebServiceFacultyPort() 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.

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

K. 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 failed, the msgDlg instance is used to show this situation.

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

M. The catch block is used to track and display any possible exception during the Web ser-vice operation execution.

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