Practical Database Programming With Java
.pdf
8.5 Build Java Web Project to Access SQL Server Database 637
Figure 8.71. The displayed LogIn.jsp page.
Click on the Clean and Build Main Project button to build our project. Then right click on the LogIn.jsp file from the Projects window and select Compile File item from the pop-up menu to compile our web pages. Right click on the LogIn.jsp page again and select the Run File item from the popup menu to run our project. If the HTTP Port of the GlassFish server 8080 has been occupied and the page cannot be opened, refer to Appendix I to fix this Port number.
Enter admin and reback as the username and password to the Java Glassfish v3 Server to log in and start this Web server. Recall that we used these login data when we installed the Java Glassfish v3 Server in Section 5.3.5.2.1. Refer to that section to get more details for these login data. If the HTTP Port 8080 has been occupied and the browser cannot open the page, change the Port number to 8082 in the Address box in the Web page.
As the LogIn.jsp is displayed, enter a valid username and password, such as jhenry and test, into the associated fields, as shown in Figure 8.71.
Click on the LogIn button to call the checkLogIn() method to perform the login query to find a matched username and password pair.The Selection.jsp page is displayed to indicate that this login process is successful, and a matched username and password has been found, as shown in Figure 8.72.
Our login process using the JSP and help class file is successful.
Next, let’s build and code for the Selection.jsp page. As we mentioned, this page can be considered as the control page, and it will direct users to the different pages to perform the different database query functions based on the users’ choices.
8.5.2 Build the Selection Page
To handle the users’ input and direct to the different target pages based on the users’ input, we still want to use the MVC mode to build this page. We can use the Selection. jsp page as a view to display the input and output, and create another JSP page
638 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.72. The successful page—Selection.jsp page.
………
<div style='position:absolute;width:10.-2040in;height:2.047in'> <![if !pub]>
A<form method=post action=".\SelectionProcess.jsp">
………
<input type=submit value=OK v:shapes="_x0000_s1028">
………
B<input type=button value=Exit onclick="self.close()" v:shapes="_x0000_s1029">
<![if !pub]></span><![endif]><![if !pub]> </form>
………
Figure 8.73. The coding modifications to the Selection.jsp page.
SelectionProcess.jsp as the model and controller to process the users’ input and direct to the target page.
Of course, you can combine the MVC mode together to perform displaying and processing page at a single JSP page file. However, you need to add a hidden field to the page and use that hidden field as an identifier to indicate whether the page has been submitted or not. That will make the Selection.jsp page complex in the coding process.
We divide this page-building process into two steps: modify the Selection.jsp page and create the SelectionProcess.jsp page.
Let’s first perform some necessary modifications to the Selection.jsp page. Launch the NetBeans IDE and open the Selection.jsp page by double clicking on
it from the Projects window, and perform the modifications shown in Figure 8.73 to this page. All modifications have been highlighted in bold.
Let’s have a closer look at these modifications to see how they work.
A.An action attribute is added to the Form tag and the destination of this action is the SelectionProcess.jsp page. The ′.\′ operator is used to indicate to the Web controller that the next page, SelectionProcess.jsp, is located at the current folder.
8.5 Build Java Web Project to Access SQL Server Database 639
B.The type of the second button, Exit, is changed from the submit to the button since we do not want to submit any form data to the next page when this button is clicked. Instead, we want a system method, self.close(), to be executed as this button is clicked to exit our project. Therefore an onclick attribute is used to direct the control to this method when this button is clicked.
Now, let’s create the selection process page SelectionProcess.jsp.
Open our project JavaWebDBJSPSQL from the Projects window. Perform the following operations to create this page:
1.Right click on our project JavaWebDBJSPSQL from the Projects window and select the New > JSP item from the pop-up menu. If you cannot find the JSP item from the pop-up
menu, go to the Other item to open the New File wizard. Select the Web from the Categories list and JSP from the File Types list to do this.
2.On the opened New JSP File wizard, enter SelectionProcess into the File Name field and click on the Finish button.
Now let’s do the coding for this page. Double click on our newly created page SelectionProcess.jsp from the Projects window to open its code window. On the opened code window, perform the modifications shown in Figure 8.74 to this page. All modification parts have been highlighted in bold.
Let’s have a closer look at this piece of codes to see how it works.
A.A JSP directive tag is used to indicate that this page uses the Java language and it is a JSP file.
B.A local string variable nextPage is declared first. This variable is used to hold the URL of the next page, which we will use later to direct the control to the associated page.
C.The getParameter() method is used to pick up the selected item by the user from the selection list in the Selection.jsp page. The argument of the getParameter() method is the name of the selection list in the Selection.jsp page. The selected item is then assigned to another local string variable userSel.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Selection Process Page</title>
</head>
<body>
A<%@page language="java" %> <%
BString nextPage = null;
CString userSel = request.getParameter("ListSelection");
Dif (userSel.equals("Faculty Information"))
nextPage = "Faculty.jsp";
else if (userSel.equals("Course Information")) nextPage = "Course.jsp";
else
nextPage = "Student.jsp"; %>
E <jsp:forward page = "<%=nextPage%>" />
</body>
</html>
Figure 8.74. The codes for the SelectionProcess.jsp page.
640 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.75. The running status of the Selection.jsp page.
D.An if selection structure is used to check the user’s selection and assign the associated next page to the local variable nextPage.
E.Finally, a JSP forward directive is used to direct the program to the next page.
Now we can build and run this page to test its function.
Click on the Clean and Build Main Project button to compile and build our project. Then right click on the Selection.jsp page from the Projects window and select the Run File item from the pop-up menu to run the project. The Selection.jsp is displayed, as shown in Figure 8.75, when the project runs.
Select a desired item, such as Faculty Information, from the Selection listbox, and click on the OK button. You can find that the Faculty.jsp page is displayed. You can try to select other item from the listbox to open other related pages.
Click on the Exit button to terminate our project. Our Selection page is successful!
8.5.3 Query the Faculty Table Using JSP and JSP Implicit Session Object
In this section, we will discuss how to access and query data from the Faculty table in our sample database using the JSP and JSP implicit session object.
In Section 8.1.5, we have provided a detailed discussion about how to use the JSP implicit session object to query our Faculty table. In this part, we will build a real project to perform this data query using this object. We divide this discussion into the following three parts:
1.Modify the Faculty.jsp page and use it as a view.
2.Create a new FacultyProcess.jsp page and use it as a model and controller page.
8.5 Build Java Web Project to Access SQL Server Database 641
3.Create a help class file FacultyQuery.java to handle data query and related business logics.
First let’s modify our view class, Fcaulty.jsp page.
8.5.3.1 Modify the Faculty.jsp Page
The Faculty.jsp page works as a view to provide the displaying function for input and output. We need to modify this page to enable it to forward the user’s inputs to the model and controller page, and furthermore, to call the help class to process our data query. Also, the page needs to return to the Selection.jsp page if the user clicks on the Back button on this page.
Open this page by double clicking on it from the Projects window, and perform the modifications shown in Figure 8.76 to this page. All modified coding parts have been highlighted in bold.
A<form method=post action=".\FacultyProcess.jsp">
………
B<v:imagedata src="<%=session.getAttribute("facultyImage") %>" o:title="<EMPTY>"/>
<v:shadow color="#ccc [4]"/>
………
<input name=FacultyNameField maxlength=255 size=18
Cvalue="<%=session.getAttribute("facultyName") %>" type=text v:shapes="_x0000_s1029">
………
<input name=FacultyIDField maxlength=255 size=21
Dvalue="<%=session.getAttribute("facultyId") %>" type=text v:shapes="_x0000_s1031">
………
<input name=NameField maxlength=255 size=21
Evalue="<%=session.getAttribute("facultyName") %>" type=text v:shapes="_x0000_s1033">
………
<input name=TitleField maxlength=255 size=21
Fvalue="<%=session.getAttribute("title") %>" type=text v:shapes="_x0000_s1035">
………
<input name=OfficeField maxlength=255 size=21
Gvalue="<%=session.getAttribute("office") %>" type=text v:shapes="_x0000_s1037">
………
<input name=PhoneField maxlength=255 size=21
Hvalue="<%=session.getAttribute("phone") %>" type=text v:shapes="_x0000_s1039">
………
<input name=CollegeField maxlength=255 size=21
Ivalue="<%=session.getAttribute("college") %>" type=text v:shapes="_x0000_s1041">
………
<input name=EmailField maxlength=255 size=21
Jvalue="<%=session.getAttribute("email") %>" type=text v:shapes="_x0000_s1043">
………
K<input type=submit value=Select name="Select" v:shapes="_x0000_s1044">
………
L<input type=submit value=Insert name="Insert" v:shapes="_x0000_s1045">
………
M<input type=submit value=Update name="Update" v:shapes="_x0000_s1046">
………
N<input type=submit value=Delete name="Delete" v:shapes="_x0000_s1047">
………
O<input type=submit value=Back name="Back" v:shapes="_x0000_s1048">
………
Figure 8.76. The modified codes for the Faculty.jsp page.
642 Chapter 8 Developing Java Web Applications to Access Databases
Let’s have a closer look at this piece of modified codes to see how it works.
A.An action attribute is added to the Form tag to forward all information collected from this page to the model and controller page FcaultyProcess.jsp that will call our help class file FacultyQuery.java to perform the faculty data query process.
B.Starting from step B until step J, we use the embedded JSP codes to assign the selected faculty image and queried faculty columns from our Faculty table to the src and the value tags of the associated text field in the Facultypage.jsp using the getAttribute() method of the session class. In this way, as long as the queried faculty row has any change, this modification will be immediately updated and reflected to each text field in our Faculty.jsp page. In this way, a direct connection or binding between the text fields in our Faculty.jsp page and the queried Faculty columns in our help class is established.
K.From steps K to O, a name attribute is added into each Submit button tag. This attribute is very important since we need to use it to identify each submit button in the next page, our model and controller page, FacultyProcess.jsp, using the getParameter() method of the request object to direct the control to the different pages to handle different data query and data manipulation actions to the Faculty table in our sample SQL Server database CSE_DEPT.
In order to select the correct faculty image based on the faculty member selected by the user, we need to assign the session.getAttribute() method to the src attribute of the imagedata tag. The argument of this method should be defined as a property in our help class file, and a method, getFacultyImage() defined in that help class file, will be used to select the appropriate faculty image and assign it to this property.
Now let’s take a look at our model and controller page FacultyProcess.jsp.
8.5.3.2 Create the FacultyProcess.jsp Page
The purpose of this page is to direct the control to the different help class files based on the button clicked by the user from the Faculty.jsp page. The following help class files will be triggered and executed based on the button clicked by the user from the Faculty. jsp page:
1.If the user selected and clicked the Select button, the control will be directed to the faculty data query help class file FacultyQuery.java to perform the faculty record query function.
2.If the user clicked the Insert button, the control will be directed to the faculty data insertion help class file FacultyInsert.java to do the faculty record insertion.
3.If the user clicked the Update or Delete button, the control will be directed to the faculty record updating help class file FacultyUpdate.java, or the faculty record deleting help class file FacultyDelete.java to perform the associated data manipulations.
4.If the user selected and clicked the Back button, the control will be returned to the Selection.jsp page to enable users to perform other information query operations.
Now let’s create this FacultyProcess.jsp page.
Right click on our project JavaWebDBJSPSQL from the Projects window and select the New > JSP item from the pop-up menu to open the New JSP File wizard. Enter FacultyProcess into the File Name field and click on the Finish button.
8.5 Build Java Web Project to Access SQL Server Database 643
Double click on our newly created FacultyProcess.jsp page from the Projects window, exactly under the Web Pages folder, to open this page. Enter the codes shown in Figure 8.77 into this page. The newly entered codes have been highlighted in bold.
Now let’s have a close look at these codes to see how they work.
A.You can embed any import directory using the JSP directive in a HTML or a JSP file. The format is <%@ page import=“java package” %>. In this page, we embed one package,
JavaWebDBJSPSQLPackage.*, since we will build our Java help class file FacultyQuery. java in that package in the next section.
B.A new instance of our help class FacultyQuery that will be created in the next section, fQuery, is created, since we need to use properties and methods defined in that class to perform faculty record query and faculty image selection functions.
C.The getParameter() method defined in the session class is executed to identify which submit button has been clicked by the user in the Faculty.jsp page. As you know, in total, we have five buttons in the Faculty.jsp page. All Faculty.jsp form data, including all text fields, image box, and submit buttons, will be submitted to this FacultyProcess.jsp page when any of five buttons is clicked. If a button is clicked, the getParameter() method with
the name of that clicked button as the argument of this method will return a non-null value. In this way, we can identify which button has been clicked. We use a sequence of if ... else if selection structures to check all five buttons to identify the clicked button.
D.If the Select button is clicked by the user, the getParameter() method with this button’s name as argument will return a non-null value. This means that the user wants to perform a faculty record query from the Faculty table in our sample database. Again, the getParameter() method with the name of the faculty name field, FacultyNameField, is used to pick up a desired faculty name that is entered by the user from the Faculty.jsp page. The picked up faculty name is assigned to a local String variable fname.
E.Then the method QueryFaculty() defined in the help class file FacultyQuery.java will be called to execute this faculty data query based on the selected faculty name fname obtained from step D above.
F.If the QueryFaculty() method is executed unsuccessfully, which means that no matched faculty record has been found, a false is returned to indicate this situation. In this case, we need to reopen the Faculty.jsp page to enable the user to reenter new faculty data to do another query using the sendRedirect() method defined in the response class.
G.Otherwise, a matched faculty record has been found and the query is successful. The setAttribute() method defined in the session class is used to set up all properties defined in the help class file using the associated getter methods in that class.
H.The getFacultyImage() method, which is defined in the help class file FacultyQuery.java and will be developed in the next section, is executed to pick up the correct faculty image file, exactly the correct name of the faculty image file.
I.If the getFacultyImage() method returns a null, which means that no matched faculty image has been found. Then we will continue to check whether the user has entered a new faculty image in the FacultyImageField textbox in the Faculty.jsp page, and this is a normal case if the user wants to insert a new faculty record into the Faculty table with a new faculty image. If the getParameter() method returns a non-null value, which means that the user did enter a new faculty image, exactly the name of a new faculty image, into that field. In that case, we need to set up the facultyImage property with that name and later on display that new faculty image based on that property.
644 Chapter 8 Developing Java Web Applications to Access Databases
A<%@ page import="JavaWebDBJSPSQLPackage.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Faculty Process Page</title>
</head>
<body>
<%
BFacultyQuery fQuery = new FacultyQuery();
Cif (request.getParameter("Select")!= null) {
//process the faculty record query
DString fname = request.getParameter("FacultyNameField");
Eboolean res = fQuery.QueryFaculty(fname);
Fif (!res)
G |
response.sendRedirect("Faculty.jsp"); |
else { |
|
|
session.setAttribute("facultyId", fQuery.getFacultyID()); |
|
session.setAttribute("facultyName", fQuery.getFacultyName()); |
|
session.setAttribute("office", fQuery.getOffice()); |
|
session.setAttribute("title", fQuery.getTitle()); |
|
session.setAttribute("college", fQuery.getCollege()); |
|
session.setAttribute("phone", fQuery.getPhone()); |
|
session.setAttribute("email", fQuery.getEmail()); |
|
} |
HString fimg = fQuery.getFacultyImage();
Iif (fimg == null) {
if (request.getParameter("FacultyImageField")!= null) session.setAttribute("facultyImage", request.getParameter("FacultyImageField"));
Jelse
session.setAttribute("facultyImage", "Default.jpg");
}
Kelse
session.setAttribute("facultyImage", fimg);
LfQuery.setFacultyImage(null);
Mresponse.sendRedirect("Faculty.jsp");
}
Nelse if (request.getParameter("Insert")!= null) { //process the faculty record insertion
}
Oelse if (request.getParameter("Update")!= null) { //process the faculty record updating
}
Pelse if (request.getParameter("Delete")!= null) { //process the faculty record deleting
}
Qelse if (request.getParameter("Back") != null) { fQuery.CloseDBConnection(); response.sendRedirect("Selection.jsp");
}
%>
</body>
</html>
Figure 8.77. The codes for the FacultyProcess.jsp page.
8.5 Build Java Web Project to Access SQL Server Database 645
J.Otherwise, it means that no matched faculty image has been found, and the user did not want to enter a new faculty image. In that case, we need to display a default faculty image by assigning the name of that default faculty image to the facultyImage property.
K.If the getFacultyImage() method returns a non-null value, which means that a matched faculty image’s name has been found, the setAttribute() method is executed to set up the facultyImage property with that faculty image’s name.
L.The setFacultyImage() method is executed to clean up the content of the property of the help class, facultyImage, which is a static String variable and works as a global variable to store the current faculty image’s name. When a new faculty image is inserted or updated with a faculty record insertion or updating, the name of that new faculty image will be assigned to the global variable facultyImage. To avoid displaying the same new faculty image in multiple times, we need to clean up this global variable each time when a faculty record has been retrieved and displayed.
M.The sendRedirect() method defined in the response class is executed to redisplay the Fcaulty.jsp page with the queried result on that page.
N.If the getParameter(“Insert”) method returns a non-null value, which means that the Insert button has been clicked by the user in the Faculty.jsp page, and the user wants to insert a new faculty record into the Faculty table in our sample database. We will build a Java bean class to handle this faculty data insertion later.
O.Similarly, if the getParameter(“Update”) method returns a non-null value, which means that the Update button has been clicked by the user in the Faculty.jsp page, and the user wants to update an existing faculty record in the Faculty table in our sample database. We will build a Java bean class to handle this faculty data updating action later.
P.If the getParameter(“Delete”) method returns a non-null value, which means that the Delete button has been clicked by the user in the Faculty.jsp page, and the user wants to delete an existing faculty record from the Faculty table in our sample database. We will build a Java bean class to handle this faculty data deleting action later.
Q.If the getParameter(“Back”) method returns a non-null value, which means that the Back button has been clicked by the user in the Faculty.jsp page, and the user wants to return totheSelection.jsppagetoperformotherdataqueryoperations.TheCloseDBConnection() method is first executed to close the connection to our sample database, and then the sendRedirect() method is called to do this returning function.
Now let’s build our Java help class file FacultyQuery.java to handle all data query actions, getter methods, class properties, and related business logics.
8.5.3.3 Create the Help Class File FacultyQuery.java
To create our Java help class file FacultyQuery.java to handle the faculty record query, right click on our project JavaWebDBJSPSQL from the Projects window and select the New > Java Class item from the pop-up menu to open the New Java Class wizard. Enter FacultyQuery into the Class Name field and select the JavaWebDBJSPSQLPackage from the Package combo box. Your finished New Java Class wizard should match one that is shown in Figure 8.78. Click on the Finish button to create this new Java help class file.
Now let’s develop the codes for this new Java help class file. Double click on our new created Java help class file FacultyQuery.java from the Projects window to open this file, and enter the codes that are shown in Figure 8.79 into this file. Because of the large
646 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.78. The finished New Java Class wizard.
size of this coding, we divide this coding process into two parts. The first part of the codes is shown in Figure 8.79, and the second part is shown in Figure 8.80. The new entered codes have been highlighted in bold.
Let’s have a close look at these newly added codes in Figure 8.79 to see how they work.
A.The java.sql.* package is imported first since all SQL Server database related classes and methods are defined in that package.
B.Eight class properties related to the associated columns in the Faculty table in our sample database are declared first. These properties are very important since they are directly mapped to the associated columns in the Faculty table. All of these properties can be accessed by using the associated getter method defined at the bottom of this class.
C.A class-level database connection object is created, and a Dialog object is also created. We will use the latter as a message box to display some debug information during the project runs.
D.A try…catch block is used to load the database JDBC driver. The catch block is used to track and collect any possible exception during this database driver loading process.
E.The database connection URL is defined. Refer to Section 6.2.1.2.4 in Chapter 6 to get more detailed information about this driver name.
F.Another try…catch block is used to connect to our sample SQL Server database with the desired username and password. The catch block is used to track and collect any possible exception occurred during this database connection process.
G.The main query method, QueryFaculty(), is defined with the selected faculty name as the argument. The SQL query statement is first created with the faculty name as the positional dynamic parameter.
H.Starting from a try block, the prepareStatement() method is called to create a PreparedStatement object pstmt.
I.The setter method is used to set the positional parameter in the positional order.
