
Practical Database Programming With Java
.pdf
8.6 Build Java Web Project to Access and Manipulate Oracle Database 757
updating parameters stored in the nCourse[] array are java.lang.String. Therefore, it is necessary to perform a conversion between these two different data types. In steps H and I, we created two new instances of the BigDecimal class and used the constructor of this class to complete this conversion. This is an easy and convenient way to do this conversion.
J.The updating action is performed by executing the update() method for the session object with the Course entity object cs as the argument of this method.
K.The commit() method is executed to actually trigger and perform this data updating action.
L.The close() method is executed to close this opened session object when this data updating is complete.
M.Finally, a true is returned to the calling method to indicate the success of this data updating action.
N.The catch block is used to track and detect any exception during this data updating action. The exception information will be displayed using the JDialog instance msgDlg, and a false is returned if any exception occurred during this data updating process.
Now let’s build and run the project to test this course data updating function.
8.6.12.3 Run the Project to Test the Course Record Updating Action
Click on the Clean and Build Main Project button to build our project. If everything is fine, right click on our JSF page CoursePage.jsp from the Projects window and select the Run File item to run the project. Of course, you can run the project by starting from the LogIn page.
On the opened Course Page, type a desired faculty name, such as Ying Bai, into the Faculty Name field to perform a course information query for that faculty member. Then select the first course_id from the course listbox, which is CSC-132B, and click on the Details button to pick up the detailed information for this course. To update this course, just enter five pieces of updated course information shown in Figure 8.167 into
Figure 8.167. The updated course information.

758 Chapter 8 Developing Java Web Applications to Access Databases
the associated five fields as an updated course record. Then click on the Update button to try to update this course record against the Course table in our sample database.
To check and confirm this data updating action, you have two ways to go. The first and easiest way is to try to retrieve this updated course record. To do that, select another course_id, such as CSE-438, from the course listbox, and click on the Details button to query and display detailed information for that course. Then select the course CSC-132B from the course listbox and click on the Details button again to try to retrieve this updated course. You can find that this course has been successfully updated.
Another way to do this confirmation is to open the Course table from our sample Oracle database by performing the following operations:
A.Open the Services window and expand the Databases node.
B.Right click on our Oracle database URL: jdbc:oracle:thin:@localhost:1521:XE [CSE_DEPT on CSE_DEPT], and select the Connect item to connect to our database.
C.Expand our sample database CSE_DEPT and Tables.
D.Right click on the Course table and select the View Data item.
Your opened Course table is shown in Figure 8.168.
It is found that the course record with the course_id of CSC-132B, which is located at the sixth row on this table and has been highlighted in dark color, has been successfully updated with five pieces of updated course information. Our course data updating action is successful!
It is highly recommended to recover this updated course record in our database since we want to keep our database clean. To do this recovery, there are two ways to go.
The first and the easiest way is to use this JSF page CoursePage.jsp to perform another course updating action by entering the original course information that is shown below for the course_id CSC-132B and clicking on the Update button.
Figure 8.168. The updated course record.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 759
The second way is that you can directly do this recovery by opening the Course table in the Services window and modifying the updated row with the original course information for the course_id CSC-132B, which is listed below:
•Course: Introduction to Programming
•Credit: 3
•Classroom: MTC-302
•Schedule: T-H: 1:00–2:25 p.m.
•Enrollment: 21
•faculty_id: B78880
One point to be noted is that when you modify each column for the updated record, you must
1.Press the Enter key for each modified column to make it active.
2.Click on the Commit Record button on the top of this table to make the modification of the row effective after the entire row has been modified.
Next, let’s discuss how to delete an existing course record from our database using the JSF faces and Java beans with the help of the Hibernate APIs.
8.6.12.4 Add the Codes to the Java Managed Bean to Manage Data Deleting
Recall that in Section 8.5.6.1, we have bound this method to the action attribute of the <h:commandButton id=″Delete″> tag in our JSF page CoursePage.jsp. With this tag, the Delete() method in our managed bean has been bound to the action attribute of that tag, and it will be called and executed as soon as the user clicks the Delete button on our JSF page CoursePage.jsp as the project runs.
Open the code window of our managed bean CourseBean.java and add the codes that are shown in Figure 8.169 into this method.
Let’s have a closer look at this piece of newly added codes to see how it works.
A.A local variable delete is created and initialized first for this method. This is a boolean variable used to hold the running status of the DeleteCourse() method defined in the session bean class, and we will build this method in the next section.
B.The DeleteCourse() method defined in our session bean, which will be developed in the next section, is called to perform this course record deleting action. The argument passed
public Boolean Delete() {
Aboolean delete = false;
Bdelete = courseSessionBean.DeleteCourse(selectedItem);
Cif (!delete) {
msgDlg.setMessage("The course deleting is failed!"); msgDlg.setVisible(true);
}
D return null;
}
Figure 8.169. The codes for the method Delete().

