Using Java Help Class Files for Java Web Applications

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

JAVA RUNTIME OBJECTS METHOD

8.1.3 Using Java Help Class Files for Java Web Applications

Take a look at the codes in Figure 8.6 , you can fi nd that about 80% of those codes are JDBC - related database processing codes, and 10% are about the data processing codes. Totally about 90% codes are used to access the database and query for the data and perform data matching functions. Only 10% codes are HTML codes.

To separate these two kinds of codes into two different fi les, we can pick up all JDBC related - codes and put them in a Java help class fi le, LogInQuery.java , as shown in Figure 8.7 .

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

A. Some member data or attributes are defi ned fi rst inside this class, which include two private String member data user_name and pass_word , a class - level connection variable con , and a dialog box that is used to display some debug information.

c08.indd 564

c08.indd 564 7/20/2011 11:12:23 AM7/20/2011 11:12:23 AM

www.traintelco.com

B. Inside the class constructor, an Oracle database driver is loaded, and this is a type IV JDBC driver.

C. The Oracle JDBC URL is assigned to the local variable url .

D. The getConnection() method is executed to establish this database connection.

E. The Java help method checkLogIn() is declared inside this help class. This method is a main function in performing the JDBC - related data query and data matching operations.

F. Some local variables used in this method are defi ned fi rst, which include the Statement and the ResultSet objects.

Figure 8.7. The codes for the Java Web help class LogInQuery.java.

import java.sql.*;

public class LogInQuery {

private String user_name = null;

private String pass_word = null;

static Connection con;

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

public LogInQuery() { try {

Class.forName("oracle.jdbc.OracleDriver");

}

catch (Exception e) {

msgDlg.setMessage("Class not found exception!" + e.getMessage());

msgDlg.setVisible(true);

}

String url = "jdbc:oracle:thin:@localhost:1521:XE";

try {

con = DriverManager.getConnection(url,"CSE_DEPT","reback");

}

catch (SQLException e) {

msgDlg.setMessage("Could not connect!" + e.getMessage());

msgDlg.setVisible(true);

e.printStackTrace();

} }

public String checkLogIn(String uname, String pword) { String c_uname = null, c_pword = null;

Statement stmt = null;

ResultSet rs = null;

String query = “SELECT user_name, pass_word FROM LogIn " +

"WHERE user_name = ‘” + uname + “’ “ + “ AND pass_word = ‘”+pword+”’;”;

stmt = con.createStatement();

rs = stmt.executeQuery(query);

while (rs.next()) {

c_uname = rs.getString(“user_name”);

c_pword = rs.getString(“pass_word”);

}

if (c_uname.equals(uname) && c_pword.equals(pword)) { user_name = c_uname;

pass_word = c_pword;

return “Matched”;

} else {

return “UnMatched”;

} } } A

B

C D

E F

G H I J

K

L

G. A query string is created, and it is used to query a matched username and password from the LogIn table.

H. The createStatement() method is called to create a Statement object.

I. The executeQuery() method is executed to perform this query, and the returned result is assigned to the ResultSet object rs .

J. A while loop is used to pick up any possible matched username and password. In fact, only one row is returned, and therefore this loop can run only one time. The getString() method is used to pick up the queried username and password. A point to be noted is that the arguments of this method, user_name and pass_word , are the column names in the LogIn table in our sample database CSE_DEPT, and they are different with those member data declared at the beginning of this class even they have the same names. The retuned username and password are assigned to two local variables c_uname and c_pword , respectively.

K. If a pair of matched username and password is found, they are assigned to two member data username and password , and return a “ Matched ” string to indicate that this check Login() method is successful and the matched results are found.

L. Otherwise, an “ Unmatched ” string is returned to indicate that no matched login informa- tion can be found.

Now let ’ s do a little modifi cation to our Login.html fi le and break this fi le into two JSP fi les: index.jsp and LogInQuery.jsp . The reason for us to make it into two JSP fi les is that we want to process and display data in two separate fi les to make it clear and easy.

Generally, the index.jsp can be considered as a starting or a home page as a Web appli- cation runs. Figure 8.8 lists the modifi ed codes for our original Login.html fi le that will be renamed to index.jsp , and the modifi ed parts have been highlighted in bold.

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

A. The fi rst modifi cation is that a Form tag is added into this page with a POST method and an action attribute. Generally, a Form tag is used to create a HTML form to collect user information and send all pieces of those collected information to the server when a submit button on this Form is clicked. Therefore, a Form and all submitting buttons on that Form have a coordinate relationship. If a button is defi ned as a submit button by its type attri- bute, all Form data will be sent to the server whose URL is defi ned in the action attribute on the Form tag when this submitting button is clicked by the user. Here, we use a Java Server Page, .\LogInQuery.jsp , as the URL for our target page. Exactly this target page is used to access our Java help class fi le to handle all JDBC and data - related processing and business logics. The .\ symbol is used to indicate that our JSP fi le is located at the rela- tively current folder, since this page is a part of the server functions and will be run at the server side as the whole project runs.

B. The second modifi cation is to change the type of our Cancel button from submit to

button , and add one more attribute onclick for this button. The reason for us to do this modifi cation is that we want to close our Login.jsp page when this Cancel button is clicked as the project runs, but we do not want to forward this button - click event to the server to allow the server to do this close action. Therefore, we have to change the type of this button to button (not submit ) to avoid triggering the action attribute in the Form tag. We also need to add a self.close() method to the onclick attribute of this button to call the system

close() method to terminate our application. The self means the current page.

C. The Form close tag is also added when the form arrived to its bottom.

c08.indd 566

c08.indd 566 7/20/2011 11:12:23 AM7/20/2011 11:12:23 AM

www.traintelco.com

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

B. Some local variable and object are declared fi rst. 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 pass- word, is assigned to two local string variables u_name and p_word , respectively.

D. The checkLogIn() method defi ned in our Java help class fi le is called to perform the data- base 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 .

Figure 8.8. The modifi ed Login.html fi le (now it is index.jsp).

<html>

<head>

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

<title>LogIn Page</title>

</head>

<body>

<%@page language="java" %>

<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>&nbsp;</td>

</tr>

<tr>

<td>

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

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

</td>

</tr>

</table>

</form>

</body>

</html>

A

B

C

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 follow- ing 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 fi le ( 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 fi le LogInQuery.java , which provides the JDBC and database pro- cessing functions and business logics processing abilities, and works as an intermediate

Figure 8.9. The codes for the LogInUuery.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" %>

<%

String nextPage = null;

LogInQuery lquery = new LogInQuery();

String u_name = request.getParameter("username");

String p_word = request.getParameter("password");

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

if (result.equals("Matched")) { nextPage = "Selection.jsp";

}

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

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

</body>

</html>

A B C D E

F G

c08.indd 568

c08.indd 568 7/20/2011 11:12:23 AM7/20/2011 11:12:23 AM

www.traintelco.com

layer between the server and clients to support above two JSP fi les. Since this help class fi le 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 fi rst Java Web application that utilized the Java Servlet and HTML page, the Web application that used the JSP techniques has a great improvement on simplifi cation of data collection and processing by using different function - related pages and help class fi le. However, one defect is that the JDBC and database - related functions makes the Java help class fi le 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 fi le 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 fi le short and simple.

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

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

(791 trang)