Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
790
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

8.6 Build Java Web Project to Access and Manipulate Oracle Database 727

Let’s have a closer look at this new method to see how it works.

A.Two local variables, maxNumber and fImage, are created first. The first one is used to define the maximum number of faculty members and associated faculty image files, and the second is used to hold the matched faculty image file’s name.

B.A string array fname is created with all seven faculty members involved.

C.Another string variable fimage is declared with all seven matched faculty image file’s names involved in this array. One point to be noted is that the orders in both array must be identical, which means that each faculty member in the fname array must be matched to a faculty image file’s name fimage.

D.A for loop is used to scan all seven faculty members’ names to try to find a matched faculty name with the input argument f_name.

E.If a matched faculty name has been found, the associated faculty image file’s name is assigned to the local variable fImage, and the loop is terminated.

F.The matched faculty image file’s name is assigned to the facultyImage property.

G.The matched faculty image file’s name is returned.

Now we can build and run the project in a Web sequence to fetch the desired faculty information from the Faculty table in our sample database.

8.6.8.7 Run the Entire Project to Test the Faculty Information Query

Before we can run the project to test its function, first we must copy all faculty and student image files and paste them to the Web Pages node in our project. Perform the following operations to perform this copy and paste works:

1.Find all faculty and students’ image files, which are located at the folder Images at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

2.Copy all image files from that location and paste them under the Web Pages node in our project folder JavaWebDBJSPOracle.

Click on the Clean and Build Main Project button on the top to build our project. If everything is fine, right click on the LogInPage.jsp from the Projects window and select the Run File item to run the project.

Enter the appropriate username and password, such as admin and reback, to our Web server, 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.

As the LogIn page opened, enter the desired username and password, such as jhenry and test, and click on the LogIn button. On the opened Selection page, select the Faculty Information item and click on the OK button to open the Faculty page.

To query a desired faculty record from the Faculty table in our sample Oracle database, enter a desired faculty name, such as Ying Bai, into the Faculty Name field, and click on the Select button to perform this query. Immediately, you can find that queried information for the selected faculty, and a matched faculty image are displayed in this page, as shown in Figure 8.144.

728 Chapter 8 Developing Java Web Applications to Access Databases

Figure 8.144. The running result of the project.

You can try to enter different faculty names, such as Jenney King and Jeff Henry, to query other faculty information. Click on the Close button that is on the upper-right corner of this page to close our project.

Our project for faculty information query is successful!

Next, let’s discuss how to insert a new faculty record into our sample database using JavaServer Faces and Java beans.

8.6.9 Insert New Records to the Faculty Table Using JavaServer Faces and Java Beans

As we did for the faculty information query action in the last section, we can divide this new faculty insertion action into two Java beans: the Java managed bean FacultyMBean. java that is used to manage and control the data insertion, and the session bean FacultySessionBean.java that is used to perform the actual data insertion actions.

First, let’s build the codes for the managed bean to manage this data insertion action.

8.6.9.1 Add the Codes to the Java Managed Bean to Manage Data Insertions

To begin this coding process, let’s first add a new method Insert() into our managed bean FacultyMBean.java and bind it to the action attribute of the <h:commandButton id=″Insert″> tag in our JSF page FacultyPage.jsp.

Open the code window of our managed bean FacultyMBean.java and add a new method Insert() into that file with the codes that are shown in Figure 8.145.

Recall that in Section 8.6.8.1, when we modified our JSF page FacultyPage.jsp file, we added one command tag shown below to that page:

<h:commandButton id=″Insert″ action=″#{FacultyMBean.Insert}″ value=″Insert″ />

8.6 Build Java Web Project to Access and Manipulate Oracle Database 729

public String Insert() {

Aboolean insert = false;

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true); String[] fInsert = {facultyID, name, office, phone, college, title, email};

Bif (facultyImageName != null)

facultyImage = facultyImageName;

Cinsert = facultySessionBean.InsertFaculty(fInsert);

Dif (!insert) {

msgDlg.setMessage("The faculty insertion is failed!"); msgDlg.setVisible(true);

}

E return null;

}

