Practical Database Programming With Java
.pdf
8.6 Build Java Web Project to Access and Manipulate Oracle Database 717
Figure 8.134. The finished Name and Location wizard.
package JavaWebDBJSPOracle;
import cse.entity.Faculty; import cse.util.HibernateUtil; import java.util.List;
import javax.ejb.Stateless; import org.hibernate.Query; import org.hibernate.Session;
@Stateless
public class FacultySessionBean {
Apublic Session session = null;
Bpublic FacultySessionBean() {
Cthis.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
Dpublic List QueryFaculty(String fname) {
EList<Faculty> facultyList = null;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
Fthis.session = HibernateUtil.getSessionFactory().getCurrentSession();
Gtry {
org.hibernate.Transaction tx = session.beginTransaction();
Query f = session.createQuery ("from Faculty as f where f.facultyName like '"+fname+"'");
HfacultyList = (List<Faculty>) f.list();
I} catch (Exception e) {
msgDlg.setMessage("Query is failed and no matched found!"); msgDlg.setVisible(true);
|
e.printStackTrace(); |
|
return null; |
|
} |
J |
return facultyList; |
|
} |
|
} |
Figure 8.135. The codes for the Java session bean class FacultySessionBean.
718 Chapter 8 Developing Java Web Applications to Access Databases
Let’s have a closer look at this piece of codes to see how it works.
A.Add a new Session object as a property to this class since we need to create a new session object to perform the data query using the Hibernate later.
B.Right click on any space of this code window and select the Insert Code item. Select the Constructor item to create a constructor for this class.
C.Inside the class constructor, call the getCurrentSession() method to obtain the current session object and assign it to our session property created at step A above.
D.Right click on any space inside this code window and select the Insert Code from the
pop-up menu. Then select the Add Business Method item to open the Add Business Method wizard. Enter QueryFaculty into the Name field and click on the Browse button to find the returning data type for this method. On the opened wizard, type List into the top field and select List (java.util) from the bottom list. Then click on the OK button, and the OK button again to create this new method. Add a String argument fname to this method.
E.Create two local variables for this method: facultyList, which is a java.util.List object, and a msgDlg, which is a JDialog object. The first is used to hold the returned queried result from the Faculty table, and the latter is used to display the debug information.
F.Before the query can be executed, the getCurrentSession() method is executed again to make sure that a valid session object has been opened.
G.A try…catch block is used to perform the faculty information query from our Faculty table. First, the beginTransaction() method is executed to create a new transaction object. Then the createQuery() method is called to perform this data query. A HQL statement works as an argument of this method and provides the query details.
H.The list() method is executed to perform this actual query operation. The queried result is returned and assigned to the local variable facultyList.
I.The catch block is used to track and detect any possible exception during this query operation, and display any error if any exception occurred.A null will be returned to the calling method if any exception occurred.
J.Finally, the queried result is returned to the calling method defined in our Java managed bean for further processing.
During the coding process, you may encounter some real-time compiling errors, which are indicated with some red underscores for the error sources. Most of these errors are related to the missed packages. To fix these errors, just right click on any space in this code window, and select the Fix Imports item to open the Fix All Imports wizard. The point to be noted is that you must select the correct packages for those real-time compiling error sources. For example, in this application, you need to select the following packages or classes for this file:
•org.hibernate.Query for the Query class
•org.hibernate.Session for the Session class
•java.util.List for the List collection class
Now we have completed the coding process for the faculty query operation with the Hibernate API. This piece of codes is only used for the faculty data query process, and the QueryFaculty() method will be called by our Java managed bean class FacultyMBean
8.6 Build Java Web Project to Access and Manipulate Oracle Database 719
to execute this data query operation. We will add more methods and codes to perform other data actions, such as data insertion, updating, and deleting, against our sample database later in the following sections.
Next, let’s build our Java managed bean class FacultyMBean.java to call some methods defined in the session bean to perform the actual data query and actions against our database.
8.6.8.3 Build the Java Managed Bean FacultyMBean to Manage Data Actions
The Java managed bean class FacultyMBean is used to manage and coordinate the faculty data queries and actions against our sample Oracle database. The session bean
FacultySessionBean is under the control of this managed bean to perform the actual data actions against our database using the Hibernate API. Perform the following operations to create our Java managed bean class FacultyMBean.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 FacultyMBean 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. Your finished Name and Location wizard should match one that is shown in Figure 8.136. Click on the Finish button to complete this managed bean creation process.
Figure 8.136. The finished Name and Location wizard.
720 Chapter 8 Developing Java Web Applications to Access Databases
Open the FacultyMBean.java class file and perform the following operations to create the first part of the codes of this file, which is shown in Figure 8.137.
Let’s have a closer look at this piece of codes to see how it works.
A.Right click on any space inside this code window and select the Insert Code item. Then choose the Call Enterprise Bean item to open the Call Enterprise Bean wizard. Expand the package JavaWebDBJSPOracle from the list and select our Java session bean FacultySessionBean by clicking on it, and click on the OK button. Immediately, you can find that an object @EJB has been injected into our managed bean, and a new instance of our Java session bean class, facultySessionBean, has also been added into this class.
B.Add ten new properties into this class and the names of these properties should be identical with those value attributes defined in the associated tags in the FacultyPage.jsp file.
For example, the facultyName property should be identical with the value attribute defined in the tag <h:inputText id=″facultyName″ value=″#{FacultyMBean. facultyName}″>. In this way, the property defined in the Java managed bean has been bound to the value attribute of the facultyName inputText tag or input field. The data type for the facultyImageName is static since we want to use this property as a global variable.
C.Right click on any space of this code window and select the Insert Code item. Select the Getter and Setter item to create 10 pairs of getter and setter methods for those 10 properties created in step B above. On the opened Generate Getters and Setters dialog box, check all 10 properties and click on the Generate button to create them.
D.Starting from step C until step R, eight pairs of getter and setter methods are created, and these methods are used to get and set the associated properties defined in this Java managed bean class.
Now let’s continue to create the second part of the codes for this managed bean, which is shown in Figure 8.138. Let’s have a closer look at this piece of codes to see how it works.
A.From steps A to D, another two pairs of getter and setter methods are defined, and they are used to pick up and set up the phone and the title properties in this managed bean class.
E.The Select() method is defined, and it is used to perform the data query operations from the Faculty table in our sample database using the Hibernate API. The point to be noted
is that the name of this method must be identical with the value defined in the action attribute in the <h:commandButton> tag in our Java JSF page FacultyPage.jsp. In this way, the Select button in that JSF page can be bound to this Select() method defined in this managed class.
F.Two local variables are created first inside this method. The first one is the List collection instance, and it is used to hold the returned query result from the Faculty table. The second is a JDialog instance, and it is used to display debug information when the project runs.
G.The QueryFaculty() method defined in our session bean FacultySessionBean.java is executed to perform the faculty information query action. The property facultyName works as an argument for this query function. The returned query result is assigned to the List instance facultyList.
H.If the queried result is non-null, which means that the query is successful, and the get(0) method is executed to pick up each column from the List object and assign each of them
8.6 Build Java Web Project to Access and Manipulate Oracle Database 721
package JavaWebDBJSPOracle;
public class FacultyMBean {
A@EJB
private FacultySessionBean facultySessionBean;
Bprivate String facultyImage;
private static String facultyImageName = null; private String facultyName;
private String facultyID; private String name; private String title; private String office; private String phone; private String college; private String email;
Cpublic String getCollege() {
return college;
}
D public void setCollege(String college) { this.college = college;
}
E public String getEmail() { return email;
}
F public void setEmail(String email) { this.email = email;
}
G public String getFacultyID() { return facultyID;
}
H public void setFacultyID(String facultyID) { this.facultyID = facultyID;
}
I public String getFacultyImage() { return facultyImage;
}
J public void setFacultyImage(String facultyImage) { this.facultyImage = facultyImage;
}
K public String getFacultyImageName() { return facultyImageName;
}
L public void setFacultyImageName(String facultyImageName) { this.facultyImageName = facultyImageName;
}
M public String getFacultyName() { return facultyName;
}
N public void setFacultyName(String facultyName) { this.facultyName = facultyName;
}
O public String getName() { return name;
}
P public void setName(String name) { this.name = name;
}
Q public String getOffice() { return office;
}
R public void setOffice(String office) { this.office = office;
}
………
Figure 8.137. The first part of the codes for the Java managed bean FacultyMBean.
722 Chapter 8 Developing Java Web Applications to Access Databases
A public String getPhone() { return phone;
}
B public void setPhone(String phone) { this.phone = phone;
}
C public String getTitle() { return title;
}
D public void setTitle(String title) { this.title = title;
}
/** Creates a new instance of FacultyMBean */ public FacultyMBean() {
}
Epublic String Select() {
FList<Faculty> facultyList = null;
MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
GfacultyList = facultySessionBean.QueryFaculty(facultyName);
Hif (facultyList != null) {
facultyID = facultyList.get(0).getFacultyId(); name = facultyList.get(0).getFacultyName(); office = facultyList.get(0).getOffice();
title = facultyList.get(0).getTitle(); phone = facultyList.get(0).getPhone(); college = facultyList.get(0).getCollege(); email = facultyList.get(0).getEmail();
|
} |
I |
else { |
|
msgDlg.setMessage("The faculty query is failed!"); |
|
msgDlg.setVisible(true); |
|
} |
J |
facultyImage = getFacultyImage(); |
K |
return null; |
|
} |
|
} |
Figure 8.138. The second part of the codes for the Java managed bean FacultyMBean.
to the associated property. Since only one row is returned, an index of 0 is used for the get() method.
I.Otherwise, this query has failed, and this exception information is displayed using the JDialog object.
J.The getter getFacultyImage() is executed to pick up the name of a matched faculty image
file and assign it to the facultyImage property. Since this property is bound to the value attribute of the <h:graphicImage> tag in our JSF page FacultyPage.jsp, the matched faculty image will be displayed in that JSF page.
K.Because the returning value of this method is useless for this application, a null is returned.
If you encountered some real-time compiling exceptions, for example, the List<Faculty> item has been underscored with a red line. In most cases, it is the
8.6 Build Java Web Project to Access and Manipulate Oracle Database 723
package or class missing-related errors. Just right click on any place inside this code window and select the Fix Imports item, then select the missed package or class such as java.util.List to fix them.
Now we can build and run our project to test this faculty information query operation.
8.6.8.4 Run the Project to Test the Faculty Information Query
Click on the Clean and Build Main Project button on the top to build our project. If everything is fine, right click on the FacultyPage.jsp from the Projects window and select the Compile File item from the pop-up menu to compile this page. Then right click on this FcaultyPage.jsp again and select the Run File item to run the project.
Enter the appropriate username and password, such as admin and reback, for our Web server GlassFish v3, and click on the OK button to continue. The point to be noted is that the username and password must be identical with those you created when downloading and installing the GlassFish v3 server in your machine.
On the opened FacultyPage.jsp page, enter a desired faculty name, such as Ying Bai, into the Faculty Name field. Then click on the Select button to query the related information for the selected faculty. Immediately, you can find the queried information is displayed in seven pieces of inputText fields, as shown in Figure 8.139.
Another way to test the project is to run a sequence of web pages we have built for this project, which starts from the LogInPage.jsp, and then SelectionPage.jsp and FacultyPage.jsp. To do that, we need to do some works to our SelectionBean.java class and the faces-config.xml file to set up the direction and page navigation rules between the SelectionPage and the FacultyPage.
Figure 8.139. The running result of the project.
724 Chapter 8 Developing Java Web Applications to Access Databases
8.6.8.5 Modify the faces-config.xml File to Run Project in a Web Pages Sequence
Recall that in Section 8.6.5, we built the SelectionBean.java file to handle the Web page navigations in this project. Refer to Figure 8.127; the OK() method in that class takes charge of directing the project to the correct next page based on the user’s selection from the selectionList box in the SelectionPage.jsp page. In addition to the OK() method, we also need to set up those navigation relationships between the LogInPage, SelectionPage, and ErrorPage using the faces-config.xml file in Section 8.6.7.
In this section, we also need to use this configuration file to set up another navigation rule between the SelectionPage and the FacultyPage. In fact, we need to set-up another two navigation rules, navigation between the SelectionPage and the CoursePage, and the navigation between the SelectionPage and the StudentPage. However, at this moment of the time, we have not built the CoursePage and the StudentPage; we can leave those jobs later when both pages have been built.
To set up a navigation rule between the SelectionPage and the FacultyPage, open the faces-config.xml file by expanding the Configuration Files node under our project from the Projects window and double clicking on this configuration file.
The opened PageFlow view of the faces-config.xml file is shown in Figure 8.140. Perform the following operations to set up this navigation rule:
1.Locate the starting point A from the SelectionPage.jsp page and drag to the ending point B at the FacultyPage.jsp page, as shown in Figure 8.140. Then double click on the label case1 and change it to FACULTY.
2.Locate the starting point C from the FacultyPage.jsp page and drag to the ending point D at the SelectionPage.jsp page, as shown in Figure 8.140. Then double click on the label case1 and change it to SELECTION.
A
D
B
C
Figure 8.140. The opened faces-config.xml file.
8.6 Build Java Web Project to Access and Manipulate Oracle Database 725
Figure 8.141. The finished faces-config.xml file.
Your finished faces-config.xml file should match one that is shown in Figure 8.141. One point to be noted is that the contents of labels between web pages must be
identical with those returned Strings defined in the OK() method in the SelectionBean. java file. Refer to Figure 8.127, you can find that the contents of labels in this facesconfig.xml file are identical with those Strings inside the OK() method. For example, the label from the page SelectionPage.jsp to the page FacultyPage.jsp is FACULTY in the configuration file. The string returned in the first if block in the OK() method is also “FACULTY”.
Now let’s run the project to test it with a sequence of web pages we have built in this project. To do that, you need to right click on the LogInPage.jsp from the Projects window and select the Run File item to run the project.
On the opened LogInPage, enter a suitable username and password, such as jhenry and test, and click on the LogIn button to browse to the SelectionPage.jsp. Select the
Faculty Information item from this page and click on the OK button to open the FacultyPage. Now you can test this faculty information query as we did above in the first test.
Our faculty information query using the Java JSF page and Java beans is successful! Next, let’s add some codes into this project to improve this query by displaying a selected faculty image.
8.6.8.6 Add Codes to the Project to Display a Selected Faculty Image
First, let’s modify the getter method, getFacultyImage(), in the FacultyMBean.java file to find and pick up a selected faculty image file, exactly a name of the faculty image file.
Open the Java managed bean class FacultyMBean.java and add the codes that are shown in Figure 8.142 into the getFacultyImage() method.
726 Chapter 8 Developing Java Web Applications to Access Databases
|
getFacultyImage() { |
A |
if (facultyImageName != null) { |
|
facultyImage = facultyImageName; |
|
facultyImageName = null; |
|
} |
B |
else |
|
facultyImage = getImage(facultyName); |
C |
return facultyImage; |
|
} |
|
|
Figure 8.142. The modified codes for the getter method.
public String getImage(String f_name) {
Aint maxNumber = 7; String fImage = null;
BString[] fname = { "Ying Bai", "Black Anderson", "Satish Bhalla", "Steve Johnson",
"Jenney King", "Alice Brown", "Debby Angles", "Jeff Henry"}; C String[] fimage = { "Bai.jpg", "Anderson.jpg", "Satish.jpg", "Johnson.jpg",
"King.jpg", "Brown.jpg", "Angles.jpg", "Henry.jpg"};
Dfor (int i=0; i<=maxNumber; i++) {
Eif (fname[i].equals(f_name)) { fImage = fimage[i];
break;
}
}
FfacultyImage = fImage;
Greturn fImage;
}
Figure 8.143. The codes for the method getImage().
Let’s have a closer look at these new added codes to see how they work.
A.First, we need to check whether the global variable facultyImageName contains a valid name of a new faculty image file. This situation will happen if the user wants to insert a new faculty record into the database with a new faculty image, and we will discuss this situation in Section 8.6.9 later. If this global variable did contain a valid name of a new faculty image file, we need to assign it to the property facultyImage and clean up this variable to make it ready for the next data insertion action.
B.If the facultyImageName did not contain any data, which means that this is not the data insertion action. The user defined method getImage() that will be built in the following part is executed to select and pick up a matched faculty image based on the faculty name, which works as an argument for this method.
C.The facultyImage property that contains a valid name of either a new or an existing faculty image file is returned. Another possibility is that this property may contain a null if a valid name of a faculty image file cannot be found.
Now let’s build the getImage() method. In the opened FacultyMBean.java file, create a new method named getImage() and enter codes that are shown in Figure 8.143 into this method.
