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 the User-Defined Method DBConnection() – Develop Java Web Services to Access Databases

9.5.4  Build the User-Defined Method DBConnection()

To make our Web service project simple, we will use the Java runtime object method to per-form the database connection function. In the opened code window of our Web service project, WebServiceFaculty.java, enter the code shown in Figure 9.25 to create and define the con-nection method DBConnection().
Let’s have a closer look at this piece of code to see how it works.

A. A try-catch block is used to perform the database connection function. First the Oracle JDBC driver is loaded using the forName() method.
B. The catch block is used to track and detect any possible exception for the JDBC driver loading process. The debug information will be displayed using the System.out. println() method if an exception occurs.

C. Our sample Oracle database connection URL is defined and used to set up a connection to our sample database. Refer to Section 6.3.3.2 in Chapter 6 to get more details about the connection URL.

D. Another try-catch 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 connec-tion process.

F. The established connection object is returned to the calling method.

Next let’s add the second Web operation to our Web Service project to query and get a matching faculty image for the selected faculty member.

9.5.5  Add the Second Operation to Our Web Service to Query the Faculty Image

Perform the following operations to add a new operation, QueryImage(), into our Web service:

1) Click on the Design button at the top of the window to open the Design View of our Web service project file, WebServiceFaculty.java.
2) Click on the Add Operation button to open the Add Operation wizard.

FIGURE 9.26  The finished Add Operation wizard.

3) Enter QueryImage into the Name field and click on the Browse button next to the Return Type combo box. Type Image into the Type Name field, select the item Image (java.awt) from the list and click on the OK button.

4) Click on the Add button and enter fname in the Name parameter field. Keep the default type java.lang.String unchanged and click on the OK button.
Your finished Add Operation wizard should match the one shown in Figure 9.26. Click on the OK button again to complete the second add operation process.

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

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.

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

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 – Develop Java Web Services to Access Databases

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

In order to call the InsertFaculty() operation in our Web service project, WebService Faculty, we need to refresh the Web reference in our Window-based client project to use the updated Web service project. Perform the following operations to refresh the Web service reference:

1) Build and deploy our Web Service application, WebAppFaculty, to make it available.
2) Open our Window-based client project, WinClientFaculty _ Insert, and expand
the Web Service References node.
3) Right-click on our Web service, WebServiceFaculty, and choose the Delete item to remove this old Web reference.
4) Right-click on our Window-based client project, WinClientFaculty _ Insert, and select the New > Web Service Client item to open the New Web Service Client wizard.
5) In the opened wizard, click on the Browse button next to the Project field and expand our Web application, WebAppFaculty. Then choose our Web service, WebServiceFaculty, by clicking on it, and click on the OK button.
6) Click on the Finish button to complete the Web service reference refresh process.

Now that we have refreshed or updated the Web service reference for our Window-based client project WinClientFaculty _ Insert, next let’s develop the code in our client project to call the Web service operation InsertFaculty() to perform faculty data insertion.

9.9.2  Develop the Code to Call Our Web Service Project

Open the Window-based client project WinClientFaculty _ Insert 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, InsertButtonActionPerformed(), and enter the code shown in Figure 9.45 into this method.
Let’s have a closer look at this piece of code to see how it works.

A. Some local objects are first declared, which include a File object, imgFile, which is used to hold the selected image file, and a new ArrayList instance, al, which is used to pick up and reserve the input new faculty data array.

B. A Java File Chooser instance, imgChooser, is generated, and it provides a file interface GUI to allow users to select a desired faculty image to be inserted into our database later.

C. The current directory, which is the folder of our current project, is selected, and this loca-tion will work as a default folder to store all selected faculty image files later.

D. The system method, showOpenDialog(), is executed to display the Chooser GUI to enable users to browse and select a desired faculty image to be inserted into our database later.
E. By checking one property, APPROVE _ OPTION, one can confirm whether the GUI oper-ation is successful. If it is opened and an image has been selected, a true is returned. Then the selected image can be retrieved by calling a method, getSelectedFile().

F. These two code lines are used to display the path and directory for the selected faculty image, and they are used for debugging purposes.

G. The clear() method is executed to make sure that the ArrayList instance is clean and empty before a new faculty record can be assigned to it.

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

9.9.3   Build and Run Our Client Project to Insert Faculty Data via Web Service

