Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
787
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

8.1 A Historical Review about Java Web Application Development 567

<html>

<head>

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

</head>

<body>

<%@page language="java" %>

A<form method="POST" action=".\LogInQuery.jsp">

<table>

<tr>

<td colspan=2>

<h3>Welcome to CSE DEPT</h3> </td>

</tr>

<tr>

<td>UserName:</td>

<td><input type="text" name="username"><br></td>

</tr>

<tr>

<td>PassWord:</td>

<td><input type="password" name="password"><br></td>

</tr>

<tr>

<td colspan=2> </td>

</tr>

<tr>

<td>

<input type="submit" value="LogIn" name="loginButton">

B<input type="button" value="Cancel" name="cancelButton" onclick="self.close()">

</td>

</tr>

</table>

C</form>

</body>

</html>

Figure 8.8. The modified Login.html file (now it is index.jsp).

Now let’s build our LogInQuery.jsp page, which works as a part of server, to receive and handle the Form data, including the login information sent by the index.jsp page.

Figure 8.9 shows the codes for this page.

Let’s have a closer look at this piece of codes to see how it works.

A.A JSP directive tag is used to indicate that this page uses the Java language and it is a JSP file.

B.Some local variable and object are declared first. The string variable nextPage is used to hold the URL of the next page, and the lquery is a new instance of our Java help class LogInQuery we built at the beginning of this section.

C.The getParameter() method is used to pick up the login information entered by the user in the index.jsp page. The collected login information, including the username and password, is assigned to two local string variables u_name and p_word, respectively.

D.The checkLogIn() method defined in our Java help class file is called to perform the database query and the login matching processing. The collected login information is used as arguments and passed into this method. The running result of this method is a string, and it is assigned to the local string variable result.

568 Chapter 8 Developing Java Web Applications to Access Databases

<html>

<head>

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

</head>

<body>

A<%@page language="java" %> <%

BString nextPage = null;

LogInQuery lquery = new LogInQuery();

CString u_name = request.getParameter("username"); String p_word = request.getParameter("password");

DString result = lquery.checkLogIn(u_name, p_word);

Eif (result.equals("Matched")) {

nextPage = "Selection.jsp";

}

Felse { out.println("LogIn is failed"); } %>

G<jsp:forward page = "<%=nextPage%>" />

</body>

</html>

Figure 8.9. The codes for the LogInUuery.jsp page.

E.An if block is used to check the running result of the checkLogIn() method. The program will be forwarded to a successful page (Selection.jsp) if a matched login record is found from our LogIn table.

F.Otherwise, an error message is printed to indicate that this login process has failed.

G.A JSP forward directive is used to direct the program to the next page.

In summary, to use a JavaServer Page to assistant a Java Web application, the following components should be considered and adopted:

1.The whole Web application can be divided into two parts:

A.The JDBC and database processing-related functions and business logics—Java help class file (LogInQuery.java).

B.The user data input and running result output functions—HTML or JSP (index.jsp and

LogInQuery.jsp).

2.The relationships between these three pages are:

A.The index.jsp, which runs on the client side, works as a starting or a homepage as the Web application runs, and it is used to collect the user information and sends it to the Web server.

B.The LogInQuery.jsp, which can be considered as a part of the application server and runs at the server side, provides the information passing or transformation functions between the home page and other target pages to collect the user information, call the Java help class to perform the data and business logic processing, and direct the program to the different target pages based on the data processing results.

C.The Java help class file LogInQuery.java, which provides the JDBC and database processing functions and business logics processing abilities, and works as an intermediate

8.1 A Historical Review about Java Web Application Development 569

Web Server

 

HTTP

Database

 

Server

 

Request

 

 

index.jsp

LogInQuery.jsp

LogInQuery.java

Client

 

 

 

HTTP

 

 

Response

 

Figure 8.10. The components and their relationships in a JSP Web application.

layer between the server and clients to support above two JSP files. Since this help class file will be called by the LogInQuery.jsp, it also belongs to the server side software.

These components and their relationships can be expressed and illustrated in Figure 8.10.

Compared with our first Java Web application that utilized the Java Servlet and HTML page, the Web application that used the JSP techniques has a great improvement on simplification of data collection and processing by using different function-related pages and help class file. However, one defect is that the JDBC and database-related functions makes the Java help class file LogInQuery.java very complicated because too many database-related functions must be involved and executed, such as loading database driver, connecting to the database, creating query-related objects, building the data query, and collecting the queried results; all of these operations makes this file longer and increases the complex in operations. A good solution to this is to use the Java Persistence API to simplify these operations and make the file short and simple.

8.1.4 Using Java Persistence APIs for Java Web Applications

