Case Study: Guest Book

Case Study Guest Book

Our next example is a guest book that enables users to place their first name, last name and e-mail address into a guest-book database. After submitting their information, users see a Web page containing all the users in the guest book. Each e-mail address is displayed as a hyperlink that makes it possible to send an e-mail message to the person whose address it is. The example demonstrates action , the JSP page directive, JSP error pages, and using JDBC from a JSP.

The guest-book example consists of JavaBeans GuestBean (Fig. 27.20) and GuestDataBean (Fig. 27.21), and JSPs guestBookLogin.jsp (Fig. 27.22), guestBookView.jsp (Fig. 27.23) and guestBookErrorPage.jsp (Fig. 27.24). Sample outputs from this example are shown in Fig. 27.25. JavaBean GuestBean (Fig. 27.20) defines three guest propertiesfirstName, lastName and email. Each property has set and get methods to manipulate the property.

Figure 27.20. GuestBean stores information for one guest.

(This item is displayed on page 1310 in the print version)

 1 // Fig. 27.20: GuestBean.java
 2 // JavaBean to store data for a guest in the guest book.
 3 package com.deitel.jhtp6.jsp.beans;
 4
 5 public class GuestBean
 6 {
 7 private String firstName;
 8 private String lastName;
 9 private String email;
10
11 // set the guest's first name
12 public void setFirstName( String name )
13 {
14 firstName = name;
15 } // end method setFirstName
16
17 // get the guest's first name
18 public String getFirstName()
19 {
20 return firstName;
21 } // end method getFirstName
22
23 // set the guest's last name
24 public void setLastName( String name )
25 {
26 lastName = name;
27 } // end method setLastName
28
29 // get the guest's last name
30 public String getLastName()
31 {
32 return lastName;
33 } // end method getLastName
34
35 // set the guest's email address
36 public void setEmail( String address )
37 {
38 email = address;
39 } // end method setEmail
40
41 // get the guest's email address
42 public String getEmail()
43 {
44 return email;
45 } // end method getEmail
46 } // end class GuestBean

Figure 27.21. GuestDataBean performs database access on behalf of guestBookLogin.jsp.

(This item is displayed on pages 1311 - 1312 in the print version)

 1 // Fig. 27.21: GuestDataBean.java
 2 // Class GuestDataBean makes a database connection and supports
 3 // inserting and retrieving data from the database.
 4 package com.deitel.jhtp6.jsp.beans;
 5
 6 import java.sql.SQLException;
 7 import javax.sql.rowset.CachedRowSet;
 8 import java.util.ArrayList;
 9 import com.sun.rowset.CachedRowSetImpl; // CachedRowSet implementation
10
11 public class GuestDataBean
12 {
13 private CachedRowSet rowSet;
14
15 // construct GuestDataBean object
16 public GuestDataBean() throws Exception
17 {
18 // load the MySQL driver
19 Class.forName( "com.mysql.jdbc.Driver" );
20
21 // specify properties of CachedRowSet
22 rowSet = new CachedRowSetImpl();
23 rowSet.setUrl( "jdbc:mysql://localhost/guestbook" );
24 rowSet.setUsername( "jhtp6" );
25 rowSet.setPassword( "jhtp6" );
26
27 // obtain list of titles
28 rowSet.setCommand(
29 "SELECT firstName, lastName, email FROM guests" );
30 rowSet.execute();
31 } // end GuestDataBean constructor
32
33 // return an ArrayList of GuestBeans
34 public ArrayList< GuestBean > getGuestList() throws SQLException
35 {
36 ArrayList< GuestBean > guestList = new ArrayList< GuestBean >();
37
38 rowSet.beforeFirst(); // move cursor before the first row
39
40 // get row data
41 while ( rowSet.next() )
42 {
43 GuestBean guest = new GuestBean();
44
45 guest.setFirstName( rowSet.getString( 1 ) );
46 guest.setLastName( rowSet.getString( 2 ) );
47 guest.setEmail( rowSet.getString( 3 ) );
48
49 guestList.add( guest );
50 } // end while
51
52 return guestList;
53 } // end method getGuestList
54
55 // insert a guest in guestbook database
56 public void addGuest( GuestBean guest ) throws SQLException
57 {
58 rowSet.moveToInsertRow(); // move cursor to the insert row
59
60 // update the three columns of the insert row
61 rowSet.updateString( 1, guest.getFirstName() );
62 rowSet.updateString( 2, guest.getLastName() );
63 rowSet.updateString( 3, guest.getEmail() );
64 rowSet.insertRow(); // insert row to rowSet
65 rowSet.moveToCurrentRow(); // move cursor to the current row
66 rowSet.acceptChanges(); // propagate changes to database
67 } // end method addGuest
68 } // end class GuestDataBean