760 Chapter 8 Developing Java Web Applications to Access Databases
into that method is a course_id that is stored in the selectedItem property, and will be deleted from our Course table. The running result of that method is returned and assigned to the local variable delete.
C.If the running result of the method DeleteCourse() is false, which means that the data deleting has failed, this situation is displayed by executing the setMessage() method in the msgDlg instance.
D.Otherwise, if a true returned, which means that this course data deleting is successful, a null is returned since this returning value is not important to this application.
Next, let’s develop the DeleteCourse() method in our session bean class to perform the course data deleting action using the Hibernate API.
8.6.12.5 Build the DeleteCourse() Method in the Session Bean to Perform Data Deleting
Open the code window for our session bean class CourseSessionBean.java and enter the codes shown in Figure 8.170 into this file to create a new method DeleteCourse() and its codes.
Let’s have a closer look at this piece of new codes to see how it works.
A.A new instance of the JDialog class msgDlg is created since we need to use it to display some debug information during the project running.
B.A try . . . catch block is used to perform this data deleting action. First, a new
SessionFactory object fact is created by executing the buildSessionFactory() method. Then, the session object is opened by executing the openSession() method.
C.A new Transaction object tx is created to help to perform this data deleting action.
public boolean DeleteCourse(String cid) {
AMsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
Btry {
SessionFactory fact = new Configuration().configure().buildSessionFactory(); session = fact.openSession();
Corg.hibernate.Transaction tx = session.beginTransaction();
Dif (!tx.isActive())
tx.begin();
ECourse cs = (Course)session.get(Course.class, cid);
Fsession.delete(cs);
Gtx.commit();
Hsession.close();
Ireturn true;
}
Jcatch(Exception e) { msgDlg.setMessage(e.getMessage()); msgDlg.setVisible(true);
Kreturn false;
}
}
Figure 8.170. The codes for the DeleteCourse() method in the session bean.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 761
D.If this new Transaction instance has not been active, the begin() method is executed to begin this transaction instance.
E.The get() method in the session class is first executed to perform a query to retrieve an existing course record from the Course table based on the courseID that is stored in the input argument cid. The first argument of this get() method is the class type Course, and the second argument is the courseID property. The returned query result is assigned to a new Course instance cs. A point to be noted is that the Course class must be casted before this method to make sure that the session object returns an appropriate object.
F.The deleting action is performed by executing the delete() method for the session object with the Course entity object cs as the argument of this method.
G.The commit() method is executed to actually trigger and perform this data deleting action.
H.The close() method is executed to close this opened session object when this data deleting is complete.
I.Finally, a true is returned to the calling method to indicate the success of this data deleting action.
J.The catch block is used to track and detect any exception during this data deleting action. The exception information will be displayed using the JDialog instance msgDlg.
K.A false is returned if any exception occurred during this data deleting process.
Now let’s build and run the project to test this course data deleting function. You can run the project in two ways: either run the single page CoursePage.jsp, or run the entire project starting from the LogInPage.jsp. Let’s first run the project in the first way.
8.6.12.6 Run the Project to Test the Course Record Deleting Action
Click on the Clean and Build Main Project button to build our project. If everything is fine, right click on our JSF page CoursePage.jsp from the Projects window and select the Run File item to run the project.
On the opened Course Page, first, we need to perform a course information query based on a desired faculty. Type a faculty name, such as Jenney King, into the Faculty Name field and click on the Select button to retrieve all courses (course_id) taught by that selected faculty.
To delete a course, select a course_id from the course listbox, such as CSC-233B, and click on the Delete button to try to delete it from the Course table in our sample database.
To check and confirm this data deleting action, open the Course table from our sample Oracle database in the NetBeans IDE by performing the following operations:
a.Open the Services window and expand the Databases node.
b.Right click on our Oracle database URL: jdbc:oracle:thin:@localhost:1521:XE [CSE_ DEPT on CSE_DEPT], and select the Connect item to connect to our database.
c.Expand our sample database CSE_DEPT and Tables.
d.Right click on the Course table and select the View Data item.
It can be found from the opened Course table that the course record with the course_id of CSC-233B has been successfully deleted from the Course table. Our data deleting action is successful!