One more step we need to do prior to building and running our project is to reserve all faculty image files since we need to insert a new faculty member with a new image file. All faculty image files can be found in the folder Images\Faculty in the Students folder on the CRC Press ftp site (refer to Figure 1.2 in Chapter 1). you can copy those files from that folder and save them to a folder on your local machine, such as C:\Images\Faculty.

Now 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 member via our Web service WebServiceFaculty. The queried result is displayed in seven text fields.

Now enter a new faculty record with the seven pieces of new faculty information shown into seven text fields, which is shown in Figure 9.46.

Faculty ID:B86577
Faculty Name:Susan Bai
Title:Professor
Office:MTC-314

FIGURE 9.46   The seven pieces of new inserted faculty information.

FIGURE 9.47   The retrieved new inserted faculty record.

Phone:750–378–1158
College:DukeUniversity
Email:[email protected]

Click on the Insert button to open the File Chooser wizard. In the opened File Chooser wizard, browse to the location where all faculty image files are located, in this case C:\Images\ Faculty; select the desired image, White.jpg; and click on the Open button to select this faculty image and insert it into the Faculty Table in our sample database.

To confirm this data insertion, two methods can be used. First we can use the Select button in this form to perform a query to try to retrieve the inserted faculty record. To do this, go to the Faculty Name combo box, and you can see that the new faculty name, Susan Bai, has been added into this box. Click to select it and click on the Select button. The new inserted faculty record is retrieved and displayed in this form, as shown in Figure 9.47. Click on the Back button to terminate our client project.

The second way to confirm this data insertion is to open our Faculty Table using either the Services window in the NetBeans IDE or the Oracle SQL Developer to check whether the new faculty record has been inserted. To do that using the Services window in the NetBeans IDE, performing the following operations:

1) Open the Services window and expand the Databases node.
2) Right-click on our sample Oracle database URL: jdbc:oracle:thin:@local host:1521:XE;, and select the Connect item to connect to our database. You may need to enter a valid password, oracle _ 18c, to complete the database connection action.

3) Expand our sample database, CSE _ DEPT, and Tables.
4) Right-click on the Faculty Table and select the View Data item.

FIGURE 9.48   The opened Faculty Table in the NetBeans IDE.

Your opened Faculty Table is shown in Figure 9.48. It can be seen that the new faculty record, Susan Bai, with the faculty _ id of B86577, which is located in the fourth row, indicated by the dark color in this Table, has been successfully inserted into our database.

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.

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

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

We can still use the Web-based client project we built in Section 9.7, WebClientFaculty _ Select, to consume our Web service to perform the faculty data insertion action. But we prefer to modify that project and make it our new Web-based client project WebClientFaculty _ Insert. Let’s copy that project and make it our new project. Perform the following steps to create our new project, WebClientFaculty _ Insert:

1) In the Projects window, right-click on the project WebClientFaculty _ Select and select the Copy item from the popup menu to open the Copy Project wizard.

2) Enter our new project name, WebClientFaculty _ Insert, into the Project Name box; browse to the default project folder, C:\Class DB Projects\Chapter 9, as the Project Location; and click on the Copy button.

A new project, WebClientFaculty _ Insert, is generated and added into our Projects window.

First let’s add a Web service reference to our Web-based client project to allow it to use our 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, WebAppFaculty, we need to refresh the Web reference in our Web-based client project, WebClientFaculty _ Insert, to use the updated Web service project. Perform the following operations to refresh the Web service reference:

1) Build and deploy our Web Service application project, WebAppFaculty, first.
2) Open our Web-based client project, WebClientFaculty _ Insert, and expand the Web Service References node.
3) Right-click on our Web service, WebServiceFaculty, and choose the Delete item to remove this old Web reference.

4) Right-click on our Web-based client project, WebClientFaculty _ Insert, and select the New > Web Service Client item to open the New Web Service Client wizard.

5) In the opened wizard, click on the Browse button next to the Project field and expand our Web application, WebAppFaculty. Then choose our Web service project, WebServiceFaculty, by clicking on it, and click on the OK button.

6) Click on the Finish button to complete the Web service reference refreshing process.

Now that we have refreshed or updated the Web service reference for our Web-based client proj-ect, WebClientFaculty _ Insert, next let’s develop the code in our client project to call the Web service operation InsertFaculty() to perform faculty data insertion.