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

Practical Database Programming With Java

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

8.5 Build Java Web Project to Access SQL Server Database 627

our database application to perform the data actions against our sample SQL Server database.

First, let’s add all five web pages we built in Sections 8.4.3.1–8.4.3.5 into this new project. Perform the following operations to complete this web pages addition process:

1.Launch the Windows Explorer and go to the folder where we stored those five web pages; in this application, it is C:\Temp. Copy all five pages including LogIn.jsp, Selection.jsp, Faculty.jsp, Course.jsp, and Student.jsp, and then paste them to our new Web project folder, which is C:\Chapter 8\JavaWebDBJSPSQL in this application.

2.Launch the NetBeans IDE and open our new Web project JavaWebDBJSPSQL. Click on the Files tab to open the Files window and browse to our Web project folder JavaWebDBJSPSQL. You can find that all five web pages have been added into this project. Select all of these five pages using the Shift key, right click on these five selected pages, and click on the Copy item from the popup menu.

3.Click on the Projects tab to open the Projects window, browse to our project folder and then the Web Pages folder, right click on this folder and select the Paste item to paste these five Web Pages to this Web Pages folder.

Next we need to do a little modification to our LogIn.jsp file and break this file into two JSP files: LogIn.jsp and LogInQuery.jsp. The reason for us to make it into two JSP files is that we want to process and display data in two separate files to make these operations clear and easy.

8.5.1.1 Modify the LogIn.jsp Page and Create LogInQuery.jsp File

Now let’s first modify the LogIn.jsp page by double clicking on the LogIn.jsp to open it and perform the following modifications to this page. The modified parts have been highlighted in bold and are shown in Figure 8.60.

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

A.The first modification is to the form tag, and an action attribute has been added into this tag. 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 defined as a submit button by its type attribute, all Form data will be sent to the server whose URL is defined 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 file to handle all JDBCand database-related processing and business logics. The .\ symbol is used to indicate that our next JSP file is located at the relatively 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 modification is to add a name attribute to the LogIn button in order for it to be identified in the server side later.

C.The third modification is to change the type of our Cancel button from submit to button, and add a name and an onclick attribute for this button. The reason for us to do these modifications 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

628 Chapter 8 Developing Java Web Applications to Access Databases

<html xmlns:v="urn:schemas-microsoft-com:vml"

………

<body style='margin:0'>

<div style='position:absolute;width:10.-2040in;height:1.-1423in'> <![if !pub]>

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

………

<input name=UserNameField maxlength=255 size=21 value="" type=text v:shapes="_x0000_s1028">

………

<input name=PassWordField maxlength=255 size=21 value="" type=text v:shapes="_x0000_s1029">

………

B<input type=submit value=LogIn name="LogInButton" v:shapes="_x0000_s1030">

C<input type=button value=Cancel name="cancelButton" onclick="self.close()" v:shapes="_x0000_s1031">

………

</form>

</body>

</html>

Figure 8.60. The modifications to the LogIn.jsp page.

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.

Now let’s create and build our LogInQuery.jsp page, which works as a part of a server, to receive and handle the Form data, including the login information sent by the LogIn.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. If you cannot find the JSP item under the New menu item, go to Other item and select the Web from the Categories list, and the JSP item from the File Types list. Click on the Next button to open this wizard.

Enter LogInQuery to the File Name field in the opened New JSP File wizard and keep all other default settings unchanged. Then click on the Finish button to create this JSP file. Enter the codes that are shown in Figure 8.61 into the <body> . . . </body> tags in 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 Java language in this JSP page.

B.Some local variables and objects 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.java we will build in the next section.

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

8.5 Build Java Web Project to Access SQL Server Database 629

<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("UserNameField"); String p_word = request.getParameter("PassWordField");

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

Eif (result.equals("Matched"))

 

nextPage = "Selection.jsp";

F

else

 

out.println("LogIn is failed");

G

lquery.CloseDBConnection();

 

%>

H

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

 

</body>

 

</html>

