Insert New Records to the Faculty Table Using JSP and

Một phần của tài liệu practical database aprogramming with java (Trang 524 - 530)

JAVA RUNTIME OBJECTS METHOD

8.5 BUILD JAVA WEB PROJECT TO ACCESS SQL SERVER

8.5.4 Insert New Records to the Faculty Table Using JSP and

To use the JSP and Java bean techniques to perform inserting new record into the Faculty table, we need to perform the following operations:

c08.indd 650

c08.indd 650 7/20/2011 11:12:31 AM7/20/2011 11:12:31 AM

www.traintelco.com

1. Modify the Java help class fi le FacultyQuery.java to make it our Java bean class fi le

FacultyInsertBean.java to handle the new faculty record insertion actions.

2. Modify the model controller page FacultyProcess.jsp to handle the faculty data collection and insertion operations.

First, let ’ s modify the Java help class fi le FacultyQuery.java to make it our Java bean class FacultyInsertBean.java to handle the new faculty record insertion actions.

8.5.4.1 Modify the Java Help Class FacultyQuery to Make it Java Bean Class Double click on the Java help class fi le FacultyQuery.java from the Projects window to open it. Then go to File > Save As menu item to save this fi le as our new Java bean class fi le named FacultyInsertBean.java .

Perform the following modifi cations to this fi le to make it our Java bean class:

1. Change the class name and the constructor ’ s name from the FacultyQuery to the

FacultyInsertBean .

2. Remove the QueryFaculty() method and the getImage() method.

3. Remove the getFacultyImage() method and the facultyImage property.

4. Create a new method InsertFaculty() and enter the codes shown in Figure 8.82 into this method.

Let ’ s have a close look at the codes for this method to see how they work.

A. A new InsertFaculty() method is created with a String array as the argument of this method. The String array contains all seven pieces of new faculty information.

Figure 8.81. The running result of the Faculty.jsp page.

B. A local integer variable numInsert is created, and it is used to hold the returned data insertion result, which is regularly equal to the number of records that have been inserted into the Faculty table.

C. The insert string is created with seven positional parameters represented by the question marks in the query string.

D. A try … catch block is used to perform this faculty record insertion action. First, a PreparedStatement object is created with the query string as the argument.

E. Then seven elements in the String array newFaculty[] , which are equivalent to seven pieces of new faculty information, are assigned to seven positional parameters. The point to be noted is that the order of those seven elements must be identical with the order of columns represented in the query string.

F. The executeUpdate() method is executed to perform this new record insertion action. The running result, which equals to the number of records that have been successfully inserted into the Faculty table, is returned and assigned to the local integer variable numInsert . G. The catch block is used to track and collect any possible exceptions during this data inser-

tion action.

H. Finally, the running result is returned to the calling method in the FacultyProcess.jsp page.

Next let ’ s modify the model controller page FacultyProcess.jsp to handle the faculty data collection and insertion operations.

8.5.4.2 Modify the FacultyProcess.jsp Page to Handle Faculty Data Collection and Insertion

Double click on the FacultyProcess.jsp page from the Projects window, and perform the following modifi cations to this page to use Java bean FacultyInsertBean.java to perform new faculty record insertion actions:

Figure 8.82. The codes for the new created method InsertFaculty().

public int InsertFaculty(String[] newFaculty) { int numInsert = 0;

String InsertQuery = "INSERT INTO Faculty (faculty_id, faculty_name, office, phone, " + "college, title, email) VALUES (?, ?, ?, ?, ?, ?, ?)";

try{

PreparedStatement pstmt = con.prepareStatement(InsertQuery);

pstmt.setString(1, newFaculty[0]);

pstmt.setString(2, newFaculty[1]);

pstmt.setString(3, newFaculty[2]);

pstmt.setString(4, newFaculty[3]);

pstmt.setString(5, newFaculty[4]);

pstmt.setString(6, newFaculty[5]);

pstmt.setString(7, newFaculty[6]);

numInsert = pstmt.executeUpdate();

}

catch (SQLException e) {

msgDlg.setMessage("Error in Insert Statement! " + e.getMessage());

msgDlg.setVisible(true);

}

return numInsert;

} A B C D E

F G

H

c08.indd 652

c08.indd 652 7/20/2011 11:12:31 AM7/20/2011 11:12:31 AM

www.traintelco.com

1. Move to the else if (request.getParameter( “ Insert ” )! = null) block, then open the Palette window by going to 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 InsertFaculty into the ID fi eld, and

