Practical Database Programming With Java
.pdf
8.5 Build Java Web Project to Access SQL Server Database 667
Table 8.4. The deleted faculty record in the Faculty table
faculty_id |
faculty_name |
office |
phone |
college |
title |
||
B78880 |
Ying Bai |
MTC-211 |
750-378-1148 |
Florida Atlantic University |
Associate Professor |
ybai@college.edu |
Table 8.5. The deleted course records in the Course table
course_id |
course |
credit |
classroom |
schedule |
enrollment |
faculty_id |
|
CSC-132B |
Introduction to Programming |
3 |
TC-302 |
T-H: 1:00-2:25 PM |
21 |
B78880 |
|
CSC-234A |
Data Structure & Algorithms |
3 |
TC-302 |
M-W-F: 9:00-9:55 AM |
25 |
B78880 |
|
CSE-434 |
Advanced Electronics Systems |
3 |
TC-213 |
M-W-F: 1:00-1:55 PM |
26 |
B78880 |
|
CSE-438 |
Advd Logic & Microprocessor |
3 |
TC-213 |
M-W-F: 11:00-11:55 AM |
35 |
B78880 |
Table 8.6. The deleted login records in the LogIn table
user_name |
pass_word |
faculty_id |
student_id |
ybai |
reback |
B78880 |
|
Table 8.7. The deleted student course records in the StudentCourse table
s_course_id |
student_id |
course_id |
credit |
major |
1005 |
J77896 |
CSC-234A |
3 |
CS/IS |
1009 |
A78835 |
CSE-434 |
3 |
CE |
1014 |
A78835 |
CSE-438 |
3 |
CE |
1016 |
A97850 |
CSC-132B |
3 |
ISE |
1017 |
A97850 |
CSC-234A |
3 |
ISE |
|
|
|
|
|
deleted records, one needs to recover all of those deleted records related to the deleted faculty in those four tables. An easy way to do this recovery job is to use either the Microsoft SQL Server Management Studio Express or the Services window in NetBeans IDE. For your convenience, we show these original records in Tables 8.4–8.7 again, and you can add or insert them back to those four tables to complete this data recovery.
Another point to be noted is that you must recover the Faculty table first, and then you can recover other records in other tables, since the faculty_id is a primary key in the
Faculty table.
Next, let’s discuss how to access and manipulate data in the Course table in our sample SQL Server database using JavaServer Faces and Java beans with Java Persistence API techniques.
668 Chapter 8 Developing Java Web Applications to Access Databases
8.5.6 Query Data from the Course Table Using JavaServer Faces and Java Beans
In this section, we will discuss how to perform data actions against our SQL Server 2008 sample database using JavaServer Faces, Java Bean, and Java Persistence API techniques. Generally, this three-tier Web application is composed of the following components:
•Web container includes the JSP or JSF pages as a view or an interface to collect the user inputs and display the output or query results from database via the Web server.
•EJB contains a Session Bean that works as an intermediate-level processor between the Web container and the Java Persistence API to handle the business logics and data-related operations. For complicated Web applications, more than one Java bean may be used to handle the different jobs and play the different roles.
•Java Persistence API works (1) as an interface between the Java Bean and database server, and performs a mapping between a relational database and a collection of mapped entity classes, and (2) handle all data actions and data translations between Java beans and database server.
First, let’s modify the Course.jsp page to make it our JavaServer Face page.
8.5.6.1 Modify the Course Page to Make it JavaServer Face Page
As you know, there are some differences that exist between the JSP and JavaServer Faces pages; even the JavaServer Faces are built based on the JSP techniques. In fact, JavaServer Faces are built on JSP by inserting some JavaServer Faces tags into the JSP pages.
Perform the following operations to modify this Course page:
1.Launch the NetBeans IDE to open our project JavaWebDBJSPSQL.
2.Right click on our project folder and select the New > JSF Page item.
3.Enter CoursePage into the File Name field and check the JSP File radio button under the Options group.
4.Click on the Finish button to create a new JSF page.
5.On the created JSF page CoursePage, open the Palette window by going to
Window > Palette item.
6.Drag the JSF Form icon under the JSF tag in the Palette window and place it under the
<body> tag in the JSF page. A <h:form> ... </h:form> tag pair is created.
7.Open the Course.jsp page and copy the codes between the <form method=post action=“.\ CourseProcess.jsp”> tag and </form> tag, and paste them to the space between the <h:form> ... </h:form> tag pair in our new created JSF page
CoursePage.
8.In the top part of the Course.jsp page, copy the codes between the <style> (under the <title> tag) and the </head> (exclude the </head> tag), and paste these codes to the space between the <head> and </head> tag pair in our new created JSF page CoursePage (under the <title> tag).
9. In the Course.jsp page, copy the <![if !pub]> tag (just under the <div> tag) and paste it to space between the <body> and the <h:form> tag in our new created JSF page
CoursePage.
8.5 Build Java Web Project to Access SQL Server Database 669
10.In the Course.jsp page, copy the <![endif]> tag (just under the </form> tag) and paste it to space just below the </h:form> tag in our new created JSF page CoursePage.
To make it the JSF page, perform the following modifications to the copied codes in the CoursePage file:
1.Add an id attribute to the JSF Form tag <h:form> and make it as
<h:form id=″CoursePage″>.
2.Replace the <select name=CourseList ... ></select> tag pair with the
<h:selectOneListbox> tag, and the result of this replacement is:
<h:selectOneListbox id=″courseList″ value=″#{CourseBean. selectedItem}″ size=″5″ >
<f:selectItems value=″#{CourseBean.courseList}″ /> </h:selectOneListbox>
3.Replacethe<input name=CourseNameField ... >tagwiththe<h:inputText> tag, and the result of this replacement is:
<h:inputText id=″courseName″ value=″#{CourseBean.courseName}″ size=″20″ maxlength=″60″></h:inputText>
4.Replace the <input name=ScheduleField ... > tag with the <h:inputText> tag, and the result of this replacement is:
<h:inputText id=″schedule″ value=″#{CourseBean.schedule}″ size=″20″ maxlength=″60″></h:inputText>
5. Replace the <input name=ClassroomField ... > tag with the <h:inputText> tag, and the result of this replacement is:
<h:inputText id=″classroom″ value=″#{CourseBean.classroom}″ size=″20″ maxlength=″20″></h:inputText>
6.Replace the <input name=CreditField ... > tag with the <h:inputText> tag, and the result of this replacement is:
<h:inputText id=″credit″ value=″#{CourseBean.credit}″ size=″20″ maxlength=″20″></h:inputText>
7.Replacethe<input name=EnrollmentField ... >tagwiththe<h:inputText> tag, and the result of this replacement is:
<h:inputText id=″enrollment″ value=″#{CourseBean.enrollment}″ size=″20″ maxlength=″20″></h:inputText>
8. |
Replace |
the |
<input |
type=submit |
value=Select |
... > |
tag |
with |
the |
|
<h:commandButton> tag, and the result of this replacement is: |
|
|
|
|
||||
|
<h:commandButton id=″Select″ action=″#{CourseBean.Select}″ |
|
|||||||
|
value=″Select″ /> |
|
|
|
|
|
|
||
9. |
Replace |
the |
<input |
type=submit |
value=Insert |
... > |
tag |
with |
the |
|
<h:commandButton> tag, and the result of this replacement is: |
|
|
|
|
||||
|
<h:commandButton id=″Details″ action=″#{CourseBean.Details}″ |
|
|||||||
|
value=″Details″ /> |
|
|
|
|
|
|
||
10. |
Replace |
the |
<input |
type=submit |
value=Update |
... > |
tag |
with |
the |
<h:commandButton> tag, and the result of this replacement is:
<h:commandButton id=″Update″ action=″#{CourseBean.Update}″ value=″Update″ />
670 Chapter 8 |
Developing Java Web Applications to Access Databases |
|
|
|
||||
11. |
Replace |
the |
<input |
type=submit |
value=Delete ... > |
tag |
with |
the |
|
<h:commandButton> tag, and the result of this replacement is: |
|
|
|
||||
|
<h:commandButton id=″Delete″ action=″#{CourseBean.Delete}″ |
|
||||||
|
value=″Delete″ /> |
|
|
|
|
|
||
12. |
Replace |
the |
<input |
type=submit |
value=Back ... > |
tag |
with |
the |
|
<h:commandButton> tag, and the result of this replacement is: |
|
|
|
||||
|
<h:commandButton id=″Back″ action=″#{CourseBean.Back}″ |
|
|
|||||
|
value=″Back″ /> |
|
|
|
|
|
||
13. |
Replace |
the |
<input |
name=FacultyNameField ... > tag |
with |
the |
||
<h:inputText> tag, and the result of this replacement is:
<h:inputText id=″facultyName″ value=″#{CourseBean. facultyName}″ size=″20″ maxlength=″50″></h:inputText>
The modified JSF page CoursePage.jsp is shown in Figure 8.95. The modified parts have been highlighted in bold.
Although these modifications look a little complex, in fact, they are very simple, and the reason we need to perform these modifications is that we need to use Java bean class to handle the database-related operations, and to display the data action results by binding the value attribute of each inputText tag with the associated properties defined in our Java bean class CourseBean. Let’s have a closer look at these modified codes to see how they work.
A.An id=“CoursePage” attribute is added to the <h:form> tag to identify this form.
B.The <h:selectOneListbox> tag is used to redefine our CourseList box. In order to set up a binding relationship between this Listbox and a property in the Java bean CourseBean, the id of this Listbox, which is courseList, must be identical with a property courseList defined in our Java bean class CourseBean that will be created later.The value attribute of this courseList, which is the output of this courseList as the user clicks one
item from this Listbox to select one, is bound to a property named selectedItem defined in our Java bean class CourseBean. The value attribute of the <f:selectItems> tag is bound to a property named courseList in our Java bean class CourseBean, and all
queried course_id will be stored into this property and bound to the value attribute of this <f:selectItems> tag. The result of this binding is that all queried course_id will be displayed in this ListBox as the project runs. The point to be noted is that although both the id of the Listbox and the property has the same value, courseList, they are different in this application.
C.Starting from step C until step G, including steps D through to F, five inputText tags are defined, and they are used to display the detailed course information, such as the course name, schedule, classroom, credit, and enrollment, for a selected course_id from the courseList Listbox by the users as the project runs. Two points to be noted for these inputText tags are: (1) the id attribute of each inputText tag must be identical with the name of an associated property defined in our Java bean class CourseBean for binding purpose; and (2) the value attribute of each tag must be bound to an associated property defined in the Java bean CourseBean using the EL expression (#{…}). After this binding, the content of each inputText field will be equal to the value of the associated property in the Java bean, and, furthermore, they can be updated and displayed as the project runs.
H.From steps H through to L, the <h:commandButton> tags are used to define five buttons in this CoursePage. One point to be noted is that the action attribute of each button tag must be identical with an associated method defined in our Java bean class
8.5 Build Java Web Project to Access SQL Server Database 671
<%@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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>CoursePage Page</title>
<style>
……..
</head>
<body> <![if !pub]>
A<h:form id="CoursePage">
………
B<h:selectOneListbox id="courseList" value="#{CourseBean.selectedItem}" size="5" > <f:selectItems value="#{CourseBean.courseList}" />
</h:selectOneListbox>
………
C<h:inputText id="courseName" value="#{CourseBean.courseName}" size="20" maxlength="60">
</h:inputText>
………
D<h:inputText id="schedule" value="#{CourseBean.schedule}" size="20" maxlength="60"> </h:inputText>
………
E<h:inputText id="classroom" value="#{CourseBean.classroom}" size="20" maxlength="20"> </h:inputText>
………
F<h:inputText id="credit" value="#{CourseBean.credit}" size="20" maxlength="20"> </h:inputText>
………
G<h:inputText id="enrollment" value="#{CourseBean.enrollment}" size="20" maxlength="20"> </h:inputText>
………
H<h:commandButton id="Select" action="#{CourseBean.Select}" value="Select" />
………
I<h:commandButton id="Details" action="#{CourseBean.Details}" value="Details" />
………
J<h:commandButton id="Update" action="#{CourseBean.Update}" value="Update" />
………
K<h:commandButton id="Delete" action="#{CourseBean.Delete}" value="Delete" />
………
L<h:commandButton id="Back" action="#{CourseBean.Back}" value="Back" />
………
M<h:inputText id="facultyName" value="#{CourseBean.facultyName}" size="20" maxlength="50"> </h:inputText>
<![if !pub]></span><![endif]><![if !pub]> </h:form>
<![endif]>
</body>
</html>
</f:view>
Figure 8.95. The modified codes for the JSF page CoursePage.jsp.
672 Chapter 8 Developing Java Web Applications to Access Databases
CourseBean. In this way, we can bind the action attribute of each button to the associated method defined in our Java bean to enable that method to be triggered and executed as the button is clicked by the user.
M.Finally, another inputText tag is used to define and bind the facultyName field to an associated property named facultyName in our Java bean class CourseBean.
Next, let’s build our Java Bean class CourseBean.java to handle the database-related operations and business logics.
8.5.6.2 Build the JavaServer Face Managed Bean CourseBean
We need to build a JavaServer Faces managed bean to handle the database-related operations and actions in this application. This JSF managed bean works as an intermediatelevel process to handle business logics and database-related operations. In fact, the function of this bean is to:
•Query all courses, exactly course_id, from the Course table in our sample database based on the faculty name entered by the user, and display them in the CourseList box.
•Query five pieces of detailed course information based on the selected course_id from the CourseList box by the user, and display them in five text fields in the CoursePage.
As you know, there is no faculty_name column in our Course table, and the only selection criterion for the course is the faculty_id column. Therefore, we need to perform two queries for all course query operations: (1) query the faculty_id from the Faculty table based on the faculty name entered by the user, and (2) query all courses, exactly all course_id, from the Course table based on the faculty_id we queried in the first query.
Because of the coding complex in this section, we need to develop two Java bean classes to handle these queries: one is the JSF Managed Bean CourseBean that is used to control and coordinate all queries, and a Java Session Bean CourseFacade that is used to access our sample database to perform database related operations using Java Persistence API. Let’s first handle the JSF Managed Bean CourseBean.
Perform the following operations to create this JSF managed bean class:
1.Launch the NetBeans IDE and open our Web application project JavaWebDBJSPSQL.
2.Right click on our project JavaWebDBJSPSQL from the Projects window and select the New > Other item to open the New File wizard.
3.Select JavaServer Faces from the Categories list, and JSF Managed Bean from the
File Types list. Then click on the Next button.
4.EnterCourseBeanintotheClass Namefield,and selectthe JavaWebDBJSPSQLPackage from the Package combo box. Select the session from the Scope combo box and click on the Finish button.
On the opened CourseBean class file, enter the first part of the codes, which is shown in Figure 8.96, into this managed bean. The newly added codes have been highlighted in bold.
Let’s have a closer look at the codes in this part to see how they work.
A.First, seven properties, which should be bound to the associated attributes of tags in the CoursePage.jsp JSF page, are declared. The point to be noted is that the names of these properties must be identical with those of attributes defined in our View file,CoursePage.jsp
8.5 Build Java Web Project to Access SQL Server Database 673
package JavaWebDBJSPSQLPackage;
import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped;
@ManagedBean(name="CourseBean")
@SessionScoped
public class CourseBean {
Aprivate String courseName; private String schedule; private String classroom; private String credit; private String enrollment; private String courseID; private String facultyName; private List courseList;
private String selectedItem = null;
BMsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);
public CourseBean() {
}
Cpublic void setSelectedItem(String cid) {
selectedItem = cid;
}
D public String getSelectedItem() { return selectedItem;
}
E public void setCourseList(List cid) { courseList = cid;
}
F public List getCourseList() { return courseList;
}
G public String getFacultyName() { return facultyName;
}
H public void setFacultyName(String FacultyName) { this.facultyName = FacultyName;
}
I public String getCourseID() { return courseID;
}
J public void setCourseID(String CourseID) { this.courseID = CourseID;
}
K public String getEnrollment() { return enrollment;
}
L public void setEnrollment(String Enrollment) { this.enrollment = Enrollment;
}
M public String getCredit() { return credit;
}
N public void setCredit(String Credit) { this.credit = Credit;
}
O public String getClassroom() { return classroom;
}
P public void setClassroom(String Classroom) { this.classroom = Classroom;
}
Figure 8.96. The first part codes of the CourseBean class.
674 Chapter 8 Developing Java Web Applications to Access Databases
file, including the cases since Java is a case-sensitive language. Also the List collection courseList, which is bound to the value attribute of the <f:selectItems> tag, and the selectedItem, which is bound to the value attribute of the <h:selectOneListbox> tag, are declared here, too.
B.The msgDlg is a new instance of our customer-built dialog box, and this is used to display our testing and debug information when we test the codes in this file later.
C.Starting from step C through step P, seven setter and getter methods are defined for seven properties we defined above. These methods are used to set or get each property defined in this Java bean class as the project runs.
Now, let’s enter the second part of the codes into this Java bean class and locate them just below the first part codes, as show in Figure 8.97.
Let’s have a closer look at the codes in this part to see how they work.
A.From steps A through to D, another two-set setter and getter methods are defined, and they are used to set and get two properties, schedule and courseName, defined in this bean class.
E.The Select() method, which is bound to the action attribute of the Select button on the CoursePage file, is defined here. This method will be called and executed as the Select button in the CoursePage.jsp is clicked by the user as the project runs. To use the List collection, first, a new ArrayList instance is created.
F.A new List instance, cList, is also created, and it is used to hold the queried result from calling the getCourseID() method that is defined in the session bean class CourseFacade that will be built in the next section. This method will return a List of course_id taught by the selected faculty by the user from the CoursePage as the project runs.
G.A for loop is utilized to pick up each course_id from the cList instance and assign it to a new instance of SelectItem class, courseid, and add it into the courseList property using the Add() method. A point to be noted is that the returned course_id must be converted to an instance of the class interface SelectItem that is in the package javax.faces.model, and then it can be added into the List collection.
H.Because the returned value is not important for this application, a null is returned when this method is done.
I.The Details() method, which is bound to the action attribute of the Details button on the CoursePage file, is defined here. This method will be called and executed as the Details button in the CoursePage.jsp page is clicked by the user as the project runs. This method will return five pieces of detailed information based on the selected course_id from the courseList box in the CoursePage as the project runs, and the returned five pieces of course information will be displayed in five inputText fields in that page. The selected
course_id, which is stored in the selectedItem property in our JSF managed bean CourseBean and has been bound to the value attribute of the <h:selectOneListbox> tag in the CoursePage, will be checked first to make sure that a valid course_id has been selected by the user.
J.If the selectedItem property is non-null, which means that a valid course_id has been selected, the getCourseDetail() method defined in our session bean class CourseFacade that will be built in the next section, will be called to retrieve five pieces of detailed information for the selected course_id, and assign them to a List object courseDetail.
K.An enhanced for loop is used to retrieve the detailed course information from the query result list and assign them one by one to the associated properties defined in our JSF managed bean class CourseBean.
8.5 Build Java Web Project to Access SQL Server Database 675
A public String getSchedule() { return schedule;
}
B public void setSchedule(String Schedule) { this.schedule = Schedule;
}
C public String getCourseName() { return courseName;
}
D public void setCourseName(String CourseName) { this.courseName = CourseName;
}
Epublic String Select() { courseList = new ArrayList();
FList cList = courseFacade.getCourseID(getFacultyName());
Gfor (int i=0; i < cList.size(); i++) {
SelectItem courseid = new SelectItem(cList.get(i).toString()); courseList.add(courseid);
}
Hreturn null;
}
Ipublic Boolean Details() {
if (selectedItem != null) {
JList<Object[]> courseDetail = courseFacade.getCourseDetail(selectedItem);
Kfor (Object[] result:courseDetail){ courseName = (String)result[0]; schedule = (String)result[1]; classroom = (String)result[2]; credit = result[3].toString(); enrollment = result[4].toString();
|
} |
|
} |
L |
else { |
|
msgDlg.setMessage("the selected courseID is invalid!"); |
|
msgDlg.setVisible(true); |
|
} |
Mreturn null;
}
Npublic Boolean Update() { return null;
}
O public Boolean Delete() { return null;
}
Ppublic void Back() {
}
}
Figure 8.97. The second part codes of the CourseBean class.
L.If the selectedItem property contains a null value, which means that no valid course_id has been selected. A warning message is displayed for this situation using the msgDlg.
M.Since the returned value of this method is not important to us, therefore, a null is used.
N.Three other methods, Update(), Delete(), and Back(), which are bound to the action attributes of the associated buttons in the CoursePage file, are defined in steps N, O, and P in this Java bean class. We will develop the codes to execute the data updating and
676 Chapter 8 Developing Java Web Applications to Access Databases
package JavaWebDBJSPSQLPackage;
Aimport java.util.*;
import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped;
Bimport javax.faces.model.SelectItem;
………
Figure 8.98. The modified import statements in the CourseBean class.
deleting actions against our sample database later using these methods. The Back() method is used to return to the Selection.jsp page.
After finishing the code development for this bean, you may encounter some realtime compiling errors indicated with either red or blue underscored lines. One reason for that is that some packages are missed when you try to use some classes or interfaces in this code development process. To fix that, right click on this coding window and select the Fix Imports item from the pop-up menu to add required packages. An example is the List class that is located at the java.util package, and an import java.util.List statement should have been added into this bean after you had performed the Fix Imports operation. Since we need to use the ArrayList class that is also located at the java.util package, we need to modify this import statement to import java.util.*.
Another package you may need to use for this bean is the javax.faces.model, since we need to use the SelectItem component as an element in the <h:selectOneListbox> tag. Therefore, add another import statement to this bean, import javax.faces.model. SelectItem. Your finished import package block should match one that is shown in Figure 8.98. The modified import statements have been highlighted in bold.
Next, let’s develop and build our session bean class CourseFacade to handle database-related operations using the Java Persistence API.
8.5.6.3 Build the Session Bean for Entity Classes CourseFacade
The purpose of this session bean is to directly access our sample SQL Server 2008 database and perform all data queries and manipulations against our database via Java Persistence API. Recalled in Section 8.4.2, we have created an Entity class from our sample database and added it into this Web project. In this section, we will use that entity class to perform data actions against our sample database.
Perform the following operations to create a new session bean for entity classes CourseFacade:
1.Launch NetBeans IDE and open our Web project JavaWebDBJSPSQL.
2.Right click on our project JavaWebDBJSPSQL from the Projects window, and select New > Other to open the New File wizard.
3.Select Java EE from the Categories list and Session Beans For Entity Classes from
the |
File |
Types list, and click on the Next button. |
|||
4. On |
the |
opened New |
Session |
Beans for Entity Classes wizard |
|
shown |
in |
Figure 8.99, |
select two |
entity classes, JavaWebDBJSPSQL.Course and |
|
JavaWebDBJSPSQL.Faculty from the Available Entity Classes list and click