Figure 8.61. The codes for the LogInQuery.jsp page.

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.

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

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

G.The CloseDBConnection() method defined in the help class is called to disconnect the connection to our sample database.

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

Next, let’s create and build our Java help class file LogInQuery.java to perform JDBCand database-related operations and actions.

8.5.1.2 Create the Java Help Class File LogInQuery.java

The purpose of this help class file is to handle the JDBC-related operations and database-related actions. As we discussed in Section 8.1.3, to distinguish between the database-related data processing and running results displaying, we can separate a Java Web application into two parts: the JDBC-related database processing and the business logics, such as checking and confirming a pair of matched username and password located

630 Chapter 8 Developing Java Web Applications to Access Databases

at a Java help class file, and the data and running results displaying at a Web or a JavaServer page.

It looks like that we can use the Java Persistence API to perform the database accessing and query to our LogIn table. However, because the Java Persistence API can only be implemented in a limited number of Java EE containers that provide the Resource Injection function, we cannot inject the Java persistence API into our normal Java help class file.Therefore, in this part, we have to use the Java runtime object method to perform database-related actions to check matched username and password from the LogIn table in our sample database. We can include these database related actions into this Java help class file.

Right click on our project JavaWebDBJSPSQL from the Projects window and select the New > Java Class item from the popup menu to open the New Java Class wizard. If you cannot find the Java Class item under the New menu item, go to Other item and select the Java item from the Categories list, and the Java Class item from the File Types list. Click on the Next button to open this wizard. On the opened wizard, enter LogInQuery into the Class Name field and select JavaWebDBJSPSQLPackage from the Package combo box, as shown in Figure 8.62. Click on the Finish button to create this help class file.

Before we can do the coding for this help class, we need first to create a dialog box in this project. This dialog box works as a message box to provide possible debug information during the project runs.

8.5.1.3 Create a Dialog Box as the Message Box

To create a new dialog box form window, perform the following operations:

1.Right click on our project JavaWebDBJSPSQL from the Projects window and select the New > Other item from the pop-up menu to open the New File wizard. Select the AWT GUI Forms from the Categories list and OK/Cancel Dialog Sample Form item from

the File Types list. Click on the Next button to open a new dialog box form.

Figure 8.62. The completed New Java Class wizard.

8.5 Build Java Web Project to Access SQL Server Database 631

Figure 8.63. The finished New OK/Cancel Dialog Form wizard.

Figure 8.64. The preview of the dialog box.

2.Enter MsgDialog into the Class Name field and select the JavaWebDBJSPSQLPackage from the Package field. Your finished New OK/Cancel Dialog Sample Form wizard should match one that is shown in Figure 8.63. Click on the Finish button to create this new dialog box.

3.A new Java dialog box class file MsgDialog.java is created and located under the

JavaWebDBJSPSQLPackage folder in the Projects window. Click on the Design button to open its dialog form window. Add a label to this dialog form window by dragging a Label control from the Palette window, exactly from the AWT subwindow, and placing it to the dialog form window.

4.Resize this label to an appropriate size, as shown in Figure 8.64. Right click on this label

and select the Change Variable Name item from the pop-up menu to open the Rename dialog. Enter MsgLabel into the New Name field and click on the OK button.

5. Go to the text property and remove the default text label1 for this label.

Now click on the Source button to open the code window for this dialog box, and we need to add some codes to this class to enable it to display some necessary messages as the project runs.

632 Chapter 8 Developing Java Web Applications to Access Databases

public MsgDialog(java.awt.Frame parent, boolean modal) { super(parent, modal);

initComponents();

this.setLocationRelativeTo(null);

}

public void setMessage(String msg){ MsgLabel.setText(msg);

}

Figure 8.65. The added codes to the MsgDialog.java class.

On the opened code window, add the codes that are highlighted in bold and shown in Figure 8.65.

The setLocationRelativeTo(null) instruction is used to set this dialog box at the center of the screen as the project runs. The method setMessage() is used to set up a user message by calling the setText() method.

Now we have finished creating and building our dialog box form, and let’s begin to do the coding for our help class file.

