Query the Faculty Table Using JSP and JSP Implicit

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

JAVA RUNTIME OBJECTS METHOD

8.5 BUILD JAVA WEB PROJECT TO ACCESS SQL SERVER

8.5.3 Query the Faculty Table Using JSP and JSP Implicit

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.

Figure 8.75. The running status of the Selection.jsp page.

c08.indd 640

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

www.traintelco.com

3. Create a help class fi le 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 modifi cations shown in Figure 8.76 to this page. All modifi ed coding parts have been highlighted in bold.

Figure 8.76. The modifi ed codes for the Faculty.jsp page.

<form method=post action=".\FacultyProcess.jsp">

………

<v:imagedata src="<%=session.getAttribute("facultyImage") %>" o:title="&lt;EMPTY&gt;"/>

<v:shadow color="#ccc [4]"/>

………

<input name=FacultyNameField maxlength=255 size=18

value="<%=session.getAttribute("facultyName") %>" type=text v:shapes="_x0000_s1029">

………

<input name=FacultyIDField maxlength=255 size=21

value="<%=session.getAttribute("facultyId") %>" type=text v:shapes="_x0000_s1031">

………

<input name=NameField maxlength=255 size=21

value="<%=session.getAttribute("facultyName") %>" type=text v:shapes="_x0000_s1033">

………

<input name=TitleField maxlength=255 size=21

value="<%=session.getAttribute("title") %>" type=text v:shapes="_x0000_s1035">

………

<input name=OfficeField maxlength=255 size=21

value="<%=session.getAttribute("office") %>" type=text v:shapes="_x0000_s1037">

………

<input name=PhoneField maxlength=255 size=21

value="<%=session.getAttribute("phone") %>" type=text v:shapes="_x0000_s1039">

………

<input name=CollegeField maxlength=255 size=21

value="<%=session.getAttribute("college") %>" type=text v:shapes="_x0000_s1041">

………

<input name=EmailField maxlength=255 size=21

value="<%=session.getAttribute("email") %>" type=text v:shapes="_x0000_s1043">

………

<input type=submit value=Select name="Select" v:shapes="_x0000_s1044">

………

<input type=submit value=Insert name="Insert" v:shapes="_x0000_s1045">

………

<input type=submit value=Update name="Update" v:shapes="_x0000_s1046">

………

<input type=submit value=Delete name="Delete" v:shapes="_x0000_s1047">

………

<input type=submit value=Back name="Back" v:shapes="_x0000_s1048">

………

A B

C

D

E

F

G

H

I

J K L M N O

Let ’ s have a closer look at this piece of modifi ed 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 fi le 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 fi eld 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 modifi cation will be immediately updated and refl ected to each text fi eld in our

Faculty.jsp page. In this way, a direct connection or binding between the text fi elds 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 data- base 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 defi ned as a property in our help class fi le, and a method, getFacultyImage() defi ned in that help class fi le, 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 fi les based on the button clicked by the user from the Faculty.jsp page. The following help class fi les 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 fi le 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 fi le 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 fi le FacultyUpdate.java , or the faculty record deleting help class fi le 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 fi eld and click on the Finish button.

c08.indd 642

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

www.traintelco.com

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 fi le. The format is < %@ page import= “ java package ” % > . In this page, we embed one package,

JavaWebDBJSPSQLPackage. * , since we will build our Java help class fi le 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 defi ned in that class to perform faculty record query and faculty image selection functions.

C. The getParameter() method defi ned 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 fi ve buttons in the Faculty.jsp page. All Faculty.jsp form data, including all text fi elds, image box, and submit buttons, will be submitted to this FacultyProcess.jsp page when any of fi ve 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 fi ve 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 getPa- rameter() method with the name of the faculty name fi eld, 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() defi ned in the help class fi le 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 defi ned in the response class.

G. Otherwise, a matched faculty record has been found and the query is successful. The setAt- tribute() method defi ned in the session class is used to set up all properties defi ned in the help class fi le using the associated getter methods in that class.

H. The getFacultyImage() method, which is defi ned in the help class fi le FacultyQuery.java and will be developed in the next section, is executed to pick up the correct faculty image fi le, exactly the correct name of the faculty image fi le.

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 fi eld. 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.

Figure 8.77. The codes for the FacultyProcess.jsp page.

<%@ page import="JavaWebDBJSPSQLPackage.*" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Faculty Process Page</title>

</head>

<body>

<%

FacultyQuery fQuery = new FacultyQuery();

if (request.getParameter("Select")!= null) { //process the faculty record query

String fname = request.getParameter("FacultyNameField");

boolean res = fQuery.QueryFaculty(fname);

if (!res)

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());

}

String fimg = fQuery.getFacultyImage();

if (fimg == null) {

if (request.getParameter("FacultyImageField")!= null)

session.setAttribute("facultyImage", request.getParameter("FacultyImageField"));

else

session.setAttribute("facultyImage", "Default.jpg");

} else

session.setAttribute("facultyImage", fimg);

fQuery.setFacultyImage(null);

response.sendRedirect("Faculty.jsp");

}

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

else if (request.getParameter("Update")!= null) { //process the faculty record updating

}

else if (request.getParameter("Delete")!= null) { //process the faculty record deleting

}

else if (request.getParameter("Back") != null) { fQuery.CloseDBConnection();

response.sendRedirect("Selection.jsp");

} %>

</body>

</html>

A

B C D E F G

H I

J

K L M N

O

P

Q

c08.indd 644

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

www.traintelco.com

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 defi ned 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 to the Selection.jsp page to perform other data query operations. The CloseDBConnection() method is fi rst 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 fi le 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 fi le 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 fi eld and select the JavaWebDBJSPSQLPackage from the Package combo box. Your fi nished 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 fi le.

Now let ’ s develop the codes for this new Java help class fi le. Double click on our new created Java help class fi le FacultyQuery.java from the Projects window to open this fi le, and enter the codes that are shown in Figure 8.79 into this fi le. Because of the large

size of this coding, we divide this coding process into two parts. The fi rst 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 fi rst since all SQL Server database related classes and methods are defi ned in that package.

B. Eight 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 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 defi ned. 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 defi ned with the selected faculty name as the argument. The SQL query statement is fi rst 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.

Figure 8.78. The fi nished New Java Class wizard.

c08.indd 646

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

www.traintelco.com

Figure 8.79. The fi rst part of the codes for the Java help class fi le.

package JavaWebDBJSPSQLPackage;

import java.sql.*;

public class FacultyQuery {

private static String facultyImage = null;

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 FacultyQuery() { 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 boolean QueryFaculty(String fname) {

String query = "SELECT faculty_id, title, office, phone, college, email FROM Faculty " + "WHERE faculty_name = ?";

try{

PreparedStatement pstmt = con.prepareStatement(query);

pstmt.setString(1, fname);

ResultSet rs = pstmt.executeQuery();

while (rs.next()){

facultyID = rs.getString(1);

title = rs.getString(2);

office = rs.getString(3);

phone = rs.getString(4);

college = rs.getString(5);

email = rs.getString(6);

facultyName = fname;

}

return true;

}

catch (SQLException e) {

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

msgDlg.setVisible(true);

return false;

} } A B

C

D

E F

G

H I J K

L M N

O

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

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

(791 trang)