JAVA RUNTIME OBJECTS METHOD
8.5 BUILD JAVA WEB PROJECT TO ACCESS SQL SERVER
8.5.5 Update and Delete Data from the Faculty Table Using
To use the JSP and Java bean techniques to perform data updating and deleting actions against the Faculty table, we need to perform the following operations:
1. Create a new Java Session bean class FacultyUpdateDeleteBean.java to handle the data updating and deleting actions.
2. Modify the model controller page FacultyProcess.jsp to handle the faculty data collection and manipulations.
First let ’ s create our Java session bean class FacultyUpdateDeleteBean.java to handle the data updating and deleting actions.
8.5.5.1 Create a New Java Session Bean Class
Perform the following operations to create a new Java session bean class:
1. Right click on our project JavaWebDBJSPSQL from the Projects window and select the
New > Session Bean item to open the New Session Bean wizard.
2. Enter FacultyUpdateDeleteBean into the EJB Name fi eld.
3. Select the JavaWebDBJSPSQLPackage from the Package combo box.
4. Keep all other default settings and click on the Finish button.
On the created FacultyUpdateDeleteBean.java class, we need to create two new methods UpdateFaculty() and DeleteFaculty() . These two methods are used to perform the data updating and deleting operations against our sample database. Figure 8.87
Figure 8.86. The new inserted faculty information.
c08.indd 656
c08.indd 656 7/20/2011 11:12:31 AM7/20/2011 11:12:31 AM
www.traintelco.com
Figure 8.87. The fi rst part of the codes of the Java bean class fi le.
package JavaWebDBJSPSQLPackage;
import java.sql.*;
import javax.ejb.Stateless;
public class FacultyUpdateDeleteBean { private 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() { try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (Exception e) {
msgDlg.setMessage("Class not found exception!" + e.getMessage());
msgDlg.setVisible(true);
}
String url = "jdbc:sqlserver://localhost\\SQL2008EXPRESS:5000;databaseName=CSE_DEPT;";
try {
con = 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) { int numUpdated = 0;
String query = "UPDATE Faculty SET faculty_name=?, office=?, phone=?, title=?, college=?, email=? " + "WHERE faculty_name= ?";
try {
PreparedStatement pstmt = con.prepareStatement(query);
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 numUpdated = pstmt.executeUpdate();
}
catch (SQLException e) {
msgDlg.setMessage("Error in Statement!" + e.getMessage());
msgDlg.setVisible(true);
}
return numUpdated;
} ………
A
B
C
D E
F G H
I J
K
shows the fi rst 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 fi rst, since all SQL Server database - related classes and methods are defi ned in that package.
B. Seven class properties related to the associated columns in the Faculty table in our sample database are declared fi rst. 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 defi ned 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 database - driver loading process.
D. The database connection URL is defi ned. 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 defi ned 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 fi rst 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 state- ment with the positional order. This order must be identical with that defi ned 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 defi ned, and they are used to pick up all seven properties defi ned at the beginning of this class.
c08.indd 658
c08.indd 658 7/20/2011 11:12:31 AM7/20/2011 11:12:31 AM
www.traintelco.com
In fact, the codes for this Java bean class fi le are basically identical with those we built in our Java help class fi le, which include the loading JDBC driver, defi ning the data- base 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 modifi cations 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 fi eld, and
JavaWebDBJSPSQLPackage. FacultyUpdateDeleteBean into the Class fi led. Select
Figure 8.88. The second part of the codes of the Java bean class fi le.
public void CloseDBConnection() {
try{
if (!con.isClosed()) con.close();
}catch (SQLException e) {
msgDlg.setMessage("Error in close the DB! " + e.getMessage());
msgDlg.setVisible(true);
} }
public String getFacultyID() { return this.facultyID;
}
public String getFacultyName() { return this.facultyName;
}
public String getOffice() { return this.office;
}
public String getTitle() { return this.title;
}
public String getPhone() { return this.phone;
}
public String getCollege() { return this.college;
}
public String getEmail() { return this.email;
} } A
B
C
D
E
F
G
H
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 infor- mation stored in the seven fi elds in the Faculty.jsp page. The collected seven pieces of new faculty information are assigned to seven local String variables.
Figure 8.89. The modifi ed codes for the Update block.
else if (request.getParameter("Update")!= null) { //process the faculty record updating %>
<jsp:useBean id="UpdateFaculty" scope="session"
class="JavaWebDBJSPSQLPackage.FacultyUpdateDeleteBean" />
<jsp:setProperty name="UpdateFaculty" property="*" />
<%
int update = 0;
String 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");
String[] upf = {fname, office, phone, title, college, email, f_name };
update = UpdateFaculty.UpdateFaculty(upf);
if (update == 0)
response.sendRedirect("Faculty.jsp");
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);
response.sendRedirect("Faculty.jsp");
fQuery.setFacultyImage(request.getParameter("FacultyImageField"));
}
UpdateFaculty.CloseDBConnection();
} ………
1 2 3 4 A B
C D E F
G H I
c08.indd 660
c08.indd 660 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM
www.traintelco.com
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 fi elds 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 defi ned 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 confi rm 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 fi nish 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, fi rst, 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 fi eld 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 fi elds (no Faculty ID fi eld), and enter the default faculty image ’ s name, Default.jpg , into the Image fi eld, since we want to use this default image as our updating faculty image. The fi nished 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 fi nd that the original faculty information is displayed, which means that this data updating is successful.
To confi rm this updating action, two ways could be used. The fi rst 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 fi eld and click on the Select button. You can fi nd that the updated record is retrieved and displayed in the seven fi elds 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 confi rm 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
Figure 8.90. The entered faculty updating information.
Figure 8.91. The updated faculty information.
c08.indd 662
c08.indd 662 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM
www.traintelco.com
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 fi nd 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 fi rst 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 .
Table 8.3. The original data for faculty member Ying Bai
faculty_id faculty_name office phone college title email
B78880 Ying Bai MTC-211 750-378-1148 Florida Atlantic University Associate Professor ybai@college.edu
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 modifi cations 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 fi eld, and
JavaWebDBJSPSQLPackage. FacultyUpdateDeleteBean into the Class fi eld. 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.
Figure 8.92. The codes for the DeleteFaculty() method.
………
public int DeleteFaculty(String fname) { int numDeleted = 0;
String query = "DELETE FROM Faculty WHERE faculty_name = ?";
try {
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, fname);
numDeleted = pstmt.executeUpdate();
}
catch (SQLException e) {
msgDlg.setMessage("Error in Statement!" + e.getMessage());
msgDlg.setVisible(true);
}
return numDeleted;
} ………
A B C D E F
G
c08.indd 664
c08.indd 664 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM
www.traintelco.com
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 execut- ing 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 fi nish 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, fi rst, 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 fi eld, 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 confi rm this data deleting action, two ways could be used. The fi rst 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 fi eld and click on the Select button. You can fi nd that all seven fi elds are displayed with nulls, as shown in Figure 8.94 , which means that the faculty member Ying Bai has been
Figure 8.93. The modifi ed codes for the Delete block.
………
else if (request.getParameter("Delete")!= null) { //process the faculty record deleting %>
<jsp:useBean id="DeleteFaculty" scope="session"
class="JavaWebDBJSPSQLPackage.FacultyUpdateDeleteBean" />
<jsp:setProperty name="DeleteFaculty" property="*" />
<%
int delete = 0;
String fname = request.getParameter("FacultyNameField");
delete = DeleteFaculty.DeleteFaculty(fname);
response.sendRedirect("Faculty.jsp");
DeleteFaculty.CloseDBConnection();
} ………
1 2 3 4 A B C D E