8.5.1.4 Develop the Codes for the Help Class File

Double click on this help class LogInQuery.java from the Projects window to open its code window. Perform the following operations to complete the coding process for this class:

1.Import the SQL Server related package and create the constructor of this class.

2.Build the codes for the checkLogIn() method to access and query the LogIn table.

3.Build the codes for the CloseDBConnection() method to close the connection to our sample database when this login query is complete.

Let’s do these one by one.

8.5.1.4.1 Import SQL Server Related Package and Create the Class Constructor Since we need to query our sample SQL Server database, therefore, we need to import the SQL Server-related package. The class constructor is used to build a valid connection to our sample database. The detailed codes are shown in Figure 8.66.

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

A.The JDBC SQL Server-related package is imported first since we need to use some JDBC classes defined in that package.

B.Some attributes or properties of this help class are defined first inside this class, which include two private String properties user_name and pass_word, a class-level connection variable con, and a dialog box that is used to display some debug information.

C.Inside the class constructor, a try….catch block is used to load the JDBC SQL Server driver, which is a type IV JDBC driver. Refer to Section 6.2.1.2.4 in Chapter 6 to get more detailed information about this driver name.

D.The catch block is used to collect any possible exceptions occurred during this driver loading process.

8.5 Build Java Web Project to Access SQL Server Database 633

package JavaWebDBJSPSQLPackage;

Aimport java.sql.*;

public class LogInQuery {

Bprivate String user_name = null; private String pass_word = null; static Connection con;

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

Ctry {

 

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

 

}

D

catch (Exception e) {

 

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

 

msgDlg.setVisible(true);

 

}

EString url = "jdbc:sqlserver://localhost\\SQL2008EXPRESS:5000;databaseName=CSE_DEPT;";

Ftry {

 

con = DriverManager.getConnection(url,"ybai","reback1956");

 

}

G

catch (SQLException e) {

 

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

 

msgDlg.setVisible(true);

 

e.printStackTrace();

 

}

 

}

 

………

Figure 8.66. The codes of the class constructor.

E.The JDBC SQL Server URL is assigned to the local variable url. Refer to Section 6.2.1.2.4 in Chapter 6 to get more detailed information about this URL.

F.The getConnection() method that is embedded in a try block is executed to establish this database connection.

G.The catch block is used to collect any possible exceptions occurred during this database connection process.

Now let’s build the codes for the checkLogIn() method to try to query the LogIn table to find a match username and password pair.

8.5.1.4.2 Build the Codes for the checkLogIn() Method The function of this method is to query the LogIn table in our sample database to try to find a matched username and password pair based on the username and password entered by the user from the LogIn.jsp page. A “Matched” string will be returned to the LogInQuery.jsp page if a matched username and password pair is found. Otherwise, an “Unmatched” string is returned. Based on this returned string, the LogInQuery.jsp will determine the next page to be opened. If a matched pair has been found, the Selection.jsp page will be displayed to allow users to select different information item to access and query different table in our sample database. Otherwise, an error message will be displayed to indicate that this login process has failed, since no matched login information can be found from our sample database.

In the opened code window of the help class LogInQuery.java, enter the codes that are shown in Figure 8.67 under the class constructor and make it the body of our checkLogIn() method.

634 Chapter 8 Developing Java Web Applications to Access Databases

public String checkLogIn(String uname, String pword) {

A String query = "SELECT user_name, pass_word FROM LogIn " + "WHERE user_name = ? AND pass_word = ?";

try{

BPreparedStatement pstmt = con.prepareStatement(query);

Cpstmt.setString(1, uname); pstmt.setString(2, pword);

DResultSet rs = pstmt.executeQuery();

Ewhile (rs.next()){

user_name = rs.getString(1); pass_word = rs.getString(2);

 

}

 

}

F

catch (SQLException e) {

 

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

 

msgDlg.setVisible(true);

 

}

G

if (user_name.equals(uname) && pass_word.equals(pword))

 

return "Matched";

H

else

 

return "Nomatched";

 

}

