Practical Database Programming With Java
.pdf
8.5 Build Java Web Project to Access SQL Server Database 657
package JavaWebDBJSPSQLPackage;
Aimport java.sql.*; import javax.ejb.Stateless;
public class FacultyUpdateDeleteBean {
Bprivate String facultyID; private String facultyName; private String office; private String title;
private String phone; private String college; private String email; static Connection con;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true); public FacultyUpdateDeleteBean() {
Ctry {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (Exception e) {
msgDlg.setMessage("Class not found exception!" + e.getMessage()); msgDlg.setVisible(true);
}
DString url = "jdbc:sqlserver://localhost\\SQL2008EXPRESS:5000;databaseName=CSE_DEPT;"; try {
Econ = DriverManager.getConnection(url,"ybai","reback1956");
}
catch (SQLException e) {
msgDlg.setMessage("Could not connect!" + e.getMessage()); msgDlg.setVisible(true);
e.printStackTrace();
}
}
public int UpdateFaculty(String[] upFaculty) {
Fint numUpdated = 0;
String query = "UPDATE Faculty SET faculty_name=?, office=?, phone=?, title=?, college=?,
email=? " + "WHERE faculty_name= ?";
G |
try { |
|
|
PreparedStatement pstmt = con.prepareStatement(query); |
|
H |
pstmt.setString(1, upFaculty[0]); |
// NameField |
|
pstmt.setString(2, upFaculty[1]); |
// OfficeField |
|
pstmt.setString(3, upFaculty[2]); |
// PhoneField |
|
pstmt.setString(4, upFaculty[3]); |
// TitleField |
|
pstmt.setString(5, upFaculty[4]); |
// CollegeField |
|
pstmt.setString(6, upFaculty[5]); |
// EmailField |
|
pstmt.setString(7, upFaculty[6]); |
// FacultyNameField |
I |
numUpdated = pstmt.executeUpdate(); |
|
|
} |
|
J |
catch (SQLException e) { |
|
|
msgDlg.setMessage("Error in Statement!" + e.getMessage()); |
|
|
msgDlg.setVisible(true); |
|
|
} |
|
K |
return numUpdated; |
|
|
} |
|
|
……… |
|
Figure 8.87. The first part of the codes of the Java bean class file.
658 Chapter 8 Developing Java Web Applications to Access Databases
shows the first part of the codes of this class, in which the UpdateFaculty() method is included.
Let’s have a closer look at the codes for these two methods 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.Seven 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 in the second coding part of this class.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.
C.In the constructor of this class, 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 databasedriver loading process.
D.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.
E.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.
F.The main data updating method, UpdateFaculty(), is defined with the selected faculty updating information as the argument. This argument is exactly a String array that contains all seven pieces of updating faculty information. A local integer variable numUpdated and the SQL updating statement are first created with the faculty name as the positional dynamic parameter.
G.Starting from a try block, the prepareStatement() method is called to create a PreparedStatement object pstmt.
H.Seven setter methods are used to set the positional parameters in the SQL updating statement with the positional order. This order must be identical with that defined in the input argument upFaculty[], which is a String array.
I.The executeUpdate() method is executed to perform this data updating action, and the returned result, which is the number of the rows that have been successfully updated in the Faculty table, is assigned to the local integer variable numUpdated.
J.The catch block is used to track and collect any exceptions during this data updating operation.
K.The data updating result is returned to the calling method.
The second part of the codes for this Java bean class is shown in Figure 8.88. Let’s have a closer look at this piece of codes to see how it works.
A.The codes for the CloseDBConnection() method are identical with those we discussed in the last section, and the purpose of this method is to close the connection between our Web application and our sample database.
B.Starting from step B, including steps C through H, seven getter methods are defined, and they are used to pick up all seven properties defined at the beginning of this class.
8.5 Build Java Web Project to Access SQL Server Database 659
Apublic void CloseDBConnection()
{
try{
if (!con.isClosed()) con.close();
}catch (SQLException e) {
msgDlg.setMessage("Error in close the DB! " + e.getMessage()); msgDlg.setVisible(true);
}
}
Bpublic String getFacultyID() {
return this.facultyID;
}
C public String getFacultyName() { return this.facultyName;
}
D public String getOffice() { return this.office;
}
E public String getTitle() { return this.title;
}
F public String getPhone() { return this.phone;
}
G public String getCollege() { return this.college;
}
H public String getEmail() { return this.email;
}
}
Figure 8.88. The second part of the codes of the Java bean class file.
In fact, the codes for this Java bean class file are basically identical with those we built in our Java help class file, which include the loading JDBC driver, defining the database connection URL, connecting to database, and executing the appropriate method to perform related data actions against our database.
Next, let’s modify the FacultyProcess.jsp page to handle the faculty data collection and manipulations.
8.5.5.2 Modify the FacultyProcess Page to Handle Faculty Data Updating
Double click on the FacultyProcess.jsp page from the Projects window, and perform the following modifications to this page to use Java bean FacultyUpdateDeleteBean. java to perform the faculty record updating actions:
1.Move to the else if (request.getParameter(“Update”)!= null) block, then open the
Palette window by going to the Window > Palette menu item. In the opened Palette window, browse to the JSP tab, drag the Use Bean icon, and place it inside the else if block.
2.On the opened Insert Use Bean dialog, enter UpdateFaculty into the ID field, and
JavaWebDBJSPSQLPackage. FacultyUpdateDeleteBean into the Class filed. Select
660 |
Chapter 8 Developing Java Web Applications to Access Databases |
|
|
|
|
|
|
else if (request.getParameter("Update")!= null) { |
|
|
//process the faculty record updating |
|
|
%> |
1 |
|
<jsp:useBean id="UpdateFaculty" scope="session" |
2 |
|
class="JavaWebDBJSPSQLPackage.FacultyUpdateDeleteBean" /> |
3<jsp:setProperty name="UpdateFaculty" property="*" />
4<%
Aint update = 0;
BString fname = request.getParameter("NameField"); String office = request.getParameter("OfficeField"); String phone = request.getParameter("PhoneField"); String college = request.getParameter("CollegeField"); String title = request.getParameter("TitleField"); String email = request.getParameter("EmailField");
String f_name = request.getParameter("FacultyNameField");
CString[] upf = {fname, office, phone, title, college, email, f_name };
Dupdate = UpdateFaculty.UpdateFaculty(upf);
Eif (update == 0)
|
response.sendRedirect("Faculty.jsp"); |
F |
else { |
|
session.setAttribute("FacultyIDField", null); |
|
session.setAttribute("NameField", null); |
|
session.setAttribute("OfficeField", null); |
|
session.setAttribute("PhoneField", null); |
|
session.setAttribute("CollegeField", null); |
|
session.setAttribute("TitleField", null); |
|
session.setAttribute("EmailField", null); |
Gresponse.sendRedirect("Faculty.jsp");
HfQuery.setFacultyImage(request.getParameter("FacultyImageField"));
}
I UpdateFaculty.CloseDBConnection();
}
………
Figure 8.89. The modified codes for the Update block.
the session from the Scope combo box. A JSP directive that contains the bean id, bean scope, and class is added to this block.
3.Add a JSP directive to the Java bean class FacultyUpdateDeleteBean.java shown below:
<jsp:setProperty name=″UpdateFaculty″ property=″*″ />
4.Add the opening and ending JSP directives to enclose those two JSP directives we added above.
The codes related to steps 1–4 above are shown in the top on Figure 8.89. Add the codes shown in steps A–I in Figure 8.89 into this block.
Let’s have a closer look at these codes to see how they work.
A.A local integer variable update is created, and it is used to hold the running result of executing the UpdateFaculty() method in the Java bean class FacultyUpdateDeleteBean with the bean id of UpdateFaculty.
B.Seven getParameter() methods are used to pick up seven pieces of updating faculty information stored in the seven fields in the Faculty.jsp page. The collected seven pieces of new faculty information are assigned to seven local String variables.
8.5 Build Java Web Project to Access SQL Server Database 661
C.A new String array upf[] is created, and it is used to hold seven pieces of updating faculty information stored in the seven local String variables.
D.The UpdateFaculty() method in our Java bean is executed to update a faculty record with these seven pieces of faculty information in the Faculty table. The seven pieces of updating faculty information is stored in the String array upf[] that works as the argument for this method. The running result of this method is returned and assigned to the local integer variable update.
E.If the running result is 0, which means that no record has been updated in the Faculty table and this data updating action has failed. In that case, we need to redisplay the Faculty.jsp page to enable users to reupdate that faculty record.
F.If the running result is nonzero, which means that at least one faculty record has been updated in the Faculty table. We may clean up all seven fields that contain seven pieces of updated faculty information in the Faculty.jsp page to enable users to either to test this updating or update another faculty record.
G.We need to redisplay the Faculty.jsp page to enable users to perform the next action.
H.We need to set the global variable facultyImage defined in the help class FacultyQuery. java, and assign the updating faculty image’s name to it in order to display this updated faculty image later when we confirm this faculty record’s updating.
I.Finally, the CloseDBConnection() method is called to disconnect the connection to our database.
Now we can build and run our project to test this faculty record updating function. Click on the Clean and Build Main Project button to perform cleaning up and building our project. Then right click on the LogIn.jsp page from the Projects window to run our project. Enter the appropriate username and password, such as jhenry and test, to finish the login process and select the Faculty Information item from the Selection. jsp page to open the Fcaulty.jsp page.
To update a faculty record, first, let’s perform a query operation to retrieve and display that faculty record. Enter a faculty name, such as Ying Bai, into the Faculty Name field and click on the Select button. All seven pieces of information related to that faculty are retrieved and displayed in this page. Now enter six pieces of updating information into the associated six fields (no Faculty ID field), and enter the default faculty image’s name, Default.jpg, into the Image field, since we want to use this default image as our updating faculty image. The finished faculty updating record is shown in Figure 8.90.
Click on the Update button to try to update this faculty record in the Faculty table in our sample database. Immediately, you can find that the original faculty information is displayed, which means that this data updating is successful.
To confirm this updating action, two ways could be used. The first way is to use the Select button in the Faculty.jsp page to retrieve this updated record from the Faculty table. To do that, enter Susan Bai to the Faculty Name field and click on the Select button. You can find that the updated record is retrieved and displayed in the seven fields with the default faculty image, as shown in Figure 8.91. Now click on the Back and Exit button to terminate our project.
The second way to confirm this data updating is to open the Faculty table. Open the Services window, expand the Databases node and our SQL Server database URL: jdbc:sqlserver://localhost\SQLEXPRESS:5000;databaseName=CSE_DEPT[ybai
662 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.90. The entered faculty updating information.
Figure 8.91. The updated faculty information.
8.5 Build Java Web Project to Access SQL Server Database 663
Table 8.3. The original data for faculty member Ying Bai
faculty_id |
faculty_name |
office |
phone |
college |
title |
||
B78880 |
Ying Bai |
MTC-211 |
750-378-1148 |
Florida Atlantic University |
Associate Professor |
ybai@college.edu |
on dbo]. Right click on this URL and select the Connect item to connect to our sample database. Then expand our database CSE_DEPT, dbo and Tables. Right click on the Faculty table and select the View Data item to open this table. You can find that the faculty record with the faculty_id of B78880 has been updated.
Our data updating action using the JSP and Java bean is successful!
It is highly recommended to recover this updated faculty record in the Faculty table since we want to keep our database neat and clean. Apply the data shown in Table 8.3 to recover this faculty record. You can do this data recovery either in the NetBeans IDE or the Microsoft SQL Server Management Studio Express by opening the Faculty table.
8.5.5.3 Add a Method to the Session Bean to Perform Faculty Data Deleting
To perform the faculty record deleting action, we need to perform the following operations:
1.Add a new method to the Java session bean FacultyUpdateDeleteBean to handle the faculty record deleting actions.
2.Modify the FacultyProcess.jsp page to handle the faculty data collection and manipulations.
Let’s first add a new method DeleteFaculty() into our Java session bean class FacultyUpdateDeleteBean to handle the faculty record deleting actions. Create a new method DeleteFaculty() and enter the codes shown in Figure 8.92 into this method.
Let’s have a closer look at this piece of codes to see how it works.
A.A local integer variable numDeleted is created, and it is used to hold the running result of executing the DeleteFaculty() method in the Java bean class FacultyUpdateDeleteBean with the bean id of DeleteFaculty.
B.The SQL deleting statement is created with the faculty_name as the positional dynamic parameter.
C.A try…catch block is used to perform this data deleting action. The prepareStatement() method is called to create a PreparedStatement object pstmt.
D.The setter method is used to set up the positional dynamic parameter faculty_name.
E.The executeUpdate() method is executed to perform this data deleting action and the running result, which is the number of the rows that have been successfully deleted from the Faculty table, is assigned to the local integer variable numDeleted.
664 Chapter 8 Developing Java Web Applications to Access Databases
………
public int DeleteFaculty(String fname) {
Aint numDeleted = 0;
BString query = "DELETE FROM Faculty WHERE faculty_name = ?"; try {
CPreparedStatement pstmt = con.prepareStatement(query);
Dpstmt.setString(1, fname);
EnumDeleted = pstmt.executeUpdate();
}
F catch (SQLException e) {
msgDlg.setMessage("Error in Statement!" + e.getMessage()); msgDlg.setVisible(true);
}
G return numDeleted;
}
………
Figure 8.92. The codes for the DeleteFaculty() method.
F.The catch block is used to track and collect any exceptions during this data deleting operation.
G.The data deleting result is returned to the calling method.
Now let’s modify the FacultyProcess.jsp page to handle the faculty data collection and manipulations.
8.5.5.4 Modify the FacultyProcess Page to Handle Faculty Data Deleting
Double click on the FacultyProcess.jsp page from the Projects window to open this page, and perform the following modifications to this page to use the Java bean FacultyUpdateDeleteBean.java to perform the faculty record deleting actions:
1.Move to the else if (request.getParameter(“Delete”)!= null) block, then open the
Palette window by going to the Window > Palette menu item. In the opened Palette window, browse to the JSP tab, drag the Use Bean icon, and place it inside the else if block.
2. On the opened Insert Use Bean dialog, enter DeleteFaculty into the ID field, and
JavaWebDBJSPSQLPackage. FacultyUpdateDeleteBean into the Class field. Select the session from the Scope combo box. A JSP directive that contains the bean id, bean scope, and class is added to this block.
3.Add a JSP directive to the Java bean class FacultyUpdateDeleteBean.java shown below:
<jsp:setProperty name=″DeleteFaculty″ property=″*″ />
4.Add the opening and ending JSP directives to enclose those two JSP directives we added above.
The codes related to steps 1–4 above are shown in the top on Figure 8.93. Add the codes shown in steps A–E in Figure 8.93 into this block.
8.5 Build Java Web Project to Access SQL Server Database 665
………
else if (request.getParameter("Delete")!= null) { //process the faculty record deleting
1%>
2<jsp:useBean id="DeleteFaculty" scope="session"
3 |
class="JavaWebDBJSPSQLPackage.FacultyUpdateDeleteBean" /> |
4 |
<jsp:setProperty name="DeleteFaculty" property="*" /> |
|
<% |
A |
int delete = 0; |
B |
String fname = request.getParameter("FacultyNameField"); |
C |
delete = DeleteFaculty.DeleteFaculty(fname); |
D |
response.sendRedirect("Faculty.jsp"); |
E |
DeleteFaculty.CloseDBConnection(); |
|
} |
|
……… |
Figure 8.93. The modified codes for the Delete block.
Let’s have a closer look at these codes to see how they work.
A.A local integer variable delete is created, and it is used to hold the running result of executing the DeleteFaculty() method in the Java bean class FacultyUpdateDeleteBean with the bean id of DeleteFaculty.
B.The getParameter() method is used to pick up the name of the faculty to be deleted from the Faculty table. The retrieved faculty name is assigned to the local variable fname.
C.The DeleteFaculty() method in our Java bean is executed to delete a faculty record based on the selected faculty name from the Faculty table. The running result of this method is returned and assigned to the local integer variable delete.
D.We need to redisplay the Faculty.jsp page to enable users to perform the next action.
E.Finally, the CloseDBConnection() method is called to disconnect the connection to our database.
Now we can build and run our project to test this faculty record deleting function.
Click on the Clean and Build Main Project button to perform cleaning up and building our project. Then right click on the LogIn.jsp page from the Projects window to run our project. Enter the appropriate username and password, such as jhenry and test, to finish the login process, and select the Faculty Information item from the Selection. jsp page to open the Fcaulty.jsp page.
To delete a faculty record, first, let’s perform a query operation to retrieve and display that faculty record. Enter a faculty name, such as Ying Bai, into the Faculty Name field, and click on the Select button. All seven pieces of information related to that faculty are retrieved and displayed in this page. Now click on the Delete button to try to delete this record from our Faculty table.
To confirm this data deleting action, two ways could be used. The first way is to use the Select button in the Faculty.jsp page to try to retrieve this deleted record from the Faculty table. To do that, enter the deleted faculty name Ying Bai to the Faculty Name field and click on the Select button. You can find that all seven fields are displayed with nulls, as shown in Figure 8.94, which means that the faculty member Ying Bai has been
666 Chapter 8 Developing Java Web Applications to Access Databases
Figure 8.94. The confirmation of the faculty data deletion action.
deleted from the Faculty table. Now click on the Back and Exit button to terminate our project.
The second way to confirm this data deleting is to open the Faculty table in the NetBeans IDE environment. Open the Services window, expand the Databases node andourSQLServerdatabaseURL:jdbc:sqlserver://localhost\SQL2008EXPRESS:5000; databaseName=CSE_DEPT [ybai on dbo]. Right click on this URL and select the
Connect item to connect to our sample database. Then expand our database CSE_DEPT, dbo, and Tables. Right click on the Faculty table and select the View Data item to open this table. You can find that the faculty record with the faculty_id of B78880 has been deleted.
Our data deleting action using the JSP and Java bean is successful!
It is highly recommended to recover this deleted faculty record in the Faculty table since we want to keep our database neat and clean.
The point to be noted is that when we delete a faculty member from the Faculty table, which is a parent table relative to the Course and LogIn tables that are child tables, the related records to that deleted faculty in those child tables will also be deleted, since a cascaded deleting relationship has been set up between the parent and child tables when we built this database in Chapter 2. Therefore, the faculty login record in the LogIn table and all courses taught by that faculty in the Course table will be deleted when the faculty member is deleted from the Faculty table. Also, because the Course table is a parent table relative to the StudentCourse table, all courses taken by students and taught by the deleted faculty will be deleted from the StudentCourse table. To recover these