762 Chapter 8 Developing Java Web Applications to Access Databases
It is highly recommended to recover this deleted course record in our database since we want to keep our database clean. You can directly do this recovery in the NetBeans IDE environment by opening the Course table in the Services window and insert a new row with the original course information for the faculty member Jenney King, which is listed below:
•course_id: CSC-233B
•course: Introduction to Algorithms
•credit: 3
•classroom: MTC-302
•schedule: M-W-F: 11:00-11:55 AM
•enrollment: 19
•faculty_id: K69880
The reason we selected the course CSC-233B as a deleting example is to make the data recovery process simpler. As you know, we have set up a cascaded deleting relationship between the parent table, Course table, and the child table, StudentCourse table, in our sample database in Chapter 2. If you want to delete any other course from the parent table Course,the same course with the identical course_id in the child table,StudentCourse, will also be deleted because of this cascaded deleting relationship. Since the course CSC233B is the only course that has not been selected by any student in the StudentCourse table, therefore, we only need to recover this course in the Course table when a recovery job is needed after this course has been deleted.
One point to be noted is that when you insert each column for a new record, you must
1.First click on the Insert Record button on the top of this table to open a new Insert Record wizard.
2.Enter the original course information shown above piece by piece to each column.
3.Press the Enter key at the end of each inserted column to make it active.
4.Click on the Commit Record button on the top of this table to make the insertion effective after the entire row has been inserted.
Your finished Insert Record wizard should match one that is shown in Figure 8.171. Click on the Add Row button to insert this row into the Course table to complete this data recovery.
The final coding job is for the Back button. The function of this coding is that the program should be directed to the SelectionPage.jsp page to enable users to make other actions when this button is clicked by the user.
8.6.12.7 Build the Codes for the Back Button Action Attribute in JSF Page
Recall that in Section 8.5.6.1, when we modify our JSF page CoursePage.jsp., we added one command tag shown below to that page:
<h:commandButton id=″Back″ action=″#{CourseBean.Back}″ value=″Back″ />

8.6 Build Java Web Project to Access and Manipulate Oracle Database 763
Figure 8.171. The finished Insert Record wizard.
public String Back() {
A return "SELECTION";
}
Figure 8.172. The codes for the Back() method.
With this tag, the Back() method in our managed bean has been bound to the action attribute of that tag, and this method will be called and executed as soon as the user clicks the Back button on our JSF page CoursePage.jsp as the project runs.
Recall that when we built the navigation relationship between the Selection and Course pages in Section 8.6.11.5, we have set up these navigation rules using the configuration file faces-config.xml. The relationship between the Course and the Selection pages has been determined by two rules, which is a round trip between these two pages.
Refer to that section to get a detailed and clear picture for this relationship.
The coding job is very simple for this Back button. Open the code window of our managed bean CourseBean.java and enter the codes shown in Figure 8.172 into the Back() method in this class.
As shown in step A in Figure 8.172, this coding is very simple, and a return “SELECTION” is executed as this Back button is clicked by the user. Refer to our Web configure file faces-config.xml, and you can find that the navigation rule from the Course page to the Selection page has been defined by a string “SELECTION”. The point to be noted is that the returned string in this Back() method must be exactly identical with that string defined in the configuration file to enable this navigation rule effective.
Now you can run the project to test the function of this Back button on the
CoursePage.jsp page.
At this point, we have finished all coding developments for this project. A complete Java Web application project using the Oracle database, JavaWebDBJSPOracle, can be found from the folder DBProjects\Chapter 8 that is located at the Wiley ftp site (refer

764 Chapter 8 Developing Java Web Applications to Access Databases
to Figure 1.2 in Chapter 1). You can download this project and test it in your computer if you like. Also, in order to make it easy and convenient to readers, we have collected all JSP and JSF pages, such as LogInPage.jsp, SelectionPage.jsp, FacultyPage.jsp and
CoursePage.jsp, and save them in a folder JSP Files that is located at the same ftp site. You can directly copy and use those pages in your projects.
8.7 CHAPTER SUMMARY
Most key techniques and knowledge in Java Web database programming are fully discussed and analyzed in this chapter with real project examples. The most popular and important techniques in Java Web database programming, such as JSP, JSF, EJB, and Java Persistence API, including the persistence and Hibernate APIs, are introduced and discussed in details in different sections in this chapter.
Starting from an introduction to the fundamental Java Web server Servlets and HTML web pages, a comprehensive historical review about Java Web application development and implementations are provided with some example codes. Then an introduction about the development of JSP and Java help classes to improve the Java Web database applications are given with some pieces of coding examples. The use of Java Persistence APIs and JSP implicit object session for Java Web applications are discussed with a few examples.
To effectively improve and enhance the efficiency and quality of Java Web database applications, the Java core techniques, Java beans, and Java enterprise edition (Java EE 6), are discussed and analyzed in details with a few of coding examples.
Following a quick introduction to the Java EE Web application models, two actual Java Web database projects are introduced and discussed in detail. The first project JavaWebDBJSPSQL, which is built based on the different techniques listed above, is used to access and manipulate the SQL Server 2008 database with the help of runtime object method and Persistence APIs. Four popular web pages, LogInPage.jsp, SelectionPage. jsp, FacultyPage.jsp, and CoursePage.jsp, which work as Web views, are built and developed with JSP techniques. The Glassfish v3 that works as a Web server, and the Java help classes and Java beans that work as models, are developed and implemented to provide users a global and detailed picture in the process of Java Web database application building and development.
The second project JavaWebDBJSPOracle, which is built based on the JSF pages and Java EJB techniques, is used to access and manipulate the Oracle database with the help of Hibernate APIs techniques. The binding relationships between each attribute of tags in the JSF pages and the associated property in the Java bean class are built and illustrated in details with actual example codes and step-by-step explanations in the coding process.
Some important techniques and points in developing and building a successful Web database application are emphasized and highlighted as below:
•Different data actions are performed and illustrated by using the coding process and line- by-line explanations, which include the data query, data insertion, data updating, and deleting.
•The Web project structure and navigation process are developed with the help of the Web configuration file, faces-config.xml, with actual examples and step-by-step illustrations.