Figure 27.22. JSP guestBookLogin.jsp enables the user to submit a first name, a last name and an e-mail address to be placed in the guest book.

(This item is displayed on pages 1313 - 1315 in the print version)

"http://www.w3.org/1999/xhtml"> 17 18

 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7 <%-- page settings --%>
 8 <%@ page errorPage = "guestBookErrorPage.jsp" %>
 9
10 <%-- beans used in this JSP --%>
11  "guest" scope = "page" 
12  class = "com.deitel.jhtp6.jsp.beans.GuestBean" /> 
13  "guestData" scope = "request" 
14  class = "com.deitel.jhtp6.jsp.beans.GuestDataBean" />
15
16 
Guest Book Login 19 32 33 34 "guest" property = "*" /> 35 <% // start scriptlet 36 if ( guest.getFirstName() == null || 37 guest.getLastName() == null || 38 guest.getEmail() == null ) 39 { 40 %> <%-- end scriptlet to insert fixed template data --%> 41"post" action = "guestBookLogin.jsp"> 42

Enter your first name, last name and email 43 address to register in our guest book.

44 45 46 47 50 51 52 53 56 57 58 59 62 63 64 67 68
First name 48 "text" name = "firstName" /> 49
Last name 54 "text" name = "lastName" /> 55
Email 60 "text" name = "email" /> 61
"2"> 65 "submit" value = "Submit" /> 66
69 70 <% // continue scriptlet 71 } // end if 72 else 73 { 74 guestData.addGuest( guest ); 75 %> <%-- end scriptlet to insert jsp:forward action --%> 76 <%-- forward to display guest book contents --%> 77 "guestBookView.jsp" /> 78 <% // continue scriptlet 79 } // end else 80 %> <%-- end scriptlet --%> 81 82

Figure 27.23. JSP guestBookView.jsp displays the contents of the guest book.

(This item is displayed on pages 1316 - 1317 in the print version)

"http://www.w3.org/1999/xhtml"> 17 18

 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7 <%-- page settings --%>
 8 <%@ page errorPage = "guestBookErrorPage.jsp" %> 
 9 <%@ page import = "java.util.*" %> 
10 <%@ page import = "com.deitel.jhtp6.jsp.beans.*" %>
11
12 <%-- GuestDataBean to obtain guest list --%>
13  "guestData" scope = "request" 
14  class = "com.deitel.jhtp6.jsp.beans.GuestDataBean" />
15
16 
Guest List 19 33 34 35

"font-size: 2em;">Guest List

36 37 38 39 40 41 42 43 44 45 <% // start scriptlet 46 List guestList = guestData.getGuestList(); 47 Iterator guestListIterator = guestList.iterator(); 48 GuestBean guest; 49 50 while ( guestListIterator.hasNext() ) 51 { 52 guest = ( GuestBean ) guestListIterator.next(); 53 %> <%-- end scriptlet; insert fixed template data --%> 54 55 56 57 61 62 <% // continue scriptlet 63 } // end while 64 %> <%-- end scriptlet --%> 65 66
"width: 100px;">Last name "width: 100px;">First name "width: 200px;">Email
<%= guest.getLastName() %> <%= guest.getFirstName() %> 58 <a href="</span"> "mailto:<%= guest.getEmail() %>"> 59 <%= guest.getEmail() %></a> 60
67 68

Figure 27.24. JSP guestBookErrorPage.jsp responds to exceptions in guestBookLogin.jsp and guestBookView.jsp.

(This item is displayed on pages 1317 - 1318 in the print version)

"http://www.w3.org/1999/xhtml"> 13 14

 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7 <%-- page settings --%>
 8 <%@ page isErrorPage = "true" %> 
 9 <%@ page import = "java.util.*" %>
10 <%@ page import = "java.sql.*" %> 
11
12 
Error! 15 23 24 25

