GETTING STARTED WITH JAVA WEB SERVICES USING NETBEANS IDE – Develop Java Web Services to Access Databases

9.4  GETTING STARTED WITH JAVA WEB SERVICES USING NETBEANS IDE

In the following sections, we will develop and build different Java Web services projects based on our Oracle Database XE 18c database system with different consuming projects to perform desired database operations.

By adding different operations or methods to our Web service projects to access and manipulate data in Tables, such as the Faculty and Course Tables, in our sample Oracle database, we can perform the following data queries and manipulations:

1) Query data from the Faculty Table in our Oracle database with QueryFaculty().
2) Insert data into the Faculty Table in our Oracle database with InsertFaculty().
3) Update and delete data against the Faculty Table in our Oracle database with the
UpdateFaculty() and DeleteFaculty() operations.
4) Query data from the Course Table in our Oracle database with QueryCourse().

FIGURE 9.19  The run result of calling our Web service.

5) Query detailed course information from the Course Table in our Oracle database with
DetailCourse().

6) Update and delete data against the Course Table in our Oracle database with the
UpdateCourse() and DeleteCourse() operations.

For each Web services project, we need to build an associated client project to consume the Web services project to test its function. The following client projects will be built:

1) Window-based client project to consume the Web service to access the Faculty and Course Tables in our Oracle database.
2) Window-based client project to consume the Web service to insert data into the Faculty and Course Tables in our Oracle database.

3) Window-based client project to consume the Web service to update and delete data against the Faculty and Course Tables in our Oracle database.
4) Web-based-based client project to consume the Web service to access the Faculty and Course Tables in our Oracle database.

5) Web-based-based client project to consume the Web service to insert data into the Faculty and Course Tables in our Oracle database.

6) Web-based-based client project to consume the Web service to update and delete data against the Faculty and Course Tables in our Oracle database.

In fact, we can develop any kind of client project to consume a Web service, either a standard Java desktop application, which is called a Window-based consume project, or a JSP page, which is called a Web-based consume project. We will develop and build different client projects to consume our Web services to enable our projects to meet real-world needs.

Let’s start with the query of the Faculty Table in our Oracle database.

BUILD JAVA WEB SERVICE PROJECTS TO ACCESS AND MANIPULATE THE FACULTY TABLE – Develop Java Web Services to Access Databases

9.5  BUILD JAVA WEB SERVICE PROJECTS TO ACCESS AND MANIPULATE THE FACULTY TABLE

In this section, we will discuss how to query and manipulate the Faculty Table against our Oracle database using Java Web services. To make our Web Services project simple, we will use the fol-lowing components to fulfill the query and manipulation actions:

  • 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.

FIGURE 9.20   The structure and components used in our Web services.

FIGURE 9.21   The finished Server and Settings wizard.

  • Use the runtime object method to actually access and query our sample Oracle database.
  • The structure and components used in our Web services are shown in Figure 9.20.
  • Now let’s create our first Web service project to perform data query and manipulation against our sample database.

9.5.1  Create a New Java Web Application Project, WebAppFaculty

When creating a new Web service application project, we need to select a desired container to deploy our Web service. Generally we can either deploy our Web service in a Web container or an EJB container. In this application, we prefer to use a Web container, since we are creating a Java EE 7 application.

Perform the following operations to create our Web application project, WebAppFaculty:

1) Launch NetBeans IDE 12.0 and choose File > New Project (Ctrl-Shift-N). Expand the Java with Ant folder, select Java Web under the Categories list and Web Application from the Projects list. Click on the Next button to continue.

2) Name the project WebAppFaculty and click on the Browse button to select a desired location for the project. In this application, we used C:\Class DB Projects\ Chapter 9 as our project location. Click on the Next button to continue.

3) Select GlassFish Server as our Web container and Java EE 7 Web as the Java EE version. Your finished Server and Settings wizard should match the one shown in Figure 9.21. Click on the Finish button to complete the 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, WebServiceFaculty.

Setup the Correct JDBC Driver and Java Platform for Our Web Service – Develop Java Web Services to Access Databases

9.5.6  Setup the Correct JDBC Driver and Java Platform for Our Web Service

Perform the following steps to complete the JDBC Driver setup process:

1) Right-click on our project, WebAppFaculty, in the Projects window and select the Properties item to open the project properties wizard.
2) Click on the Libraries node and click on the Add JAR/Folder button to open the Windows Explorer to locate our installed JDBC Driver for Oracle 18c XE, ojdbc8.jar.

3) Browse to the location where the JDBC Driver is installed (refer to Appendix H to down-load this driver). In our case, it is C:\Temp. Click the file ojdbc8.jar to select it and click on the Open and OK buttons to add it into our project.

4) Click on the drop-down arrow on the right of the Java Platform box, select JDK 1.8 and click on the Change Platform button in the popup menu to make this change valid.

Your finished Project Properties wizard should match the one shown in Figure 9.28.

Click on the OK button to complete the JDBC driver addition operation.

9.5.7  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, 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.29.