JavaWebDBJSPSQLPackage.FacultyInsertBean into the Class fi led. Select the session from the Scope combo box. Your fi nished Insert Use Bean dialog should match one that is shown in Figure 8.83 . Click on the OK button to close this dialog box. A JSP directive that contains the bean id, bean scope, and class is added to this block.

3. Add a JSP directive to set up all properties on the Java bean class FacultyInsertBean.java shown below:

<jsp:setProperty name =InsertFaculty 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.84 . Add the codes shown in steps AI in Figure 8.84 into this block.

Let ’ s have a closer look at these codes to see how they work.

A. A local integer variable res is created, and it is used to hold the running result of executing the InsertFaculty() method in the Java bean class FacultyInsertBean with the bean id of

InsertFaculty .

B. Seven getParameter() methods are used to pick up seven pieces of newly inserted faculty information 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.

C. A new String array fnew is created, and it is used to hold seven pieces of new faculty information stored in the seven local String variables.

D. The InsertFaculty() method in our Java bean is executed to insert these seven pieces of faculty information as a new faculty record into the Faculty table. The seven pieces of new faculty information is stored in the String array fnew that works as the argument for this method. The running result of this method is returned and assigned to the local integer variable res .

E. If the running result is 0, which means that no record has been inserted into the Faculty table ,and this data insertion action has failed. In that case, we need to redisplay the

Faculty.jsp page to enable users to reinsert that faculty record.

Figure 8.83. The fi nished Insert Use Bean dialog box.

F. If the running result is nonzero, which means that at least one new faculty record has been inserted into the Faculty table. We need to clean up all seven fi elds that contain seven pieces of newly inserted faculty information in the Faculty.jsp page to enable users to either to test this insertion or insert the next faculty record.

G. Also, 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 new faculty image ’ s name to it in order to display this new faculty image later when we confi rm a new faculty record ’ s insertion or 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 new faculty record insertion func- tion. 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 to fi nish the login process, and select the Faculty Information item from the Selection.jsp page to

Figure 8.84. The modifi ed codes for the Insert block.

else if (request.getParameter("Insert")!= null) { //process the faculty record insertion %>

<jsp:useBean id="InsertFaculty" scope="session"

class="JavaWebDBJSPSQLPackage.FacultyInsertBean" />

<jsp:setProperty name="InsertFaculty" property="*" />

<%

int res = 0;

String fid = request.getParameter("FacultyIDField");

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[] fnew = {fid, fname, office, phone, college, title, email };

res = InsertFaculty.InsertFaculty(fnew);

if (res == 0) {

response.sendRedirect("Faculty.jsp");

} else {

request.setAttribute("FacultyIDField", null);

request.setAttribute("NameField", null);

request.setAttribute("OfficeField", null);

request.setAttribute("PhoneField", null);

request.setAttribute("CollegeField", null);

request.setAttribute("TitleField", null);

request.setAttribute("EmailField", null);

response.sendRedirect("Faculty.jsp");

fQuery.setFacultyImage(request.getParameter("FacultyImageField"));

}

InsertFaculty.CloseDBConnection();

} ………

1 2 3 4 A B

C D E

F

G H I

c08.indd 654

c08.indd 654 7/20/2011 11:12:31 AM7/20/2011 11:12:31 AM

www.traintelco.com

open the Fcaulty.jsp page. Enter seven pieces of information into the associated seven fi elds as a new faculty record, 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 new faculty image.

The fi nished new faculty record is shown in Figure 8.85 .

Click on the Insert button to try to insert this new faculty record into the Faculty table in our sample database. Immediately, you can fi nd that the original faculty informa- tion is displayed, which means that this data insertion is successful.

To confi rm this insertion, two ways could be used. The fi rst way is to use the Select button in the Faculty.jsp page to retrieve this newly inserted record from the Faculty table. To do that, enter Tom Jeck to the Faculty Name fi eld and click on the Select button. You can fi nd that the new inserted record is retrieved and displayed in the seven fi elds with the default faculty image, as shown in Figure 8.86 . Now click on the Back and

Exit button to terminate our project.

The second way to confi rm this data insertion is to open the Faculty table. Open the

Services window, and expand the Databases node and our SQL Server database URL:

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 fi nd that the new faculty record has been inserted into this table at the last row.

Our data insertion using the JSP and Java bean is successful!

It is highly recommended to remove this newly inserted faculty record from the Faculty table, since we want to keep our database neat and clean.

Figure 8.85. The entered new faculty information.

Một phần của tài liệu practical database aprogramming with java (Trang 524 - 530)

Tải bản đầy đủ (PDF)

(791 trang)