Two Java Persistence APIs are involved in NetBeans IDE, Java Persistence API and Hibernate API, and both provide good functions and controllabilities on database accessing and data processing. In this section, we want to use the Hibernate API to illustrate how to use this API to simplify the database accessing and data operations in our Java help class file.

In Section 5.3.6.2 in Chapter 5, we have provided a very detailed discussion about the Hibernate technique. In fact, Hibernate is an object-relational mapping (ORM) library for the Java language, and it provides a framework for mapping an object-oriented domain model to a traditional relational database. Unlike the Java Persistence API, Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

To use the Hibernate technique to build a Web application in NetBeans IDE, perform the following operations:

1.Select the Hibernate framework when create a new Web application.

2.Modify the Hibernate Configuration file to include the desired database.

3.Create the HibernateUtil.java helper file to access the session object.

4.Generate Hibernate Mapping Files and Java Classes for all data tables in our sample database.

570 Chapter 8 Developing Java Web Applications to Access Databases

We will discuss these topics in more details in the following sections.

Suppose now we have installed the Hibernate frameworks and complete all of these operations listed above, now let’s use the Hibernate frameworks to simplify the codes in our Java help class file LogInQuery.java. The modified LogInQuery.java file that used the Hibernate technique is shown in Figure 8.11.

Let’s have a closer look at this piece of modified codes to see how it works.

A.All necessary packages related to components and library files used in this help class file are declared first.

B.A new instance of Hibernate session object is created and initialized. The purpose of creating this session instance is that we need to use it to perform all data actions to our sample database later.

C.The getCurrentSession() method is executed to get the default session object.

D.The detailed definition of the checkLogIn() method starts from here with the method header.

Aimport csedept.entity.Login; import csedept.util.HibernateUtil; import java.util.List;

import org.hibernate.Query; import org.hibernate.Session;

public class LogInQuery {

private String user_name = null; private String pass_word = null;

Bpublic Session session = null; public LogInQuery() {

Cthis.session = HibernateUtil.getSessionFactory().getCurrentSession();

}

D

public String checkLogIn(String uname, String pword) {

EList<Login> loginList = null;

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true); try {

Forg.hibernate.Transaction tx = session.beginTransaction();

GQuery q = session.createQuery ("from Login as lg where lg.userName like '"+uname+"'

and lg.passWord like '"+pword+"'");

HloginList = (List<Login>) q.list();

I} catch (Exception e) {

msgDlg.setMessage("Query is failed and no matched found!"); msgDlg.setVisible(true);

e.printStackTrace();

}

Juser_name = loginList.get(0).getUserName(); pass_word = loginList.get(0).getPassWord();

Kif (user_name.equals(uname) && pass_word.equals(pword)) { return "Matched";

 

}

L

else {

 

return "Nomatched";

 

}

 

}

 

}

Figure 8.11. The Java help class with the Hibernate frameworks support.

8.1 A Historical Review about Java Web Application Development 571

E.A new java.util.List instance is created and initialized since we need this object to pick up and hold our queried login result.

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 login information query later.

H.The list() method is executed to perform a query to the LogIn table in our sample database

to try to retrieve a pair of matched username and password. The query result is assigned to and held in a local variable loginList that has a List<LogIn> data type.

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 loginList.get(0).getUserName() and loginList.get(0).getPassWord() methods are called to pick up the matched username and password. The first part, loginList.get(0), returns the first matched row in which a match username and a password are stored. The second part, getUserName() and getPassWord(), are used to pick up the matched username and password columns from that first matched row. Since in our database, exactly in our LogIn table, there is only one record or one row existed in there, therefore, only one row or the first row can be returned. The returned username and password are assigned to two member data or two properties of the help class, user_name and pass_word, respectively.

K.A business logic is performed to check whether the queried login information is matched to the login information entered by the user. If it is, a Matched string is returned to the

LogInQuery.jsp file.

L.Otherwise a Nomatched string is returned.

Comparing the codes in Figure 8.7 with the codes in Figure 8.11, it can be found that the JDBCand database-related process, as well as the business logics in the latter has been simplified by using the Hibernate API.

The components and their relationships used in this JSP Web application with the help of the Hibernate persistence API are basically identical with those used in the JSP Web applications without Hibernate persistence API. The only difference between them is that the coding processing has been greatly simplified in the former Web applications.

These components and their relationships used in this JSP Web application with the help of the Hibernate persistence API can be expressed and illustrated in Figure 8.12.

An alternative way is to use the Java Persistence API to replace this Hibernate API to perform an object-relational database mapping to execute data actions against our sample database for Web applications.

 

Web Server

 

 

HTTP

 

 

Database

Request

 

 

Server

index.jsp

LogInQuery.jsp