"bigRed"> 26 <% // scriptlet to determine exception type 27 // and output beginning of error message 28 if ( exception instanceof SQLException ) 29 { 30 %> 31 32 A SQLException 33 34 <% 35 } // end if 36 else if ( exception instanceof ClassNotFoundException ) 37 { 38 %> 39 40 A ClassNotFoundException 41 42 <% 43 } // end else if 44 else 45 { 46 %> 47 48 An exception 49 50 <% 51 } // end else 52 %> 53 <%-- end scriptlet to insert fixed template data --%> 54 55 <%-- continue error message output --%> 56 occurred while interacting with the guestbook database. 57

58

"bigRed"> 59 The error message was:
60 <%= exception.getMessage() %> 61

62

"bigRed">Please try again later

63 64

Figure 27.25. JSP guest book sample output windows.

(This item is displayed on pages 1319 - 1320 in the print version)

 

JavaBean GuestDataBean (Fig. 27.21) connects to the guestbook database and provides methods getGuestList and addGuest to manipulate the database. The guestbook database has a single table (guests) containing three columns (firstName, lastName and email). Each column stores String values. We provide a SQL script (guestbook.sql) with this example that can be used with the MySQL DBMS to create the guestbook database. For further details on creating a database with MySQL, refer back to Section 25.7.

GuestDataBean constructor (lines 1629) loads the MySQL database driver, creates a CachedRowSet object using Sun's reference implementation CachedRowSetImpl and sets the properties of the CachedRowSet. Recall that CachedRowSet objects are disconnected rowsets, hence the database connection is automatically closed after the query is executed. Line 23 invokes method setUrl (from interface RowSet) to set the CachedRowSet's database URL property. Line 24 invokes method setUsername (from interface RowSet) to set the CachedRowSet's database username property. Line 25 invokes method setPassword (from interface RowSet) to set the CachedRowSet's database password property. Lines 2829 invoke method setCommand (from interface RowSet) to set the CachedRowSet's command property. Line 30 invokes method execute (from interface RowSet) to execute the query specified by the command property.

GuestDataBean method getGuestList (lines 3453) returns an ArrayList of GuestBean objects representing the guests in the database. Line 38 invokes method beforeFirst (from interface ResultSet) to move the CachedRowSet's cursor before the first row. Lines 4150 create the GuestBean objects for each row in the CachedRowSet.

GuestDataBean method addGuest (lines 5667) receives a GuestBean as an argument and uses the GuestBean's properties as the arguments to insert a row to the CachedRowSet, which in turn propagates the changes to the underlying database. Recall from Chapter 25 that a CachedRowSet is scrollable and updatable by default. Line 58 invokes the CachedRowSet's moveToInsertRow method to remember the current row position and move the cursor to the insert rowa special row in an updatable result set that allows programmers to insert new rows to the result set. Lines 6163 invoke the CachedRowSet's updateString method to update the column values. Method updateString takes two argumentsan int that specifies the column index and a String that specifies the column value. Line 64 invokes the CachedRowSet's insertRow method to insert the row into the rowset. Line 65 invokes the CachedRowSet's moveToCurrentRow method to move the cursor back to the current rowthe position before method moveToInsertRow was called. Line 66 invokes the CachedRowSet's acceptChanges method to propagates the changes in the rowset to the underlying database.

Note that the GuestDataBean's constructor, getGuestList method and addGuest method do not process potential exceptions. In the constructor, line 19 can throw a ClassNotFoundException, and the other statements can throw SQLExceptions. Similarly, SQLExceptions can be thrown from the bodies of methods getGuestList and addGuest. In this example, we purposely let any exceptions that occur get passed back to the JSP that invokes the GuestDataBean's constructor or methods. This enables us to demonstrate JSP error pages. A JSP can include scriptlets that catch potential exceptions and process them. Exceptions that are not caught can be forwarded to a JSP error page for handling.

JavaServer Page guestBookLogin.jsp (Fig. 27.22) is a modified version of forward1.jsp (Fig. 27.11) that displays a form in which users can enter their first name, last name and e-mail address. When the user submits the form, guestBookLogin.jsp is requested again, so it can ensure that all the data values were entered. If they were not, the guestBookLogin.jsp responds with the form again, so the user can fill in missing field(s). If the user supplies all three pieces of information, guestBookLogin.jsp forwards the request to guestBookView.jsp, which displays the guest-book contents.

