Practical Database Programming With Java
.pdf
8.6 Build Java Web Project to Access and Manipulate Oracle Database 697
Figure 8.121. The finished Generation of Code wizard.
4.Select hibernate.reveng.xml from the Hibernate Reverse Engineering File dropdown list, if it has not been selected.
5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.
6.Type cse.entity for the Package name. The finished New Hibernate Mapping Files and POJOs from Database wizard is shown in Figure 8.121.
7.Click on the Finish button to complete this creation process.
When clicking on the Finish button, the NetBeans IDE generates the POJO files with all the required fields in the src/java/cse/entity directory in the Files window. The NetBeans IDE also generates five Hibernate mapping files in the src/java/cse/ entity directory and adds the mapping entries to the hibernate.cfg.xml configuration file.
Now that we have the POJOs and necessary Hibernate-related files, we can start to create our web pages and perform data operations for our application. We will also create and then add some Hibernate Query Language (HQL) queries that query from our sample database to retrieve and display the desired data. In that process, we need to use the HQL editor to build and test the queries. First, let’s take care of the LogIn table query.
8.6.4 Query the LogIn Table Using JSF Pages and Java Beans
To save time and energy, we can modify the web pages we built in Sections 8.4.3.1–8.4.3.5 in this Chapter to make them as our JSF pages used in this project. We need to modify and change those pages from JSP to JavaServer Face pages. Let’s start from the LogIn. jsp page.
698 Chapter 8 Developing Java Web Applications to Access Databases
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 find 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 field 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.
8.6 Build Java Web Project to Access and Manipulate Oracle Database 699
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 file.
7.Copy the <![endif]> tag from the LogIn.jsp file, 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 modifications to the related attributes of tags to bind them to the associated properties or methods defined 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 modified <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 finished LogInPage.jsp file should match one that is shown in Figure 8.123. The modified 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 defined in the Java managed bean LogInBean. These binding relationships provide a convenient way to
700 Chapter 8 Developing Java Web Applications to Access Databases
<%@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;
Atext-indent:45pt; margin-top:28pt; margin-bottom:-22pt; text-align:left;
………
</head>
<body> <![if !pub]>
B<h:form id="LogInPage">
………
C<h:inputText id="userName" value="#{LogInBean.userName}"></h:inputText>
………
D<h:inputText id="passWord" value="#{LogInBean.passWord}"></h:inputText>
………
E<h:commandButton id="LogIn" action="#{LogInBean.LogIn}" value="LogIn" />
………
F<h:commandButton id="Cancel" value="Cancel" onclick="self.close()" />
………
<![if !pub]></span><![endif]><![if !pub]> </h:form>
<![endif]>
</body>
</html>
</f:view>
Figure 8.123. The modified codes for the LogInPage.jsp file.
enable the values of each tag in the JSF page to be updated immediately as the associated properties in the Java bean class are modified.
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:
8.6 Build Java Web Project to Access and Manipulate Oracle Database 701
Figure 8.124. The finished Name and Location wizard.
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 field. Type JavaWebDBJSPOracle into the Package combo box, and select the session from the Scope combo box. Make sure to check the Add data to configuration file checkbox since we need this configuration file. Your finished 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 file are imported first. In fact, you do not need to specially do these imports by manual. When you finished all coding jobs in this file, 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 fix these imports since some packages contain different classes with the same names.
702 Chapter 8 Developing Java Web Applications to Access Databases
package cse.entity;
Aimport 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 {
Bprivate String userName; private String passWord;
Cpublic Session session = null; public LogInBean() {
Dthis.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
Epublic String getPassWord() {
|
return passWord; |
|
} |
F |
public void setPassWord(String passWord) { |
|
this.passWord = passWord; |
|
} |
G |
public String getUserName() { |
|
return userName; |
|
} |
H |
public void setUserName(String userName) { |
|
this.userName = userName; |
|
} |
I |
public String LogIn() { |
|
List<Login> loginList = null; |
|
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true); |
try {
Jorg.hibernate.Transaction tx = session.beginTransaction();
KQuery q = session.createQuery ("from Login as lg where lg.userName like '"+userName+
"' and lg.passWord like '"+passWord+"'");
LloginList = (List<Login>) q.list();
M} catch (Exception e) {
msgDlg.setMessage("Query is failed and no matched found!"); msgDlg.setVisible(true);
e.printStackTrace();
}
NString username = loginList.get(0).getUserName(); String password = loginList.get(0).getPassWord();
Oif (username.equals(userName) && password.equals(passWord)) return "SELECTION";
Pelse
return "ERROR";
}
}
Figure 8.125. The codes for the Java managed bean LogInBean.
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 defined 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 defined in the JSF pages, and it is used to perform the Hibernate data actions.
8.6 Build Java Web Project to Access and Manipulate Oracle Database 703
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 commandButton in the JSF page LogInPage.jsp, is defined and coded here. Two local variables, a Login List and a JDialog instance, are created first 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 file 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 defined in our LogIn table. Two dynamic parameters, userName and passWord, are properties defined 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 first. Then, we can use the faces configuration file, faces-config.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 modification:
704Chapter 8 Developing Java Web Applications to Access Databases
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 field 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 file.
7.Copy the <![endif]> tag from the Selection.jsp file, 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 modifications to the related attributes of the tags to bind them to the associated properties or methods defined 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 modified <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″ />
8.6 Build Java Web Project to Access and Manipulate Oracle Database 705
<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 finished SelectionPage.jsp file should match one that is shown in Figure 8.126.
The modified 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 field. 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 configuration file checkbox since we need to use this configuration file 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 file and perform the following operations to create the codes that are shown in Figure 8.127 for this file.
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 defined in the <h:selectOneListbox> tag in the SelectionPage.jsp file, 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 defined in the <h:commandButton> tag in the SelectionPage.jsp page file to make sure that a binding
706 Chapter 8 Developing Java Web Applications to Access Databases
<%@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
A{margin-right:90pt; text-indent:0pt; margin-top:0pt; margin-bottom:0pt; text-align:left;
………
</head>
<body> <![if !pub]>
B<h:form id="SelectionPage">
………
C<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" /> <f:selectItem itemLabel="Student Information" itemValue="Student Information" />
</h:selectOneListbox>
………
D<h:commandButton id="OK" action="#{SelectionBean.OK}" value="OK" />
………
E<h:commandButton id="Exit" value="Exit" onclick="self.close()" />
………
<![if !pub]></span><![endif]><![if !pub]> </h:form>
<![endif]>
</body>
</html>
</f:view>
Figure 8.126. The codes for the SelectionPage.jsp file.
relationship has been built between this method and the action attribute of the OK button in the JSF page. To correctly direct the program to the next selected page, we need to build the associated navigation rules in the JSF configuration file faces-config.xml in the following sections.
E.If the Course Information item has been selected, a “COURSE” string is returned to indicate that the CoursePage that will be developed in the following section will be opened to allow users to query the course information related to the selected faculty member in the sample CSE department.
F.If the Student Information item has been selected, a “STUDENT” string is returned to indicate that the StudentPage that will be developed in the following section will be opened
