JAVA RUNTIME OBJECTS METHOD
8.6 BUILD JAVA WEB PROJECT TO ACCESS AND MANIPULATE ORACLE DATABASE
8.6.4 Query the LogIn Table Using JSF Pages and Java Beans
jsp page.
Figure 8.121. The fi nished Generation of Code wizard.
8.6.4.1 Modify the LogIn.jsp Page to Make it JSF Page
In this section, we want to modify the LogIn.jsp page we built in our Web project
JavaWebDBJSPSQL in Section 8.4.3.1 to make it our JSF page. You can fi nd this project from the folder DBProjects\Chapter 8 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).
Perform the following operations to create the JSF page based on the LogIn.jsp page:
1. Launch the NetBeans IDE and open our new project JavaWebDBJSPOracle . In the
Projects window, right click on the Web Pages folder and select the New > JSF Page item from the pop - up menu.
2. On the opened New JSF File wizard, enter LogInPage into the File Name fi eld and check the JSP File radio button under the Options panel. Then click on the Finish button to create this new JSF page.
3. On the opened new JSF page, open the Palette window by going to Window > Palette menu item. Then browse to the JSF Form that is located under the JSF group in the Palette window. Drag the JSF Form item from the Palette window and place it into the new JSF page, exactly between the <body > and </body > tag pair, as shown in Figure 8.122 . Delete the original default label <h1 ><h:outputText value =″Hello World! ″/ ></h1 >
tag from this page, since we do not need this label in this application.
Figure 8.122. The new added JSF Form.
c08.indd 698
c08.indd 698 7/20/2011 11:12:34 AM7/20/2011 11:12:34 AM
www.traintelco.com
4. Open the project JavaWebDBJSPSQL we built in Section 8.4.3.1 and the LogIn.jsp page.
Copy the codes between the <head > and </head > tag pair and paste them under the
<head > tag in our new JSF page LogInPage.jsp .
5. Copy the <![if !pub] > tag that is under the <div style … > tag and paste it to the new LogInPage.jsp page, just under the <body > tag.
6. Copy all codes between the <form > and </form > tag from the LogIn.jsp page and paste them into our new JSF page LogInpage.jsp , exactly between the <h:form > and
</h:form > tag in the LogInPage.jsp fi le.
7. Copy the <![endif] > tag from the LogIn.jsp fi le, which is located just under the
</form > tag, and paste it to our new JSF page LogInPage.jsp , exactly just under the
</h:form > tag.
Now perform the following modifi cations to the related attributes of tags to bind them to the associated properties or methods defi ned in the session bean class LogInBean.
java that will be built in the following section.
A. Modify the margin and style of the labels displayed in this page by changing the following margins and text indent that are located under the / * Style Definitions * / group below the <style > tag:
A. Change the text - indent from 0 pt to 45 pt. The result is text - indent:45 pt;
B. Change the margin - top from 0 pt to 28 pt. The result is margin - top:28 pt;
C. Change the margin - bottom from 0 pt to − 22 pt. The result is margin - bottom: - 22pt;
B. Add an new id attribute for the <h:form > tag and make this id equal to LogInPage . The modifi ed <h:form > tag now becomes <h:form id =″LogInPage ″> .
C. Replace the tag <input name =UserNameField maxlength =255 size =21 value =″″ type =text > with the tag <h:inputText id =″userName ″ value =″#{LogInBean.userName} ″></h:inputText > .
D. Replace the tag <input name =PassWordField maxlength =255 size =21 value =″″ type =text > with the tag <h:inputText id =″passWord ″ value =″#{LogInBean.passWord} ″></h:inputText > .
E. Replace the tag <input type =submit value =LogIn name =″LogInButton ″... > with the tag <h:commandButton id =″LogIn ″ action =″#{LogInBean.LogIn} ″ value =″LogIn ″ / > .
F. Replace the tag <input type =button value =Cancel name =″cancelButton ″ onclick =″self.close() ″> with the tag <h:commandButton id =″Cancel ″ value =″Cancel ″ onclick =″self.close() ″ / > .
Your fi nished LogInPage.jsp fi le should match one that is shown in Figure 8.123 . The modifi ed parts have been highlighted in bold.
Now you can test this page by building and running this page. Right click on this page from the Projects window and select the Compile File item, and then right click on this page again and select the Run File item to run this page.
Refer to Figure 8.123 ; in steps C and D, the value attributes of the username and password inputText tags are bound to the associated properties in the Java managed bean
LogInBean class that will be built in the next section. In step E, the action attribute of the LogIn commandButton tag is bound to the LogIn() method defi ned in the Java managed bean LogInBean . These binding relationships provide a convenient way to
enable the values of each tag in the JSF page to be updated immediately as the associated properties in the Java bean class are modifi ed.
Next, let ’ s build the Java managed bean class LogInBean.java to handle data queries and actions against our LogIn table in our sample database using the Hibernate interface.
8.6.4.2 Create and Build the Java Managed Bean LogInBean Class
The purpose of this managed bean is to perform business logics and all database - related actions against our sample database using the Hibernate component.
Perform the following operations to create our Java managed bean class
LogInBean.java :
Figure 8.123. The modifi ed codes for the LogInPage.jsp fi le.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<f:view>
<html>
<head>
………
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal {margin-right:0pt;
text-indent:45pt;
margin-top:28pt;
margin-bottom:-22pt;
text-align:left;
………
</head>
<body>
<![if !pub]>
<h:form id="LogInPage">
………
<h:inputText id="userName" value="#{LogInBean.userName}"></h:inputText>
………
<h:inputText id="passWord" value="#{LogInBean.passWord}"></h:inputText>
………
<h:commandButton id="LogIn" action="#{LogInBean.LogIn}" value="LogIn" />
………
<h:commandButton id="Cancel" value="Cancel" onclick="self.close()" />
………
<![if !pub]></span><![endif]><![if !pub]>
</h:form>
<![endif]>
</body>
</html>
</f:view>
A
B C D E F
c08.indd 700
c08.indd 700 7/20/2011 11:12:35 AM7/20/2011 11:12:35 AM
www.traintelco.com
1. Right click on our project JavaWebDBJSPOracle from the Projects window, and select the New > Other item to open the New File wizard.
2. Select JavaServer Faces from the Categories list and JSF Managed Bean from the File Types list, and then click on the Next button.
3. Enter LogInBean into the Class Name fi eld. Type JavaWebDBJSPOracle into the Package combo box, and select the session from the Scope combo box. Make sure to check the Add data to confi guration fi le checkbox since we need this confi guration fi le.
Your fi nished Name and Location wizard of this new managed bean is shown in Figure 8.124 . Click on the Finish button to complete this managed bean creation process.
Now let ’ s develop the codes for this managed bean class.
On the opened managed bean LogInBean.java , add two properties, userName and
passWord , as shown in step B in Figure 8.125 .
Then right click on any place inside this code window, select the Insert Code item and choose the Getter and Setter item to create two pairs of getter and setter methods for two properties we added in step B above. On the opened Generate Getters and Setters dialog box, check the userName and passWord two items and click on the
Generate button to create these getter and setter methods.
Enter the rest of the codes as shown in Figure 8.125 into this class. Let ’ s have a close look at this piece of codes to see how it works.
A. All necessary packages that contain classes and interfaces used in this class fi le are imported fi rst. In fact, you do not need to specially do these imports by manual. When you fi nished all coding jobs in this fi le, just right click on any space inside this code window and select the Fix Imports item from the pop - up menu to enable the NetBeans IDE to do that automatically. The point is that you need to select the correct packages to fi x these imports since some packages contain different classes with the same names.
Figure 8.124. The fi nished Name and Location wizard.
B. Two properties, userName and passWord , are created inside this bean and the names of these properties must be identical with those attributes of the tags defi ned in the JSF page
LogInPage.jsp in this project to make sure that they are bound together.
C. A new Hibernate Session instance is created and initialized with a null value. The point to be noted is that this session object is different with those session beans defi ned in the JSF pages, and it is used to perform the Hibernate data actions.
Figure 8.125. The codes for the Java managed bean LogInBean.
package cse.entity;
import cse.util.HibernateUtil;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hibernate.Query;
import org.hibernate.Session;
@ManagedBean(name="LogInBean")
@SessionScoped public class LogInBean {
private String userName;
private String passWord;
public Session session = null;
public LogInBean() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public String getPassWord() { return passWord;
}
public void setPassWord(String passWord) { this.passWord = passWord;
}
public String getUserName() { return userName;
}
public void setUserName(String userName) { this.userName = userName;
}
public String LogIn() { List<Login> loginList = null;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery ("from Login as lg where lg.userName like '"+userName+
"' and lg.passWord like '"+passWord+"'");
loginList = (List<Login>) q.list();
} catch (Exception e) {
msgDlg.setMessage("Query is failed and no matched found!");
msgDlg.setVisible(true);
e.printStackTrace();
}
String username = loginList.get(0).getUserName();
String password = loginList.get(0).getPassWord();
if (username.equals(userName) && password.equals(passWord)) return "SELECTION";
else
return "ERROR";
} } A
B C D E
F
G
H
I
J K L M
N O P
c08.indd 702
c08.indd 702 7/20/2011 11:12:35 AM7/20/2011 11:12:35 AM
www.traintelco.com
D. The getCurrentSession() method is executed to obtain the current Hibernate session object and assign it to the new created session instance in step C above.
E. Starting from step E through to step H , two pair of getter and setter methods are created and coded.
I. The LogIn() method, which is bound to the action attribute of the LogIn commandBut- ton in the JSF page LogInPage.jsp , is defi ned and coded here. Two local variables, a Login List and a JDialog instance, are created fi rst inside the method. The former is used to query the login data from the LogIn table, and the latter is used to provide the debug information when the project is tested later. The point to be noted is that you have to copy the
MsgDialog.java class fi le from our project JavaWebDBJSPSQL and paste it into this project, exactly into the cse.entity folder.
J. A try … catch block is used to perform the login data query using the Hibernate API. First, a Transaction instance is created to make it ready for the data actions.
K. Then, the createQuery() method is executed to create this login data query with a HQL statement. The point to be noted is that the names of columns used in this HQL query must be the Hibernate mapped names, not the original names defi ned in our LogIn table. Two dynamic parameters, userName and passWord , are properties defi ned in this class.
L. The query is performed by calling the list() method, and the result is returned and assigned to the Login List instance.
M. The catch block is used to track and collect any possible exception during this query and display the debug information using the MsgDialog .
N. The query result is further separate and assigned to two local string variables, username and password using the getUserName() and getPassWord() methods, respectively.
O. A comparison is performed between the properties of this class, userName and passWord, which are entered by the user from the JSF page LogInPage.jsp, and the query result. If a matching is found, a string “ SELECTION ” is returned to show the next page that is the
Selection.jsp that will be built later to allow users to continue the project to query other information.
P. Otherwise, the program will be directed to an ERROR page, which will be built later, and it is used to display the exception information for this login data query.
Next, we need to set up the navigation relationship between the LogInPage and other pages, such as the SelectionPage and ErrorPage , to enable the program to switch to the appropriate next page. This switching relationship is dependent on the execution result of the login process. The SelectionPage should be the next page if the login is successful;
otherwise, the ErrorPage should be displayed to indicate this situation.
In order to set up these relationships, we had better build the SelectionPage and the ErrorPage fi rst. Then, we can use the faces confi guration fi le, faces - confi g.xml , to set up these relationships.
8.6.5 Build the SelectionPage and the SelectionBean Class To save time and energy, we can modify the Selection.jsp page we built in our previous project JavaWebDBJSPSQL to make it our JSF page. Perform the following operations to do this modifi cation:
1. Right click on our current project JavaWebDBJSPOracle from the Projects window, and select New > JSF Page item from the pop up menu to open the New JSF File wizard.
2. Enter SelectionPage into the File Name fi eld and check the JSP File radio button.
Click on the Finish button to create this JSF page.
3. Remove the Hello World label from this page and go to the Window > Palette menu item to open the Palette window. Drag a JSF Form that is under the JSF group in the Palette window and place it into the space between the <body > and </body > tag.
4. Open the project JavaWebDBJSPSQL we built in Section 8.4.3.1 and the Selection.jsp page. Copy the codes between the <head > and </head > tag pair and paste them under the <head > tag in our new JSF page SelectionPage.jsp .
5. Copy the <![if !pub] > tag that is under the <div style … > tag and paste it to the new SelectionPage.jsp page, just under the <body > tag.
6. Copy all codes between the <form > and </form > tag from the Selection.jsp page and paste them into our new JSF page SelectionPage.jsp , exactly between the <h:form > and
</h:form > tag in the SelectionPage.jsp fi le.
7. Copy the <![endif] > tag from the Selection.jsp fi le, which is located just under the
</form > tag, and paste it to our new JSF page SelectionPage.jsp , exactly just under the
</h:form > tag.
Now perform the following modifi cations to the related attributes of the tags to bind them to the associated properties or methods defi ned in the session bean class
SelectionBean.java that will be built in the following section.
A. Modify the margin and style of the labels displayed in this page by changing the following margins and text indent that are located under the / * Style Definitions * / group below the <style > tag:
a. Change the margin - right from 0 pt to 90 pt. The result is margin - right:90pt;
B. Add an new id attribute for the <h:form > tag and make this id equal to SelectionPage . The modifi ed <h:form > tag now becomes <h:form id =″SelectionPage ″> . C. Replace the following tags
<select name =ListSelection size =6 v:shapes =″_x0000_s1027 ″>
<option selected value =″Faculty Information ″>Faculty Information </option >
<option value =″Course Information ″>Course Information </option >
<option value =″Student Information ″>Student Information
</option >
</select >
with the tags shown below:
<h:selectOneListbox id =″selectionList ″ value =″#{SelectionBean.
selectedItem} ″ size =″5 ″ >
<f:selectItem itemLabel =″Faculty Information ″ itemValue =″Faculty Information ″ / >
<f:selectItem itemLabel =″Course Information ″ itemValue =″Course Information ″ / >
c08.indd 704
c08.indd 704 7/20/2011 11:12:35 AM7/20/2011 11:12:35 AM
www.traintelco.com
<f:selectItem itemLabel =″Student Information ″ itemValue =″Student Information ″ / >
</h:selectOneListbox >
D. Replace the tag <input type =submit value =OK v:shapes =″_x0000_s1028 ″>
with the tag <h:commandButton id =″OK ″ action =″#{SelectionBean.OK} ″ value =″OK ″ / > .
E. Replace the tag <input type =button value =Exit onclick =″self.close() ″ v:shapes =… .. > with the tag <h:commandButton id =″Exit ″ value =″Exit ″ onclick =″self.close() ″ / > .
Your fi nished SelectionPage.jsp fi le should match one that is shown in Figure 8.126 . The modifi ed parts have been highlighted in bold.
Next, we need to create and build the Java managed bean class SelectionBean.java to handle the page navigation process to direct the program to the different page based on the users ’ selection on the SelectionPage .
The bean class SelectionBean is used to process some business - related operations for the SelectionPage . Perform the following operations to create our Java managed bean class SelectionBean.java :
1. Right click on our project JavaWebDBJSPOracle from the Projects window, and select the New > Other item to open the New File wizard.
2. Select JavaServer Faces from the Categories list and JSF Managed Bean from the File Types list, and then click on the Next button.
3. Enter SelectionBean into the Class Name fi eld. Select the JavaWebDBJSPOracle from the Package combo box, and select the session from the Scope combo box. Make sure to check the Add data to confi guration fi le checkbox since we need to use this confi gura- tion fi le to build the page navigation rules later in this application. Click on the Finish button to complete this managed bean creation process.
Open the SelectionBean.java class fi le and perform the following operations to create the codes that are shown in Figure 8.127 for this fi le.
Let ’ s have a closer look at this piece of codes to see how it works.
A. Some properties are created for this class, including a String variable selectedItem , which should be identical with the value attribute defi ned in the < h:selectOneListbox > tag in the SelectionPage.jsp fi le, and a JDialog instance msgDlg , which is used to display the debug and test information when the project runs.
B. The getter and setter methods are declared in steps B and C , respectively. To create these two methods, right click on any place inside this SelectionBean code window and select the Insert Code item from the pop - up menu. Then select the Getter and Setter item from the pop - up menu. On the opened wizard, check the selectedItem:String item and click on the Generate button.
D. Inside the OK() method, an if selection structure is used to identify the selected item from the selection list by the user. If the Faculty Information item has been selected, a “ FACULTY ” string is returned to indicate that the FacultyPage that will be developed in the following section will be opened to allow users to query the information related to faculty members in the sample CSE department. The point to be noted is that the name of this method should be identical with the action attribute defi ned in the < h:commandButton > tag in the SelectionPage.jsp page fi le to make sure that a binding