Line 8 of guestBookLogin.jsp uses the page directive, which defines information that is globally available in a JSP. In this case, the page directive's errorPage attribute is set to guestBookErrorPage.jsp (Fig. 27.24), indicating that all uncaught exceptions are forwarded to guestBookErrorPage.jsp for processing.

Lines 1114 define two actions. Lines 1112 create an instance of GuestBean called guest. This bean has page scopeit exists for use only in this page. Lines 1314 create an instance of GuestDataBean called guestData. This bean has request scopeit exists for use in this page and any other page that helps process a single client request. Thus, when guestBookLogin.jsp forwards a request to guestBookView.jsp, the same GuestDataBean instance is still available for use in guestBookView.jsp.

Line 34 demonstrates setting a property of the GuestBean called guest with a request parameter value. The input elements in lines 48, 54 and 60 have the same names as the GuestBean properties. So we use action 's ability to match request parameters to properties by specifying "*" for attribute property. You can set the properties individually by replacing line 34 with the following lines:

  "guest" property = "firstName"
 param = "firstName" />

  "guest" property = "lastName"
 param = "lastName" />

  "guest" property = "email"
 param = "email" />

 

If the request parameters had names that differed from GuestBean's properties, the param attribute in each of the preceding actions could be changed to the appropriate request parameter name. Or you could make a call to the set method directly, like this:

 <% guest.setFirstName( request.getparameter( "firstName" ) ); %>

 

JavaServer Page guestBookView.jsp (Fig. 27.23) outputs an XHTML document containing the guest-book entries in tabular format. Lines 810 define three page directives. Line 8 specifies that the error page for this JSP is guestBookErrorPage.jsp. Line 9 indicates that classes from package java.util are used in this JSP, and line 10 indicates that classes from our package com.deitel.jhtp6.jsp.beans are also used.

Lines 1314 specify a action that declares a reference to a GuestDataBean object. If a GuestDataBean object already exists, the action returns a reference to the existing object. Otherwise, the action creates a GuestDataBean for use in this JSP. Lines 4553 define a scriptlet that gets the guest list from the GuestDataBean and begins a loop to output the entries. Lines 5461 combine fixed template text with JSP expressions to create rows in the table of guest-book data that will be displayed on the client. The scriptlet at lines 6264 terminates the loop that begins at line 50.

JavaServer Page guestBookErrorPage.jsp (Fig. 27.24) outputs an XHTML document containing an error message based on the type of exception that causes this error page to be invoked. Lines 810 define several page directives. Line 8 sets page directive attribute isErrorPage. Setting this attribute to TRue makes the JSP an error page and enables access to the JSP implicit object exception that refers to an exception object indicating the problem that occurred.

Lines 2652 define scriptlets that determine the type of exception that occurred and begin outputting an appropriate error message with fixed template data. The actual error message from the exception is output at line 60.

Figure 27.25 shows sample interactions between the user and the JSPs in the guest book example. In the first two rows of output, separate users entered their first name, last name and e-mail. In each case, the current contents of the guest book are returned and displayed for the user. In the final interaction, a third user specified an e-mail address that already existed in the database. The e-mail address is the primary key in the guests table of the guestbook database, so its values must be unique. Thus, the database prevents the new record from being inserted, and an exception occurs. The exception is forwarded to guestBookErrorPage.jsp for processing, which results in the last screen capture.

To test the guest book in Tomcat, copy guestBookLogin.jsp, guestBookView.jsp and guestBookErrorPage.jsp into the jsp directory created in Section 27.3. Copy GuestBean.class and GuestDataBean.class into the jhtp6 Web application's WEBINFclassescomdeiteljhtp6eans directory in Tomcat. [Note: This example will work only if the proper package directory structure for GuestBean and GuestDataBean is defined in the classes directory. These classes are declared in package com.deitel.jhtp6.jsp.beans.] Create the database by running the guestbook.sql script included with this example on the CD that accompanies this book. For further details on creating a database with MySQL, refer back to Section 25.7. Open your Web browser and enter the following URL to test guestBookLogin.jsp:

http://localhost:8080/jhtp6/jsp/guestBookLogin.jsp


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover

show all menu





Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net