Figure 8.145. The codes for the new added method Insert().

With this tag, the Insert() method we just added into 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 Insert button on our JSF page FacultyPage.jsp as the project runs.

Let’s have a closer look at this piece of new added codes to see how it works.

A.Some local variables are created first for this method. The insert is a boolean variable used to hold the running status of the InsertFaculty() method defined in the session bean class, and we will build this method in the next section. The msgDlg is a JDialog instance used to display the debug or exception information as the project runs. The fInsert[] is a string array used to hold seven pieces of new faculty information to be inserted into the Faculty table in our sample database.The point to be noted is that we used seven properties defined

in this managed bean as seven pieces of new faculty information, since those properties have been bound to the associated value attributes of the <h:inputText> tags in our JSF page FacultyPage.jsp. Furthermore, those properties can be automatically updated as the users enter seven pieces of new faculty information into seven text fields related to those tags in our JSF page FacultyPage.jsp.

B.If the user entered a new faculty image into the Image field in the JSF page, the property facultyImageName defined in the managed bean should contain a valid faculty image file’s name, and this name is assigned to the property facultyImage that will be used to display this new image later.

C.The InsertFaculty() method defined in our session bean, which will be developed in the next section, is called to perform this new faculty record insertion. The argument passed into that method is the string array fInsert[] that contains seven pieces of new faculty information. The running result of that method is returned and assigned to the local variable insert.

D.If the running result of the method InsertFaculty() is false, which means that the data insertion has failed, this situation is displayed by executing the setMessage() method in the msgDlg instance.

E.A null is returned since this returning value is not important to this application.

Next, let’s develop the InsertFaculty() method in our session bean class FacultySessionBean.java to perform the data insertion using the Hibernate API.

730 Chapter 8 Developing Java Web Applications to Access Databases

public boolean InsertFaculty(String[] newFaculty) {

AFaculty ft = new Faculty();

Borg.hibernate.Transaction tx = session.beginTransaction();

Cif (!tx.isActive())

tx.begin();

Dft.setFacultyId(newFaculty[0]);

ft.setFacultyName(newFaculty[1]);

ft.setOffice(newFaculty[2]);

ft.setPhone(newFaculty[3]);

ft.setCollege(newFaculty[4]);

ft.setTitle(newFaculty[5]);

ft.setEmail(newFaculty[6]);

Esession.persist(ft);

Ftx.commit();

Greturn true;

}

Figure 8.146. The codes for the InsertFaculty() method.

8.6.9.2 Build the InsertFaculty() Method for the Session Bean to Perform Data Insertions

Open the code window for our session bean class FacultySessionBean.java, and enter the codes shown in Figure 8.146 into this file to create a new method InsertFaculty() and its codes.

Let’s have a closer look at this piece of new codes to see how it works.

A.First, a new instance of the entity class Faculty is created, since we need this object to perform new faculty record insertion later.

B.A new Transaction object tx is created to help to perform this data insertion action.

C.If this new Transaction instance has not been active, the begin() method is executed to begin this transaction instance.

D.Seven setter methods are executed to set up seven pieces of new faculty information to the newly created Faculty entity object.

E.The insertion action is performed by executing the persist() method for the session object with the Faculty entity object as the argument of this method.

F.The commit() method is executed to actually trigger and perform this insertion action.

G.Finally, a true is returned to the calling method to indicate the success of this data insertion.

Now let’s build and run the project to test this data insertion function.

8.6.9.3 Run the Project to Test the New Faculty Record Insertion

Click on the Clean and Build Main Project button to build our project. If everything is fine, right click on our JSF page FacultyPage.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.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 731

Figure 8.147. The newly inserted faculty record.

On the opened Faculty Page, type a desired faculty name such as Ying Bai into the

Faculty Name field to perform a query for that faculty member. Then enter seven pieces of new faculty information shown in Figure 8.147 into the associated seven fields as a new faculty record. Also, enter the default faculty image file’s name, Default.jpg, into the Image field as a new image for this new faculty, as shown in Figure 8.147. Then click on the Insert button to try to insert this new faculty record into the Faculty table in our sample database.

