JAVA RUNTIME OBJECTS METHOD
8.5 BUILD JAVA WEB PROJECT TO ACCESS SQL SERVER
8.5.1 Access and Query the LogIn Table Using JSP and Help
In Section 8.4.1 , we have created a new Java Web application project, JavaWebDBJSPSQL , and added the entity class fi les into this new project. Now we will use this project to build
c08.indd 626
c08.indd 626 7/20/2011 11:12:29 AM7/20/2011 11:12:29 AM
www.traintelco.com
our database application to perform the data actions against our sample SQL Server database.
First, let ’ s add all fi ve 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 fi ve web pages;
in this application, it is C:\Temp . Copy all fi ve 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 fi nd that all fi ve web pages have been added into this project. Select all of these fi ve pages using the Shift key, right click on these fi ve 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 fi ve Web Pages to this Web Pages folder.
Next we need to do a little modifi cation to our LogIn.jsp fi le and break this fi le into two JSP fi les: LogIn.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 these opera- tions clear and easy.
8.5.1.1 Modify the LogIn.jsp Page and Create LogInQuery.jsp File
Now let ’ s fi rst modify the LogIn.jsp page by double clicking on the LogIn.jsp to open it and perform the following modifi cations to this page. The modifi ed parts have been high- lighted in bold and are shown in Figure 8.60 .
Let ’ s have a closer look at these modifi cations to see how they work.
A. The fi rst modifi cation 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 coor- dinate relationship. If a button is defi ned as a submit button by its type attribute, 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 database - related processing and business logics. The .\ symbol is used to indicate that our next JSP fi le 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 modifi cation is to add a name attribute to the LogIn button in order for it to be identifi ed in the server side later.
C. The third modifi cation 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 modifi cations 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.
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 fi nd 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 fi eld in the opened New JSP File wizard and keep all other default settings unchanged. Then click on the Finish button to create this JSP fi le. 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 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.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 pass- word, is assigned to two local string variables u_name and p_word , respectively.
Figure 8.60. The modifi cations to the LogIn.jsp page.
<html xmlns:v="urn:schemas-microsoft-com:vml"
………
<body style='margin:0'>
<div style='position:absolute;width:10.-2040in;height:1.-1423in'>
<![if !pub]>
<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">
………
<input type=submit value=LogIn name="LogInButton" v:shapes="_x0000_s1030">
<input type=button value=Cancel name="cancelButton" onclick="self.close()" v:shapes="_x0000_s1031">
………
</form>
</body>
</html>
A
B C
c08.indd 628
c08.indd 628 7/20/2011 11:12:29 AM7/20/2011 11:12:29 AM
www.traintelco.com
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 .
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 defi ned 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 fi le LogInQuery.java to perform JDBC - and database - related operations and actions.
8.5.1.2 Create the Java Help Class File LogInQuery.java
The purpose of this help class fi le 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 confi rming a pair of matched username and password located
Figure 8.61. The codes for the LogInQuery.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("UserNameField");
String p_word = request.getParameter("PassWordField");
String result = lquery.checkLogIn(u_name, p_word);
if (result.equals("Matched")) nextPage = "Selection.jsp";
else
out.println("LogIn is failed");
lquery.CloseDBConnection();
%>
<jsp:forward page = "<%=nextPage%>" />
</body>
</html>
A B C D E F G H
at a Java help class fi le, 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 access- ing 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 fi le. 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 fi le.
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 fi nd 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 fi eld and select JavaWebDBJSPSQLPackage from the Package combo box, as shown in Figure 8.62 . Click on the Finish button to create this help class fi le.
Before we can do the coding for this help class, we need fi rst to create a dialog box in this project. This dialog box works as a message box to provide possible debug infor- mation 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.
c08.indd 630
c08.indd 630 7/20/2011 11:12:29 AM7/20/2011 11:12:29 AM
www.traintelco.com
2. Enter MsgDialog into the Class Name fi eld and select the JavaWebDBJSPSQLPackage from the Package fi eld. Your fi nished 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 fi le 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 fi eld 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.
Figure 8.63. The fi nished New OK/Cancel Dialog Form wizard.
Figure 8.64. The preview of the dialog box.
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 fi nished creating and building our dialog box form, and let ’ s begin to do the coding for our help class fi le.
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 fi rst since we need to use some JDBC classes defi ned in that package.
B. Some attributes or properties of this help class are defi ned fi rst 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.
Figure 8.65. The added codes to the MsgDialog.java class.
public MsgDialog(java.awt.Frame parent, boolean modal) { super(parent, modal);
initComponents();
this.setLocationRelativeTo(null);
}
public void setMessage(String msg){
MsgLabel.setText(msg);
}
c08.indd 632
c08.indd 632 7/20/2011 11:12:30 AM7/20/2011 11:12:30 AM
www.traintelco.com
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 fi nd 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 fi nd a matched user- name 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 check- LogIn() method.
Figure 8.66. The codes of the class constructor.
package JavaWebDBJSPSQLPackage;
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("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();
} } ………
A B
C D
E F G
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 fi rst 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 fi nished and no more data actions are needed for a data- base application. A possible running error may be encountered if one did not disconnect the established connection to a target database and exit the project.
Figure 8.67. The codes for the checkLogIn() method.
public String checkLogIn(String uname, String pword) {
String query = "SELECT user_name, pass_word FROM LogIn " + "WHERE user_name = ? AND pass_word = ?";
try{
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, uname);
pstmt.setString(2, pword);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
user_name = rs.getString(1);
pass_word = rs.getString(2);
} }
catch (SQLException e) {
msgDlg.setMessage("Error in Statement! " + e.getMessage());
msgDlg.setVisible(true);
}
if (user_name.equals(uname) && pass_word.equals(pword)) return "Matched";
else
return "Nomatched";
} A
B C D E
F
G H
c08.indd 634
c08.indd 634 7/20/2011 11:12:30 AM7/20/2011 11:12:30 AM
www.traintelco.com