3) To test this Web service, right-click on our target service output file, WebServiceFaculty, under the Web Services node in our project, and select the Test Web Service item.
4) The tested page is opened and displayed. Then 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 run result is shown in Figure 9.30.

FIGURE 9.28  The finished Project Properties wizard.

FIGURE 9.29  The deployment result of our Web service project.

FIGURE 9.30  The test result of our Web service project.

It can be seen that all seven pieces of queried faculty information for the selected faculty member have been retrieved and displayed in the tester. Our data query for our Faculty Table is successful using our Web service.

Now let’s continue to test the second operation, QueryImage(), by clicking on the Back button to return to the original test page. Enter a desired faculty name such as Ying Bai in the text field and click on the queryImage button. The selected faculty image is [B@66c557e1.

Next we can develop a Windows or Web client project to consume this Web service to per-form a 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 client projects to consume a Web service. In the fol-lowing sections, we will discuss two popular client projects, Window-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 Window-based client project to consume our Web service.

BUILD A WINDOW-BASED CLIENT PROJECT TO CONSUME THE WEB SERVICE – Develop Java Web Services to Access Databases

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

To save time and space, we can use the Window-based project OracleSelectFaculty we developed in Section 6.3 in Chapter 6 to build our new client project, WinClientFaculty _ Select. That project can be found in the folder Class DB Projects\Chapter 6, which is located in the Students folder on the CRC Press ftp site (refer to Figure 1.2 in Chapter 1).

9.6.1  Copy the FacultyFrame and MsgDialog Components as GUIs

Perform the following operations to create a GUI for our Window-based client project,
WinClientFaculty _ Select, to consume our Web service:

1) Launch NetBeans IDE 12.0 and choose File > New Project.
2) Select Java with Ant and Java Application from the Categories and
Projects lists, respectively. Click on the Next button.
3) Name the project WinClientFaculty _ Select 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 shown in Figure 9.31. Click on the Finish button to create this project.

FIGURE 9.31   The finished Name and Location wizard.

FIGURE 9.32   The finished Copy Class wizard.

4) Go to the Students folder on the CRC Press ftp site and load and open the project OracleSelectFaculty from the folder Class DB Projects\Chapter 6.
5) In 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.

Copy Class—FacultyFrame wizard, select our new project,
WinClientFaculty _ Select, from the Project combo box and remove the 1 FacultyFrame from the New Name field. Your finished Copy Class wiz-6)Intheopenedafterthe ard is shown in Figure 9.32.
7) Click on the Refactor button to make a refactored copy of the frame file.
8) Return to our new project, WinClientFaculty _ Select, and you can see that a copied FacultyFrame.java file has been pasted in the default package in our project.
Perform a similar Refactor operation to copy the MsgDialog.java file and paste it into our new client project. Next let’s develop the code to call our Web service to perform the faculty data query. However, before we can begin the coding process, we must first setup or create a Web service reference for our WinClientFaculty _ Select project to enable our project to recognize the Web service and call it when it is instructed to do so.

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

A. Some local objects are declared first, which include a byte[] array object, bimg, and an Image object, img, and both objects are used to hold the created byte[] image array and converted Image object. Both integer variables, imgId and timeout, are used to keep the image ID and timeout value when displaying this image in the Canvas object in our client.

B. 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, a keyword _ Service must be appended after the Web Service name to create a new service object.

C. 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.

D. Now our Web Service operation, QueryImage(), is called with the selected faculty name as the argument to retrieve the selected faculty image from our sample database and assign it to our local variable bimg. One issue is that this returned object is an Image type when it is defined in our Web Service, but now we are using a byte[] array data type to hold this image. The reason for that is the default conversion by NetBeans IDE.

E. Two code lines in this section are used to convert the data type of this returned image from byte[] to Image. A ByteArrayInputStream object and ImageIO.read() method must be used for this conversion.

F. A catch block is used to detect and report any error for the conversion process.

G. In order to store our retrieved faculty image in our current project folder, the system method getProperty() with our current directory (user.dir) is used, and the current folder is assigned to a local string variable, imgPath.

H. To get the selected faculty image, we need to get the current selected or queried faculty name from the Faculty Name combo box, convert this item to a string and attach “.jpg” to the image file name. We need to use the name of this faculty image later to store and display this selected faculty image in the Canvas.

I. To save this converted faculty image in our current project folder, a new File object is gen-erated with the image path and name. A system method, ImageIO.write(), is used to complete this image-saving job.

J. To display the selected faculty image, the getImage() method that belongs to the abstract class Toolkit is executed to load the selected image. Since the Toolkit class is an abstract class, we use the getToolkit() method to create it instead of generating it by invoking its constructor. The getGraphics() method is called to get a Graphics context, and our ImageCanvas works as an image holder for this faculty image.

K. The addImage() method that belongs to the MediaTracker class is called to add our image with its ID into the tracking system.

L. A try-catch block is used to begin a tracking process, and the waitForID() method is called to execute the tracking. If a timeout occurs for the tracking process, which means

that the selected faculty image has not been loaded into the project, a warning message is displayed using our MsgDialog object, and a False is returned to indicate this error.
M. Any other possible exception or error will be caught by the catch block and be displayed in our msgDlg dialog.