To check and confirm this new data insertion, open the Faculty 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 Faculty table and select the View Data item.

Your opened Faculty table is shown in Figure 8.148.

It can be found that the new faculty record with the faculty_id of W56789, which is located at the first row and has been highlighted in dark color, has been successfully inserted into our database. Our data insertion action is successful!

It is highly recommended to remove this newly inserted faculty record from our database since we want to keep our database clean. To do this clean up, click and select the first row in this Faculty table, and click on the Delete Selected Record button that is the second button under the query statement: select * from CSE_DEPT.FACULTY at the top of this window. Click on the Yes button to the popup message box to confirm this deletion action.

Next, let’s discuss how to update and delete an existing faculty record in our database using the JSF faces and Java beans.

732 Chapter 8 Developing Java Web Applications to Access Databases

Figure 8.148. The opened Faculty table in the NetBeans IDE.

8.6.10 Update and Delete Records from the Faculty Table Using JSF Page and Java Bean

First, let’s handle the faculty record updating action.

Because of the complex in updating a faculty record with the primary key faculty_id, in this section, we still want to update a faculty record with an existing faculty_id. In other words, we will update a faculty record by changing all columns without touching the faculty_id column since one needs to update this faculty_id first in the child tables (LogIn and Course) before he can update it in the parent table (Faculty) if one wants to update this faculty_id column.

As we did for the new faculty record insertion in the last section, we can divide this faculty record updating action into two Java beans:the Java managed bean FacultyMBean. java that is used to manage and control the data updating, and the session bean

FacultySessionBean.java that is used to perform the actual data updating actions. First, let’s build the codes for the managed bean to manage this data updating

action.

8.6.10.1 Add the Codes to the Java Managed Bean to Manage Data Updating

To begin this coding process, let’s first add a new method Update() into our managed bean FacultyMBean.java. Recall that in Section 8.6.8.1, we have bound this method to the <h:commandButton id=″Update″> tag in our JSF page FacultyPage.jsp.

Open the code window of our managed bean FacultyMBean.java and add a new method Update() into that file with the codes that are shown in Figure 8.149.

Recall that in Section 8.6.8.1, when we modified our JSF page FacultyPage.jsp file, we added one command tag shown below to that page:

<h:commandButton id=″Update″ action=″#{FacultyMBean.Update}″ value=″Update″ />

8.6 Build Java Web Project to Access and Manipulate Oracle Database 733

public String Update() {

Aboolean update = false;

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true); String[] fUpdate = {name, office, phone, college, title, email, facultyID};

Bif (facultyImageName != null)

facultyImage = facultyImageName;

Cupdate = facultySessionBean.UpdateFaculty(fUpdate);

Dif (!update) {

msgDlg.setMessage("The faculty updating is failed!"); msgDlg.setVisible(true);

}

E return null;

}

Figure 8.149. The codes for the newly added method Update().

With this tag, the Update() method we just added into 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 Update button on our JSF page FacultyPage.jsp as the project runs.

Let’s have a closer look at this piece of newly added codes to see how it works.

A. Some local variables are created first for this method. The update is a boolean variable used to hold the running status of the UpdateFaculty() method defined in the session bean class, and we will build this method in the next section. The msgDlg is a JDialog instance used to display the debug or exception information as the project runs. The fUpdate[] is a string array used to hold six pieces of updating faculty information for an existing record in the Faculty table in our sample database. The point to be noted is that we used six properties defined in this managed bean as six pieces of updating faculty information, since those properties have been bound to the associated valueattributes of the <h:inputText> tags in our JSF page FacultyPage.jsp. Furthermore, those properties can be automatically updated as the users enter six pieces of updating faculty information into six text fields related to those tags in our JSF page FacultyPage.jsp. The seventh parameter in the fUpdate[] array is the property facultyID used to work as a query criterion.

B.If the user entered an updated faculty image’s name into the Image field in the JSF page, the property facultyImageName defined in the managed bean should contain a valid faculty image file’s name, and this name is assigned to the property facultyImage that will be used to display this updated image later.