Homework 765
•The relationships between the Java managed beans and the Java session beans are fully discussed and analyzed using the actual example codes and line-by-line explanations.
•The mapping relationships between each attribute in the tags on our JSF pages and the associated property in the Java managed beans are explicitly illustrated with the real coding process.
After finishing this chapter, readers can have a solid understanding, a clear and a full picture about the Java Web database application, including the Web structures, components, navigation, and mapping relationships between different objects, as well as the connections among those components.
It hard to find a similar book that contains so much details and so clear illustrations on these topics about the Java Web applications in the current market.
HOMEWORK
I. True/False Selections
____1. When a Servlet is created, the init() method is called to do the initialization jobs for the Web server.
____2. When a request is received by the Servlet, it creates two objects: request and response. Then the Servlet sends these two objects to the service() method, in which these two objects are further to be processed.
____3. The conventional Web applications are built with a Servlet as a Web container and JSF pages as Web clients.
____4. Unlike a Common Gateway Interface (CGI), a Servlet can be used to create dynamic web pages during the server–client communication processes.
____5. To interface to the client to get user’s data, most of the time, the Web server calls the getParameter() method that belongs to the request object to do this job.
____6. The so-called implicit objects in JSP are objects that are automatically available in JSP because they are automatically instantiated as the project runs.
____7. Among those implicit objects, the request, response, and session are the most popular objects, and are often used in the interfacing between clients and servers.
____8. To use a Java bean, the JSP provide three basic tags for working with beans,
<jsp:useBean id=″bean name″ class=″bean class″ scope = ″page|request |session|application″/>
____9. To embed any Java codes into a HTML page, the JSP directive <%@ page /> must be used.
___10. The navigation from one page to another can be done in two ways. One way is to directly use the codes by writing the JSP tag such as <jsp:forward /> or the HTML hyperlink in the JSF file. Another way that is provided by JSF is to use the application configuration resource file faces-config.xml to build these navigation rules.
II. Multiple Choices
1.The <from-view-id> tag is used to define a navigation ______________.
a.Source
b.Terminal

766Chapter 8 Developing Java Web Applications to Access Databases
c.Destination
d.None of above
2.To bind a Java bean’s property to an associated attribute of a tag in the JSF page, one needs to use the ________________.
a.Expression language (EL) with the syntax #(managedbean.property)
b.Expression language (EL) with the syntax #{managedbean.property}
c.Expression language (EL) with the syntax #[managedbean.property]
d.Expression language (EL) with the syntax ${managedbean.property}
3.A typical Java bean class should contain __________________.
a.All properties
b.All properties, setter methods
c.All properties, setter and getter methods
d.All properties, setter and getter methods, as well as user-defined methods
4.Java beans need to be configured in the Web configuration file faces-config.xml so that the implementation can automatically create a new _________ of the beans as needed.
a.Statement
b.Method
c.Instance
d.Project
5.Before you can use a Servlet such as FacesServlet in the server side from a Web browser, you need to map the FacesServlet to a path in your deployment descriptor file ________.
a.Web pages
b.WEB INF file
c.Web configuration file
d.web.xml
6.To separate the presentations and business logics, we can use ________ pages to present our GUI and the ___________ to store our data to perform business-related logics.
a.HTML, Java help class
b.XML, JSF pages
c.JSP, Java beans
d.JSF, JSP pages
7.All JSF tag components are represented by a tree of components whose root is the UIViewRoot, which is represented by the _________ tag. All JSF component tags must be enclosed in this
_________ tag.
a.UIComponent
b.UITree
c.<h:form>
d.<f:view>
8.A JSP form, which is submitted to the Web server when a button is clicked, is represented by the _________ tag. The tags representing the form components, such as textfields and buttons, must be nested inside this tag.
a.<f:form>
b.<h:form>
c.<h:view>
d.<f:view>