N. If no timeout error happens, which means that the selected faculty image has been loaded into our project and is ready to be displayed, the drawImage() method is executed to dis-play it in the FacultyFrame Form window. We want to display this image starting from the origin of the Canvas object, which is the upper-left corner of the canvas (0, 0), with a width and height that are identical to those of the canvas. Therefore, the getWidth() and getHeight() methods are called to get both of them from the canvas object. A true is returned to the main program to indicate that the execution of this method is successful.

Before we can build and run our client project to test this faculty query, add one more code line, System.exit(0); to the bottom of the BackButtonActionPerformed() handler or method in the Source window of the FacultyFrame class to terminate our project if the Back button is clicked.

Now we are ready to build and run our client project to test its function to call our Web service to perform the faculty data query.

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

D. Before we can call our Web service, make sure that our ArrayList object al is empty by executing the clear() method.

E. The queryFaculty() method defined in our Web service is called to perform this fac-ulty data query. Two points to be noted are: 1) the argument of this method is a selected faculty name obtained from the getSelectedItem() method from the Faculty Name combo box ComboName. Since this method returns an object, a toString() method must be attached to convert it to a string. 2) An ArrayList cast must be used to make sure that the returned query result is an ArrayList type since an ArrayList type is used
in our Web service project. The query result is assigned to our ArrayList instance, al.
F. A for() loop is used to pick up each column from the query result using the get() method. Two points to be noted are: 1) the argument of the get() method indicates the index of each column in the returned query result is a single row, and the data type of this method is an object. Therefore, a toString() method must be attached to convert it to a string. 2) To assign each column to each item in the f _ field array, the setText() method must be used.

G. The catch block is used to track and display any possible exception during the Web ser-vice calling process.

H. Another try-catch block is used to call a user-defined method, ShowFaculty(), that will be built later to call our Web method to query and display a selected faculty image.

I. The user-defined method ShowFaculty() is modified by removing its argument. The code for this method will be built later.

Now let’s build the code for our user-defined method ShowFaculty() to get and display a selected faculty image by calling another operation, QueryImage(), built in our Web Service.

In the opened FacultyFrame.java file, browse to the ShowFaculty() method and replace all original code with the code shown in Figure 9.35.

FIGURE 9.35   The modified code for the ShowFaculty() method.

Let’s have a closer look at the modified code to see how it works.

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.

Develop the Code to Call Our Web Service Project 2 – Develop Java Web Services to Access Databases

The code related to steps 1~5 is shown in steps 1~4 in Figure 9.50. Add the Java code shown in steps A~E in Figure 9.50 into this block.

Let’s have a closer look at this code to see how it works.

A. An additional system method, getParameter(), is used to get the name of the selected faculty image, which is located at the Faculty _ Image tag in the view class Faculty. jsp. The name of the selected faculty image will be automatically assigned and stored to the Faculty _ Image tag in the view class as soon as the image is selected.

B. A new String array, fnew, is created, and it is used to hold eight pieces of new faculty information stored in the eight local String variables.
C. The InsertFaculty() method defined in our Java Bean is executed to insert these eight pieces of faculty information as a new faculty record into the Faculty Table. The eight pieces of new faculty information are stored in the String array fnew that works as the argument for this method. The run result of this method is returned and assigned to the local integer variable res.

D. If the run result is 0, it means that no record has been inserted into the Faculty Table, and this data insertion fails. In that case, we need to re-display the Faculty.jsp page to enable users to re-insert the faculty record.

E. If the run result is non-zero, it means that the new faculty record has been inserted into the Faculty Table. We need to clean up all seven fields that contain seven pieces of new inserted faculty information in the Faculty.jsp page to enable users to either test this insertion or insert another faculty record. A for() loop is used for that purpose.

Now let’s do our code for the Java managed bean class FacultyMBean.java.
Open our Web-based client project, WebClientFaculty _ Insert, and double-click on the FacultyMBean.java in the Projects window to open the managed bean class file. Let’s develop the code for the Insert() method in this class to fulfill this data insertion function.

Browse to the Insert() method and enter the code, as shown in Figure 9.51, into this method.

Let’s have a closer look at this code to see how it works.

A. Some local variables, such as an integer variable numInsert and an ArrayList instance al, are created. The first variable is used to hold the run result of this data insertion, and the second variable is used to pick up and reserve the input new faculty data array.

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 eight pieces of new faculty information into this new ArrayList instance al. Eight pieces of new faculty information are entered and selected by the user in the JSP page Faculty.jsp and stored in eight tags defined in the view class Faculty.jsp page.

D. A try-catch block is used to call the data insertion operation InsertFaculty() defined in our Web Service project. First a service instance with its service port is generated.

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

F. If the returned Boolean variable insert is false, which means that this data insertion fails, a system method, System.out.println(), is used to indicate this.

G. The catch block is used to catch any possible exception during the data insertion process.
H. Finally the run result of this data insertion is returned to the calling method.

Now let’s build and run our Web client project to call our Web service operation to perform the faculty data insert action.

FIGURE 9.51   The modified code for the Insert() method.