Figure 8.67. The codes for the checkLogIn() method.

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

A.The query string, which is a standard SQL statement, is created first with the actual column names as the query columns. The positional parameters are used for both username and password dynamic inputs.

B.Starting from a try block, the prepareStatement() method is called to create a PreparedStatement object pstmt.

C.The setter method is used to set two positional parameters in the positional order.

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

E.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. The retuned username and password are assigned to two properties, user_name and pass_word, respectively.

F.The catch block is used to collect any possible exceptions occurred during this database query process.

G.If a matched username/password pair is found, a “Matched” string will be returned to the LogInQuery.jsp page.

H.Otherwise, an “Unmatched” string is returned to indicate that this login query has failed.

Next, let’s build the codes for the CloseDBConnection() method.

8.5.1.4.3 Build the Codes for the CloseDBConnection() Method This method is necessary when a data query is finished and no more data actions are needed for a database application. A possible running error may be encountered if one did not disconnect the established connection to a target database and exit the project.

8.5 Build Java Web Project to Access SQL Server Database 635

 

public void CloseDBConnection()

 

{

A

try{

 

if (!con.isClosed())

 

con.close();

B

}catch (SQLException e) {

 

msgDlg.setMessage("Error in close the DB! " + e.getMessage());

 

msgDlg.setVisible(true);

 

}

 

}

 

 

Figure 8.68. The codes for the CloseDBConnection() method.

On the opened code window of the help class LogInQuery.java, enter the codes that are shown in Figure 8.68 under the checkLogIn() method to create our

CloseDBConnection() method.

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

A.A try block is used to handle this database disconnection function. First we need to check whether a valid connection object exists, which means that the database is still being connected. The isClosed() method is executed to do this checking. A false will be returned if a valid connection object exists, which means that the database is still being connected. In that case, the close() method is called to disconnect this connection.

B.The catch block is sued to collect any possible exceptions occurred during this disconnection process.

Now we have finished all coding development for this login process. Before we can build and run our Web application project to test the login function using the LogIn.jsp and help class files, we need to first add the JDBC SQL Server driver into our project.

8.5.1.5 Add the JDBC Driver for the SQL Server Database into the Project

To enable our Java Web application project to load and connect to our sample SQL Server

2008 database, CSE_DEPT, which we built in Chapter 2, we need to:

1.Download this driver from the site http://msdn.microsoft.com/data/jdbc/

2.Configure the TCP/IP protocol and setup for the SQL server

3.Set up a SQL Server database connection using NetBeans 6.8 IDE

4.Add the JDBC SQL Server driver into our Web application project

Refer to Section 6.2.1.2 in Chapter 6 to complete the top three steps. Now let’s perform the fourth step to add this JDBC driver into our project.

When we finished downloading this JDBC driver sqljdbc4.jar, the default location of this driver is at: C:\Program Files\Microsoft SQL Server JDBC Driver 2.0|sqljdbc_2.0|enu. To add this JDBC driver to our project, right click on our Web project JavaWebDBJSPSQL from the Projects window and select the Properties item from the pop-up menu. On the opened Project Properties dialog, select the Libraries item from the Categories list. Then click on the Add JAR/Folder button to open the Add JAR/Folder dialog, as shown in Figure 8.69.

636 Chapter 8 Developing Java Web Applications to Access Databases

Figure 8.69. The opened Add JAR/Folder dialog box.

Figure 8.70. The finished Project Properties dialog box.

Click on the drop-down arrow in the Look in combo box and browse to the location where our downloaded JDBC driver sqljdbc4.jar is located, which is C:\Program Files\ Microsoft SQL Server JDBC Driver 2.0|sqljdbc_2.0|enu. Then select this driver and click on the Open button. Your finished Project Properties dialog box should match one that is shown in Figure 8.70.

Click on the OK button to complete this JDBC driver adding process. Now we are ready to build and run our Web project to test the login function using the LogIn.jsp,

LogInQuery.jsp, nd the help class file LogInQuery.java.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]