LogInQuery.java

Hibernate

persistence

Client

 

 

 

 

API

HTTP

 

 

 

 

 

Response

 

 

 

Figure 8.12. The components and relationships in a JSP Web application with Hibernate API.

572 Chapter 8 Developing Java Web Applications to Access Databases

After using the Java help class to handle the JDBCand database-related processing, as well as business logics, the Java Web applications can be developed and built more objectively, simply and clearly. Next, let’s discuss how to convert this help class to a former Java technique way, or a Java bean, to do these kinds data operations and business logics.

8.1.5 Using the JSP Implicit Object Session for Java Web Applications

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 executed. The specific 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 convenient 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 file 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 difficult.

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 Office Publisher 2007 to build a FacultyPage.html file first and then convert it to a FacultyPage.jsp file. 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 file FacultyQuery.jsp.

8.1.5.1 Modify the FacultyPage JSP File to Use the Session Object

Perform the modifications shown in Figure 8.15 to this FacultyPage.jsp file to use the session object to store and pick up data between client pages. All modified codes have been highlighted in bold.

Web Server

HTTP

Request

FacultyPage.jsp

FacultyQuery.jsp

FacultyBean.java

Hibernate

persistence

Client

 

 

 

 

API

 

 

 

 

HTTP

 

 

 

Response

 

 

Figure 8.13. The architecture of using session object in Web applications.

Database

Server

8.1 A Historical Review about Java Web Application Development 573

Figure 8.14. The preview of the FacultyPage.jsp page.

<html>

<head>

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

</head>

<body>

<%@page language="java" %>

A<form method=post action=".\FacultyQuery.jsp">

<input name=FacultyNameField maxlength=255 size=24

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

 

………

 

 

 

<input name=FacultyIDField maxlength=255 size=26

 

 

C

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

 

………

 

 

 

<input name=NameField maxlength=255 size=26

 

 

D

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

 

………

 

 

 

<input name=OfficeField maxlength=255 size=26

 

 

E

value="<%=session.getAttribute("office") %>"

type=text

v:shapes="_x0000_s1104">

 

………

 

 

 

<input name=PhoneField maxlength=255 size=26

 

 

F

value="<%=session.getAttribute("phone") %>"

type=text

v:shapes="_x0000_s1116">

 

………

 

 

 

<input name=CollegeField maxlength=255 size=26

 

 

G

value="<%=session.getAttribute("college") %>" type=text

v:shapes="_x0000_s1117">

 

………

 

 

 

<input name=EmailField maxlength=255 size=26

 

 

H

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

 

………

 

 

 

</body>

 

 

 

</html>

 

 

Figure 8.15. The modifications to the FacultyPage.jsp file.

574 Chapter 8 Developing Java Web Applications to Access Databases

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 file 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 field 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 modification will be immediately updated and reflected to each text field in our FacultyPage.jsp page. In this way, a direct connection or binding between the text fields 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 file is to transfer data and information between our main displaying page FacultyPage.jsp and our working help class file FacultyBean that performs all JDBCand database-related operations and business logics. The codes for this file 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 file. 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.

A<%@ 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> <%

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

CFacultyBean fBean = new FacultyBean();

DList fList = fBean.QueryFaculty(fname);

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

Fresponse.sendRedirect("FacultyPage.jsp");

%>

</body>

</html>

Figure 8.16. The codes for the model and controller page FacultyQuery.jsp.

8.1 A Historical Review about Java Web Application Development 575

B.The getParameter() method is executed to get the faculty name entered by the user to the Faculty Name text field 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 defined 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 field in the FacultyPage.jsp page, we use the sendRedirect() method to return to that page.

Finally, let’s take care of the help class file 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 defined. 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 relationship 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 defined 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 definition 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 database 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.

576 Chapter 8 Developing Java Web Applications to Access Databases

@Stateless

public class FacultyBean {

Aprivate String facultyID; private String facultyName; private String office; private String title;

private String phone; private String college; private String email;

Bpublic Session session = null; public FacultyBean() {

Cthis.session = HibernateUtil.getSessionFactory().getCurrentSession();

}

D

public List QueryFaculty(String fname) {

EList<Faculty> facultyList = null;

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true); try {

Forg.hibernate.Transaction tx = session.beginTransaction();

GQuery f = session.createQuery ("from Faculty as f where f.facultyName like '"+fname+"'");

HfacultyList = (List<Faculty>) f.list();

I} catch (Exception e) {

msgDlg.setMessage("Query is failed and no matched found!"); msgDlg.setVisible(true);

e.printStackTrace();

}

JfacultyID = 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;

}

K 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;

}

}

Figure 8.17. The codes for the FacultyBean help class.