JAVA RUNTIME OBJECTS METHOD
8.1.5 Using the JSP Implicit Object Session for Java
As we mentioned in Section 8.1.2 , the session is a JSP implicit object used to facilitate developers to build professional Java Web applications. The implicit means that those objects, including the session object, can be created automatically as a new JSP is exe- cuted. The specifi c property of using a session object is that you can save user data in some web pages and retrieve them from other web pages. This provides a great and con- venient way to transfer data between clients and clients, and also between clients and a server.
In this section, we will use this session object to help us to build our Faculty page to query and display the desired faculty information from the Faculty table in our sample database. The structure or architecture of using the session object to coordinate the data query from the Faculty table is shown in Figure 8.13 .
Basically, this structure is identical with that we discussed in the last section, and the only difference is that we use a new Java help class fi le FacultyBean.java that is not a real Java Bean class but is very similar to one JavaBean. The reason we did this is that we do not want to have a big jump between the help class and JavaBean to make this design diffi cult.
The FacultyPage.jsp that is our Web client page is shown in Figure 8.14 . Because of its complexity in HTML and JSP codes, we will leave the building and coding of this page in our real project later. In fact, we need to use Microsoft Offi ce Publisher 2007 to build a FacultyPage.html fi le fi rst and then convert it to a FacultyPage.jsp fi le. Now we just assume that we have built this page and want to use it in our Faculty table query process.
Now let ’ s modify this FacultyPage.jsp to use session object to perform data storage and retrieving functions between this page and the help class fi le FacultyQuery.jsp . 8.1.5.1 Modify the FacultyPage JSP File to Use the Session Object
Perform the modifi cations shown in Figure 8.15 to this FacultyPage.jsp fi le to use the session object to store and pick up data between client pages. All modifi ed codes have been highlighted in bold.
Figure 8.13. The architecture of using session object in Web applications.
FacultyPage.jsp Client
FacultyQuery.jsp Web Server HTTP
Request
HTTP Response
Database Server FacultyBean.java Hibernate
persistence API
c08.indd 572
c08.indd 572 7/20/2011 11:12:25 AM7/20/2011 11:12:25 AM
www.traintelco.com
Figure 8.14. The preview of the FacultyPage.jsp page.
Figure 8.15. The modifi cations to the FacultyPage.jsp fi le.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LogIn Query Page</title>
</head>
<body>
<%@page language="java" %>
<form method=post action=".\FacultyQuery.jsp">
<input name=FacultyNameField maxlength=255 size=24
value="<%=session.getAttribute("facultyName") %>" type=text v:shapes="_x0000_s1109">
………
<input name=FacultyIDField maxlength=255 size=26
value="<%=session.getAttribute("facultyId") %>" type=text v:shapes="_x0000_s1110">
………
<input name=NameField maxlength=255 size=26
value="<%=session.getAttribute("facultyName") %>" type=text v:shapes="_x0000_s1106">
………
<input name=OfficeField maxlength=255 size=26
value="<%=session.getAttribute("office") %>" type=text v:shapes="_x0000_s1104">
………
<input name=PhoneField maxlength=255 size=26
value="<%=session.getAttribute("phone") %>" type=text v:shapes="_x0000_s1116">
………
<input name=CollegeField maxlength=255 size=26
value="<%=session.getAttribute("college") %>" type=text v:shapes="_x0000_s1117">
………
<input name=EmailField maxlength=255 size=26
value="<%=session.getAttribute("email") %>" type=text v:shapes="_x0000_s1118">
………
</body>
</html>
A B
C
D E
F G
H
Figure 8.16. The codes for the model and controller page FacultyQuery.jsp.
<%@ page import="java.util.*" %>
<%@ page import="JavaWebHibDBOraclePackage.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FacultyQuery JSP Page</title>
</head>
<body>
<h1>This is the FaculrtQuery JSP Page!</h1>
<%
String fname = request.getParameter("FacultyNameField");
FacultyBean fBean = new FacultyBean();
List fList = fBean.QueryFaculty(fname);
session.setAttribute("facultyId", fBean.getFacultyID());
session.setAttribute("facultyName", fBean.getFacultyName());
session.setAttribute("office", fBean.getOffice());
session.setAttribute("title", fBean.getTitle());
session.setAttribute("college", fBean.getCollege());
session.setAttribute("phone", fBean.getPhone());
session.setAttribute("email", fBean.getEmail());
response.sendRedirect("FacultyPage.jsp");
%>
</body>
</html>
A
B C D E
F
In step A , we add an action attribute to forward all information collected from this page to our model and controller page FcaultyQuery.jsp that will call our FacultyBean fi le to perform the faculty data query process.
Starting from step B until step H , we use the embedded JSP codes to assign the real queried faculty columns from our Faculty table to the value tag of each 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 FacultyPage.jsp page. In this way, a direct connec- tion or binding between the text fi elds in our Facultypage.jsp page and the queried Faculty columns in our help class is established.
Now let ’ s take a look at our model and controller page FacultyQuery.jsp . 8.1.5.2 Build the Transaction JSP File FacultyQuery.jsp
The purpose of this fi le is to transfer data and information between our main displaying page FacultyPage.jsp and our working help class fi le FacultyBean that performs all JDBC - and database - related operations and business logics. The codes for this fi le are shown in Figure 8.16 .
Let ’ s take a closer look at this piece of codes to see how it works.
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 two packages:
one is java.util. * , since we need to use the List class and JavaWebHibDBOraclePackage. * , since we built our FacultyBean help class in that package.
c08.indd 574
c08.indd 574 7/20/2011 11:12:25 AM7/20/2011 11:12:25 AM
www.traintelco.com
B. The getParameter() method is executed to get the faculty name entered by the user to the Faculty Name text fi eld in the FacultyPage.jsp page, and this faculty name is assigned to a local String variable fname .
C. A new instance of our help class FacultyBean is created.
D. The main help method QueryFaculty() we built in the FacultyBean is called to query a faculty record based on the faculty name we obtained from step B .
E. The setAttribute() method in the session class is executed to store each column of queried faculty row from the Faculty table with a given name. The getter() methods defi ned in the FacultyBean class are executed to pick up each queried column. The point to be noted is that later on, when we need to pick up these queried columns from the session object in other pages, we need to use the identical names we used here for each column, such as facultyId , facultyName , title, and so on.
F. Finally, since we need to display all queried columns to the associated text fi eld in the
FacultyPage.jsp page, we use the sendRedirect() method to return to that page.
Finally, let ’ s take care of the help class fi le FacultyBean .
8.1.5.3 Build the Help Class FacultyBean
This class is a help class, but is very similar to a real Java bean class. The codes of this class are shown in Figure 8.17 .
Let ’ s have a closer look at this piece of codes to see how it works.
A. At the beginning of this class, seven member data or properties of this class are defi ned. This is very important in a Java bean class since all data - related transactions between the client pages and Java bean are dependent these properties. In other words, all clients could pick up data from a Java bean using those properties, and a one - to - one rela- tionship exists between each property in the Java bean class and each queried column in the data table. According to the convention, all of these properties should be defi ned in private data type and can be accessed by using the getter() methods provided in this Java bean class.
B. A new instance of the Hibernate session class is created and initialized. The point to be noted is that this Hibernate session object is different with that JSP implicit session object.
C. The getCurrentSession() method is executed to get the default Hibernate session object.
D. The detailed defi nition of the QueryFcaulty() method starts from here with the method header.
E. A new java.util.List instance is created and initialized since we need this object to pick up and hold our queried faculty result. The MsgDislog instance is used to display error information in case any exception was encountered during this query operation.
F. A try … catch block is used to perform our data query. First, a new Transaction instance tx is created. with the beginTransaction() method being executed.
G. Then a query string built with the Hibernate Query Language (HQL) is created, and this query string will be used to perform the faculty information query later.
H. The list() method is executed to perform a query to the Faculty table in our sample data- base to try to retrieve a matched faculty record based on the selected faculty name fname . The query result is assigned to and held in a local variable facultyList that has a
List < Faculty > data type.
Figure 8.17. The codes for the FacultyBean help class.
@Stateless
public class FacultyBean { private String facultyID;
private String facultyName;
private String office;
private String title;
private String phone;
private String college;
private String email;
public Session session = null;
public FacultyBean() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public List QueryFaculty(String fname) { List<Faculty> facultyList = null;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query f = session.createQuery ("from Faculty as f where f.facultyName like '"+fname+"'");
facultyList = (List<Faculty>) f.list();
} catch (Exception e) {
msgDlg.setMessage("Query is failed and no matched found!");
msgDlg.setVisible(true);
e.printStackTrace();
}
facultyID = facultyList.get(0).getFacultyId();
facultyName = facultyList.get(0).getFacultyName();
office = facultyList.get(0).getOffice();
title = facultyList.get(0).getTitle();
phone = facultyList.get(0).getPhone();
college = facultyList.get(0).getCollege();
email = facultyList.get(0).getEmail();
return facultyList;
}
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 I
J
K
c08.indd 576
c08.indd 576 7/20/2011 11:12:25 AM7/20/2011 11:12:25 AM
www.traintelco.com
I. The catch block is used to track and collect any possible exception during this query process. An error message will be displayed if this query encountered any problem.
J. The facultyList.get(0) method is used to retrieve the fi rst matched row from the query result. In fact, only one faculty row should be queried and retrieved, since all faculty names are unique in our sample database. A sequence of getter() methods is used to pick up the associated columns and assign them to the associated properties in this FacultyBean class.
Finally, the query result is returned to the FacultyQuery.jsp page.
K. Seven getter() methods are defi ned at the bottom of this class, and they can be used to pick up all properties defi ned in this class.
An operational sequence and data transformation structure of the Faculty Name is shown in Figure 8.18 .
In Figure 8.18 , the faculty name is used as an example to illustrate how to transfer this data between client and the help class. The operational sequence is:
1. First, a desired faculty name is entered by the user into the Faculty Name text fi eld in the
FacultyPage.jsp page. This piece of data will be transferred to the FacultyQuery.jsp page as the Select button is clicked by the user.
2. In the FcaultyQuery.jsp page, the getParameter() method is used to pick up this trans- ferred Faculty Name.
3. Then, the help method QueryFaculty() in the help class FacultyBean is called to query a matched faculty record from the Faculty table based on the transferred faculty name
fname .
4. When the getter() method in the FacultyBean class is executed, the queried faculty name is returned to the FacultyQuery.jsp page.
5. One of session method, setAttribute() , is called to store this queried faculty name into the JSP implicit object session.
6. The getAttribute( “ facultyName ” ) method that is assigned to the value tag of the FacultyName text fi eld will pick up the queried faculty name and display in this text fi eld in step 7.
Figure 8.18. The operational sequence and data transfer structure using the session object.
Faculty Name
Select FacultyPage.jsp
Session value="<%=session.getAttribute("facultyName")%>"
FacultyQuery.jsp
fname = request.getParameter("FacultyNameField");
List fList = fBean.QueryFaculty(fname);
session.setAttribute("facultyName", fBean.getFacultyName());
FacultyBean.java List QueryFaculty(String fname) {
facultyName = facultyList.get(0).getFacultyName();
public String getFacultyName() {return this.facultyName;}
7
1
2
3
4 5
6
By referring to Figure 8.18 , we can get a clear and complete picture about the data storage and transferring between different pages.
Now if you compile and run these three fi les, FacultyPage.jsp , FacultyQuery.jsp , and FacultyBean.java , you can get the start page shown in Figure 8.19 .
Enter a desired faculty name, such as Ying Bai , into the Faculty Name text fi eld, and click on the Select button; the running result is shown in Figure 8.20 .
As we mentioned at the beginning of this chapter, Java EE provides a set of powerful tools and supports to Java Web applications to access and manipulate databases. One of the most important components provided by Java EE is the Java bean that works as a separate component to perform database - related operations and business logics. By com- bining the JavaServer Faces techniques and Java beans, a professional Java Web database application can be divided into two separate parts: the GUIs that are built with JSF tags in JSP are used for data presentations and results displaying, and Java managed beans used for database - related operations and business logics. By dividing a Web application into these two sections, it has greatly reduced the development efforts and complexities in the coding development and organizations of the whole application.
Now let ’ s take care of using Java beans technology for Java Web applications.