Query Data from the Course Table Using JavaServer

Một phần của tài liệu practical database aprogramming with java (Trang 542 - 556)

JAVA RUNTIME OBJECTS METHOD

8.5 BUILD JAVA WEB PROJECT TO ACCESS SQL SERVER

8.5.6 Query Data from the Course Table Using JavaServer

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 data- base 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 fi eld 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 .

c08.indd 668

c08.indd 668 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM

www.traintelco.com

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 modifi cations to the copied codes in the CoursePage fi le:

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. Replace the <input name =CourseNameField ... > tag with the <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. Replace the <input name =EnrollmentField ... > tag with the <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 / >

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 modifi ed JSF page CoursePage.jsp is shown in Figure 8.95 . The modifi ed parts have been highlighted in bold.

Although these modifi cations look a little complex, in fact, they are very simple, and the reason we need to perform these modifi cations 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 defi ned in our Java bean class CourseBean . Let ’ s have a closer look at these modifi ed 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 redefi ne 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 defi ned 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 defi ned 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 , fi ve inputText tags are defi ned, 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 input- Text tags are: (1) the id attribute of each inputText tag must be identical with the name of an associated property defi ned in our Java bean class CourseBean for binding purpose;

and (2) the value attribute of each tag must be bound to an associated property defi ned in the Java bean CourseBean using the EL expression (#{ … }). After this binding, the content of each inputText fi eld 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 defi ne fi ve 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 defi ned in our Java bean class

c08.indd 670

c08.indd 670 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM

www.traintelco.com

Figure 8.95. The modifi ed codes for the JSF page CoursePage.jsp.

<%@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]>

<h:formid="CoursePage">

………

<h:selectOneListbox id="courseList" value="#{CourseBean.selectedItem}" size="5" >

<f:selectItems value="#{CourseBean.courseList}" />

</h:selectOneListbox>

………

<h:inputText id="courseName" value="#{CourseBean.courseName}" size="20" maxlength="60">

</h:inputText>

………

<h:inputText id="schedule" value="#{CourseBean.schedule}" size="20" maxlength="60">

</h:inputText>

………

<h:inputText id="classroom" value="#{CourseBean.classroom}" size="20" maxlength="20">

</h:inputText>

………

<h:inputText id="credit" value="#{CourseBean.credit}" size="20" maxlength="20">

</h:inputText>

………

<h:inputText id="enrollment" value="#{CourseBean.enrollment}" size="20" maxlength="20">

</h:inputText>

………

<h:commandButton id="Select" action="#{CourseBean.Select}" value="Select" />

………

<h:commandButton id="Details" action="#{CourseBean.Details}" value="Details" />

………

<h:commandButton id="Update" action="#{CourseBean.Update}" value="Update" />

………

<h:commandButton id="Delete" action="#{CourseBean.Delete}" value="Delete" />

………

<h:commandButton id="Back" action="#{CourseBean.Back}" value="Back" />

………

<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>

A B

C

D

E F

G

H I J K L M

CourseBean . In this way, we can bind the action attribute of each button to the associated method defi ned 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 defi ne and bind the facultyName fi eld 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 opera- tions and actions in this application. This JSF managed bean works as an intermediate - level 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 fi ve pieces of detailed course information based on the selected course_id from the CourseList box by the user, and display them in fi ve text fi elds 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 fi rst 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 fi rst 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. Enter CourseBean into the Class Name fi eld, and select the 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 fi le, enter the fi rst 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 defi ned in our View fi le, CoursePage.jsp

c08.indd 672

c08.indd 672 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM

www.traintelco.com

Figure 8.96. The fi rst part codes of the CourseBean class.

package JavaWebDBJSPSQLPackage;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.SessionScoped;

@ManagedBean(name="CourseBean")

@SessionScoped public class CourseBean {

private 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;

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);

public CourseBean() { }

public void setSelectedItem(String cid) { selectedItem = cid;

}

public String getSelectedItem() { return selectedItem;

}

public void setCourseList(List cid) { courseList = cid;

}

public List getCourseList() { return courseList;

}

public String getFacultyName() { return facultyName;

}

public void setFacultyName(String FacultyName) { this.facultyName = FacultyName;

}

public String getCourseID() { return courseID;

}

public void setCourseID(String CourseID) { this.courseID = CourseID;

}

public String getEnrollment() { return enrollment;

}

public void setEnrollment(String Enrollment) { this.enrollment = Enrollment;

}

public String getCredit() { return credit;

}

public void setCredit(String Credit) { this.credit = Credit;

}

public String getClassroom() { return classroom;

}

public void setClassroom(String Classroom) { this.classroom = Classroom;

} A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

fi le, 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 fi le later.

C. Starting from step C through step P , seven setter and getter methods are defi ned for seven properties we defi ned above. These methods are used to set or get each property defi ned 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 fi rst 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 defi ned, and they are used to set and get two properties, schedule and courseName , defi ned in this bean class.

E. The Select() method, which is bound to the action attribute of the Select button on the

CoursePage fi le, is defi ned 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, fi rst, 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 defi ned 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 fi le, is defi ned 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 fi ve pieces of detailed information based on the selected course_id from the

courseList box in the CoursePage as the project runs, and the returned fi ve pieces of course information will be displayed in fi ve inputText fi elds 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 fi rst 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 defi ned in our session bean class CourseFacade that will be built in the next section, will be called to retrieve fi ve pieces of detailed infor- mation 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 defi ned in our JSF managed bean class CourseBean.

c08.indd 674

c08.indd 674 7/20/2011 11:12:32 AM7/20/2011 11:12:32 AM

www.traintelco.com

Một phần của tài liệu practical database aprogramming with java (Trang 542 - 556)

Tải bản đầy đủ (PDF)

(791 trang)