C.The UpdateFaculty() method defined in our session bean, which will be developed in the next section, is called to perform this faculty record updating. The argument passed into that method is the string array fUpdate[] that contains six pieces of updated faculty information. The running result of that method is returned and assigned to the local variable update.

D.If the running result of the method UpdateFaculty() is false, which means that the data updating has failed, this situation is displayed by executing the setMessage() method in the msgDlg instance.

E.A null is returned since this returning value is not important to this application.

Next, let’s develop the UpdateFaculty() method in our session bean class to perform the data updating using the Hibernate API.

734 Chapter 8 Developing Java Web Applications to Access Databases

public boolean UpdateFaculty(String[] upFaculty) {

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();

EFaculty ft = (Faculty)session.get(Faculty.class, upFaculty[6]);

Fft.setFacultyName(upFaculty[0]);

ft.setOffice(upFaculty[1]);

ft.setPhone(upFaculty[2]);

ft.setCollege(upFaculty[3]);

ft.setTitle(upFaculty[4]);

ft.setEmail(upFaculty[5]);

Gsession.update(ft);

Htx.commit();

Isession.close();

Jreturn true;

}

Kcatch(Exception e) { msgDlg.setMessage(e.getMessage()); msgDlg.setVisible(true);

Lreturn false;

}

}

Figure 8.150. The codes for the UpdateFaculty() method in the session bean.

8.6.10.2 Build the UpdateFaculty() Method in the Session Bean to Perform Data Updating

Open the code window for our session bean class FacultySessionBean.java and enter the codes shown in Figure 8.150 into this file to create a new method UpdateFaculty() 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 updating 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 updating action.

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 faculty record from the Faculty table based on the faculty_id that is stored in the string array upFaculty[6]. The first argument of this get() method is the class type Faculty, and the second argument is the faculty_id. The returned query result is assigned to a new Faculty instance ft. A point to be noted is that the Faculty class must be casted before this method to make sure that the session object returns an appropriate object.

8.6 Build Java Web Project to Access and Manipulate Oracle Database 735

F.Six setter methods are executed to set up six pieces of updated faculty information to the newly created Faculty entity object ft.

G.The updating action is performed by executing the update() method for the session object, with the Faculty entity object ft as the argument of this method.

H.The commit() method is executed to actually trigger and perform this data updating action.

I.The close() method is executed to close this opened session object when this data updating is complete.

J.Finally, a true is returned to the calling method to indicate the success of this data updating action.

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

L.A false is returned if any exception occurred during this data updating process.

Now let’s build and run the project to test this data updating function.

8.6.10.3 Run the Project to Test the Faculty 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 FacultyPage.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 Faculty Page, type a desired faculty name, such as Ying Bai, into the Faculty Name field to perform a query for that faculty member. Then enter six pieces of updated faculty information shown in Figure 8.151 into the associated six fields as an updated faculty record. Also, enter the default faculty image file’s name, Default.jpg, into the Image field as an updated image for this faculty, as shown in Figure 8.151. Then click on the Update button to try to update this faculty record against the Faculty table in our sample database.

Figure 8.151. The updated faculty information.

736 Chapter 8 Developing Java Web Applications to Access Databases

Figure 8.152. The updated faculty record.

To check and confirm this data updating action, open the Faculty 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 Faculty table and select the View Data item.

Your opened Faculty table is shown in Figure 8.152.

It can be found that the faculty record with the faculty_id of B78880, which is located at the first row on this table and has been highlighted in dark color, has been successfully updated with six pieces of updated faculty information. Our data updating action is successful!

It is highly recommended to recover this updated faculty 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 FacultyPage.jsp to perform another updating action by entering the original information that is shown below for the faculty member Ying Bai and clicking on the Update button. Make sure that the Image field is empty when you use the first way to recover that faculty information since we do not want to update the image for the faculty Ying Bai.

The second way is that you can directly do this recovery by opening the Faculty table in the Services window and modifying the updated row with the original faculty information for faculty member Ying Bai, which is listed below:

Name: Ying Bai

Title: Associate Professor

Office: MTC-211

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]