Page #467 (34.7. Database Programming in Servlets)

 
[Page 1180 ( continued )]

34.8. Session Tracking

Web servers use the Hyper-Text Transport Protocol (HTTP). HTTP is a stateless protocol. An HTTP Web server cannot associate requests from a client, and therefore treats each request independently. This protocol works fine for simple Web browsing, where each request typically results in an HTML file or a text file being sent back to the client. Such simple requests are isolated. However, the requests in interactive Web applications are often related . Consider the two requests in the following scenario:

  • Request 1: A client sends registration data to the server; the server then returns the data to the user for confirmation.

  • Request 2: The client confirms the data by resubmitting it.

In Request 2, the data submitted in Request 1 is sent back to the server. These two requests are related in a session. A session can be defined as a series of related interactions between a single client and the Web server over a period of time. Tracking data among requests in a session is known as session tracking .

This section introduces three techniques for session tracking: using hidden values , using cookies , and using the session tracking tools from servlet API .

34.8.1. Session Tracking Using Hidden Values

You can track a session by passing data from the servlet to the client as hidden values in a dynamically generated HTML form by including a field like this one:

   <input type   =   "hidden"   name   =   "lastName"   value   =   "Smith"   > 

The next request will submit the data back to the servlet. The servlet retrieves this hidden value just like any other parameter value, using the getParameter method.


[Page 1181]

Let us use an example to demonstrate using hidden values in a form. The example creates a servlet that processes a registration form. The client submits the form using the GET method, as shown in Figure 34.17. The server collects the data in the form, displays it to the client, and asks the client for confirmation, as shown in Figure 34.18. The client confirms the data by submitting the request with the hidden values using the POST method. Finally, the servlet writes the data to a database.

Figure 34.17. The registration form collects user information.

Figure 34.18. The servlet asks the client for confirmation of the input.

Create an HTML form named Registration.html in Listing 34.8 for collecting the data and sending it to the database using the GET method for confirmation. This file is almost identical to Listing 34.3, Student_Registration_Form.html. Place this file under c:\jakarta-tomcat-5.5.9\webapps\liangweb .


[Page 1182]
Listing 34.8. Registration.html
 1  <!-- Registration.html -->  2   <html>   3   <head>   4   <title>   Using Hidden Data for Session Tracking   </title>   5   </head>   6   <body>   7 Please register to your instructor's student address book. 8 9    <form method   =   "get"   action   =   "/liangweb/Registration">    10   <p>   Last Name   <font color   =   "#FF0000"   >   *   </font>   11   <input type   =   "text"   name   =   "lastName"   >   12 First Name   <font color   =   "#FF0000"   >   *   </font>   13   <input type   =   "text"   name   =   "firstName"   >   14 MI   <input type   =   "text"   name   =   "mi"   size   =   "3"   >   15   </p>   16   <p>   Telephone 17   <input type   =   "text"   name   =   "telephone"   size   =   "20"   >   18 Email 19   <input type   =   "text"   name   =   "email"   size   =   "28"   >   20   </p>   21   <p>   Street   <input type   =   "text"   name   =   "street"   size   =   "50"   >   22   </p>   23   <p>   City   <input type   =   "text"   name   =   "city"   size   =   "23"   >   24 State 25   <select size   =   "1"   name   =   "state"   >   26   <option value   =   "GA"   >   Georgia-GA   </option>   27   <option value   =   "OK"   >   Oklahoma-OK   </option>   28   <option value   =   "IN"   >   Indiana-IN   </option>   29   </select>   30 Zip   <input type   =   "text"   name   =   "zip"   size   =   "9"   >   31   </p>   32   <p>      <input type   =   "submit"   name   =   "Submit"   value   =   "Submit"   >    33    <input type   =   "reset"   value =   "Reset"   >    34   </p>   35    </form>    36   <p><font color   =   "#FF0000"   >   * required fields   </font></p>   37   </body>   38   </html>   

Create the servlet named Registration in Listing 34.9 and compile it into c:\jakarta-tomcat-5.5.9\webapps\liangweb\WEB-INF\classes .

Listing 34.9. Registration.java
(This item is displayed on pages 1182 - 1185 in the print version)
 1   import   javax.servlet.*; 2   import   javax.servlet.http.*; 3   import   java.io.*; 4   import   java.sql.*; 5 6   public class   Registration   extends   HttpServlet { 7  // Use a prepared statement to store a student into the database  8   private   PreparedStatement pstmt; 9 10  /** Initialize variables */  11    public void   init()   throws   ServletException  { 12 initializeJdbc(); 13 } 14 

[Page 1183]
 15  /** Process the HTTP Get request */  16    public void   doGet(HttpServletRequest request, HttpServletResponse  17  response)   throws   ServletException, IOException  { 18 response.setContentType(   "text/html"   ); 19 PrintWriter out = response.getWriter(); 20 21  // Obtain data from the form  22 String lastName = request.getParameter(   "lastName"   ); 23 String firstName = request.getParameter(   "firstName"   ); 24 String mi = request.getParameter(   "mi"   ); 25 String telephone = request.getParameter(   "telephone"   ); 26 String email = request.getParameter(   "email"   ); 27 String street = request.getParameter(   "street"   ); 28 String city = request.getParameter(   "city"   ); 29 String state = request.getParameter(   "state"   ); 30 String zip = request.getParameter(   "zip"   ); 31 32   if   (lastName.length() ==     firstName.length() ==     ) { 33 out.println(   "Last Name and First Name are required"   ); 34   return   ;  // End the method  35 } 36 37  // Ask for confirmation  38 out.println(   "You entered the following data"   ); 39 out.println(   "<p>Last name: "   + lastName); 40 out.println(   "<br>First name: "   + firstName); 41 out.println(   "<br>MI: "   + mi); 42 out.println(   "<br>Telephone: "   + telephone); 43 out.println(   "<br>Email: "   + email); 44 out.println(   "<br>Address: "   + street); 45 out.println(   "<br>City: "   + city); 46 out.println(   "<br>State: "   + state); 47 out.println(   "<br>Zip: "   + zip); 48 49  // Set the action for processing the answers  50  out.println(   "<p><form method=\"   post\   " action="   +  51    "/liangweb/Registration>"   );  52  // Set hidden values  53 out.println(   "<p><input type=\"   hidden\   " "   + 54   "value="   + lastName +   " name=\"   lastName\   ">"   ); 55 out.println(   "<p><input type=\"   hidden\   " "   + 56   "value="   + firstName +   " name=\"   firstName\   ">"   ); 57 out.println(   "<p><input type=\"   hidden\   " "   + 58   "value="   + mi +   " name=\"   mi\   ">"   ); 59 out.println(   "<p><input type=\"   hidden\   " "   + 60   "value="   + telephone +   " name=\"   telephone\   ">"   ); 61 out.println(   "<p><input type=\"   hidden\   " "   + 62   "value="   + email +   " name=\"   email\   ">"   ); 63 out.println(   "<p><input type=\"   hidden\   " "   + 64   "value="   + street +   " name=\"   street\   ">"   ); 65 out.println(   "<p><input type=\"   hidden\   " "   + 66   "value="   + city +   " name=\"   city\   ">"   ); 67 out.println(   "<p><input type=\"   hidden\   " "   + 68   "value="   + state +   " name=\"   state\   ">"   ); 69 out.println(   "<p><input type=\"   hidden\   " "   + 70   "value="   + zip +   " name=\"   zip\   ">"   ); 71 out.println(   "<p><input type=\"   submit\   " value=\"   Confirm\   " >"   ); 72 out.println(   "</form>"   ); 73 74 out.close();  // Close stream  75 } 

[Page 1184]
 76 77  /** Process the HTTP Post request */  78   public void  doPost(HttpServletRequest request, HttpServletResponse  79  response)   throws   ServletException, IOException  { 80 response.setContentType(   "text/html"   ); 81 PrintWriter out = response.getWriter(); 82 83   try   { 84 String lastName = request.getParameter(   "lastName"   ); 85 String firstName = request.getParameter(   "firstName"   ); 86 String mi = request.getParameter(   "mi"   ); 87 String telephone = request.getParameter(   "telephone"   ); 88 String email = request.getParameter(   "email"   ); 89 String street = request.getParameter(   "street"   ); 90 String city = request.getParameter(   "city"   ); 91 String state = request.getParameter(   "state"   ); 92 String zip = request.getParameter(   "zip"   ); 93 94 storeStudent(lastName, firstName, mi, telephone, email, 95 street, city, state, zip); 96 97 out.println(firstName +   " "   + lastName + 98   " is now registered in the database"   ); 99 } 100   catch   (Exception ex) { 101 out.println(   "Error: "   + ex.getMessage()); 102   return   ;  // End the method  103 } 104 } 105 106  /** Initialize database connection */  107   private void   initializeJdbc() { 108   try   { 109  // Declare driver and connection string  110 String driver =   "sun.jdbc.odbc.JdbcOdbcDriver"   ; 111 String connectionString =   "jdbc:odbc:exampleMDBDataSource"   ; 112  /* For Oracle  113  String driver = "oracle.jdbc.driver.OracleDriver";  114  String connectionString = "jdbc:oracle:" +  115  "thin:scott/tiger@liang.armstrong.edu:1521:orcl";  116  */  117  // Load the Oracle JDBC Thin driver  118 Class.forName(driver); 119 120  // Connect to the sample database  121 Connection conn = DriverManager.getConnection 122 (connectionString); 123 124  // Create a Statement  125 pstmt = conn.prepareStatement(   "insert into Address "   + 126   "(lastName, firstName, mi, telephone, email, street, city, "   127 +   "state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"   ); 128 } 129   catch   (Exception ex) { 130 System.out.println(ex); 131 } 132 } 133 

[Page 1185]
 134  /** Store a student record to the database */  135   private void    storeStudent(String lastName, String firstName,  136  String mi, String phone, String email, String address,  137  String city, String state, String zip)   throws   SQLException  { 138 pstmt.setString(   1   , lastName); 139 pstmt.setString(   2   , firstName); 140 pstmt.setString(   3   , mi); 141 pstmt.setString(   4   , phone); 142 pstmt.setString(   5   , email); 143 pstmt.setString(   6   , address); 144 pstmt.setString(   7   , city); 145 pstmt.setString(   8   , state); 146 pstmt.setString(   9   , zip); 147 pstmt.executeUpdate(); 148 } 149 } 

The servlet processes the GET request by generating an HTML page that displays the client's input and asks for the client's confirmation. The input data consists of hidden values in the newly generated forms, so it will be sent back in the confirmation request. The confirmation request uses the POST method. The servlet retrieves the hidden values and stores them in the database.

Since the first request does not write anything to the database, it is appropriate to use the GET method. Since the second request results in an update to the database, the POST method must be used.

Note

The hidden values could also be sent from the URL query string if the request uses the GET method.


34.8.2. Session Tracking Using Cookies

You can track sessions using cookies, which are small text files that store sets of name-value pairs on the disk in the client's computer. Cookies are sent from the server through the instructions in the header of the HTTP response. The instructions tell the browser to create a cookie with a given name and its associated value. If the browser already has a cookie with the key name, the value will be updated. The browser will then send the cookie with any request submitted to the same server. Cookies can have expiration dates set, after which they will not be sent to the server. The javax.servlet.http.Cookie is used to create and manipulate cookies, as shown in Figure 34.19.

Figure 34.19. Cookie stores a name-value pair and other information about the cookie.
(This item is displayed on page 1186 in the print version)

To send a cookie to the browser, use the addCookie method in the HttpServletResponse class, as shown below:

 response.addCookie(cookie); 

where response is an instance of HttpServletResponse .

To obtain cookies from a browser, use

 request.getCookies(); 

where request is an instance of HttpServletRequest .

To demonstrate the use of cookies, let us create an example that accomplishes the same task as Listing 34.9, Registration.java. Instead of using hidden values for session tracking, it uses cookies.


[Page 1186]

Create the servlet named RegistrationWithHttpCookie in Listing 34.10. Compile it into c:\jakarta-tomcat-5.5.9\webapps\liangweb\WEB-INF\classes .

Create an HTML file named RegistrationWithCookie.html that is identical to Registration. html except that the action is replaced by

 http://localhost:   8080   /liangweb/RegistrationWithCookie 

Listing 34.10. RegistrationWithCookie.java
(This item is displayed on pages 1186 - 1189 in the print version)
 1   import   javax.servlet.*; 2   import   javax.servlet.http.*; 3   import   java.io.*; 4   import   java.sql.*; 5 6    public class   RegistrationWithCookie   extends   HttpServlet  { 7   private static final   String CONTENT_TYPE =   "text/html"   ; 8  // Use a prepared statement to store a student into the database  9   private   PreparedStatement pstmt; 10 11  /** Initialize variables */  12    public void   init()   throws   ServletException  { 13 initializeJdbc(); 14 } 15 16  /** Process the HTTP Get request */  17    public void   doGet(HttpServletRequest request, HttpServletResponse  18  response)   throws   ServletException, IOException  { 19 response.setContentType(   "text/html"   ); 20 PrintWriter out = response.getWriter(); 21 22  // Obtain data from the form  23 String lastName = request.getParameter(   "lastName"   ); 24 String firstName = request.getParameter(   "firstName"   ); 25 String mi = request.getParameter(   "mi"   ); 26 String telephone = request.getParameter(   "telephone"   ); 

[Page 1187]
 27 String email = request.getParameter(   "email"   ); 28 String street = request.getParameter(   "street"   ); 29 String city = request.getParameter(   "city"   ); 30 String state = request.getParameter(   "state"   ); 31 String zip = request.getParameter(   "zip"   ); 32 33  // Create cookies and send cookies to browsers  34  Cookie cookieLastName =   new   Cookie(   "lastName"   , lastName);  35  // cookieLastName.setMaxAge(1000);  36  response.addCookie(cookieLastName);  37 Cookie cookieFirstName =   new   Cookie(   "firstName"   , firstName); 38 response.addCookie(cookieFirstName); 39  // cookieFirstName.setMaxAge(0);  40 Cookie cookieMi =   new   Cookie(   "mi"   , mi); 41 response.addCookie(cookieMi); 42 Cookie cookieTelephone =   new   Cookie(   "telephone"   , telephone); 43 response.addCookie(cookieTelephone); 44 Cookie cookieEmail =   new   Cookie(   "email"   , email); 45 response.addCookie(cookieEmail); 46 Cookie cookieStreet =   new   Cookie(   "street"   , street); 47 response.addCookie(cookieStreet); 48 Cookie cookieCity =   new   Cookie(   "city"   , city); 49 response.addCookie(cookieCity); 50 Cookie cookieState =   new   Cookie(   "state"   , state); 51 response.addCookie(cookieState); 52 Cookie cookieZip =   new   Cookie(   "zip"   , zip); 53 response.addCookie(cookieZip); 54 55 System.out.println(   "MaxAge? "   + cookieLastName.getMaxAge()); 56 System.out.println(   "MaxAge fir? "   + cookieFirstName.getMaxAge()); 57 58   if   (lastName.length() ==     firstName.length() ==     ) { 59 out.println(   "Last Name and First Name are required"   ); 60   return   ;  // End the method  61 } 62 63  // Ask for confirmation  64 out.println(   "You entered the following data"   ); 65 out.println(   "<p>Last name: "   + lastName); 66 out.println(   "<br>First name: "   + firstName); 67 out.println(   "<br>MI: "   + mi); 68 out.println(   "<br>Telephone: "   + telephone); 69 out.println(   "<br>Email: "   + email); 70 out.println(   "<br>Street: "   + street); 71 out.println(   "<br>City: "   + city); 72 out.println(   "<br>State: "   + state); 73 out.println(   "<br>Zip: "   + zip); 74 75  // Set the action for processing the answers  76 out.println(   "<p><form method=\"   post\   " action="   + 77   "/liangweb/RegistrationWithCookie>"   ); 78 out.println(   "<p><input type=\"   submit\   " value=\"   Confirm\   " >"   ); 79 out.println(   "</form>"   ); 80 out.close();  // Close stream  81 } 82 83  /** Process the HTTP Post request */  84    public void   doPost(HttpServletRequest request, HttpServletResponse  85  response)   throws   ServletException, IOException  { 

[Page 1188]
 86 response.setContentType(CONTENT_TYPE); 87 PrintWriter out = response.getWriter(); 88 89 String lastName =   ""   ; 90 String firstName =   ""   ; 91 String mi =   ""   ; 92 String telephone =   ""   ; 93 String email =   ""   ; 94 String street =   ""   ; 95 String city =   ""   ; 96 String state =   ""   ; 97 String zip =   ""   ; 98 99  // Read the cookies  100  Cookie[] cookies = request.getCookies();  101 102  // Get cookie values  103   for   (   int   i =     ; i < cookies.length; i++) { 104   if   (  cookies[i].getName().  equals(   "lastName"   )) 105 lastName =  cookies[i].getValue()  ; 106   else if   (cookies[i].getName().equals(   "firstName"   )) 107 firstName = cookies[i].getValue(); 108   else if   (cookies[i].getName().equals(   "mi"   )) 109 mi = cookies[i].getValue(); 110   else if   (cookies[i].getName().equals(   "telephone"   )) 111 telephone = cookies[i].getValue(); 112   else if   (cookies[i].getName().equals(   "email"   )) 113 email = cookies[i].getValue(); 114   else if   (cookies[i].getName().equals(   "street"   )) 115 street = cookies[i].getValue(); 116   else if   (cookies[i].getName().equals(   "city"   )) 117 city = cookies[i].getValue(); 118   else if   (cookies[i].getName().equals(   "state"   )) 119 state = cookies[i].getValue(); 120   else if   (cookies[i].getName().equals(   "zip"   )) 121 zip = cookies[i].getValue(); 122 } 123 124   try   { 125  storeStudent(lastName, firstName, mi, telephone, email, street,  126  city, state, zip);  127 128 out.println(firstName +   " "   + lastName + 129   " is now registered in the database"   ); 130 131 out.close();  // Close stream  132 } 133   catch   (Exception ex) { 134 out.println(   "Error: "   + ex.getMessage()); 135   return   ;  // End the method  136 } 137 } 138 139  /** Initialize database connection */  140   private void   initializeJdbc() { 141   try   { 142  // Declare driver and connection string  143 String driver =   "sun.jdbc.odbc.JdbcOdbcDriver"   ; 144 String connectionString =   "jdbc:odbc:exampleMDBDataSource"   ; 

[Page 1189]
 145  // For Oracle  146  // String driver = "oracle.jdbc.driver.OracleDriver";  147  // String connectionString = "jdbc:oracle:" +  148  // "thin:scott/tiger@liang.armstrong.edu:1521:orcl";  149 150  // Load the Oracle JDBC Thin driver  151 Class.forName(driver); 152 System.out.println(   "Driver "   + driver +   " loaded"   ); 153 154  // Connect to the sample database  155 Connection conn = DriverManager.getConnection 156 (connectionString); 157 System.out.println(   "Database "   + connectionString + 158   " connected"   ); 159 160  // Create a Statement  161 pstmt = conn.prepareStatement(   "insert into Address "   + 162   "(lastName, firstName, mi, telephone, email, street, city, "   163 +   "state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"   ); 164 } 165   catch   (Exception ex) { 166 System.out.println(ex); 167 } 168 } 169 170  /** Store a student record to the database */  171   private void    storeStudent(String lastName, String firstName,  172  String mi, String telephone, String email, String street,  173  String city, String state, String zip)   throws   SQLException {  174 pstmt.setString(   1   , lastName); 175 pstmt.setString(   2   , firstName); 176 pstmt.setString(   3   , mi); 177 pstmt.setString(   4   , telephone); 178 pstmt.setString(   5   , email); 179 pstmt.setString(   6   , street); 180 pstmt.setString(   7   , city); 181 pstmt.setString(   8   , state); 182 pstmt.setString(   9   , zip); 183 pstmt.executeUpdate(); 184 } 185 } 

You have to create a cookie for each value you want to track, using the Cookie class's only constructor, which defines a cookie's name and value as shown below (line 34):

 Cookie cookieLastName =   new   Cookie(   "lastName"   , lastName); 

To send the cookie to the browser, use a statement like this one (line 36):

 response.addCookie(cookieLastName); 

If a cookie with the same name already exists in the browser, its value is updated; otherwise , a new cookie is created.

Cookies are automatically sent to the Web server with each request from the client. The servlet retrieves all the cookies into an array using the getCookies method (line 100):

 Cookie[] cookies = request.getCookies(); 

To obtain the name of the cookie, use the getName method (line 104):

 String name = cookies[i].getName(); 


[Page 1190]

The cookie's value can be obtained using the getValue method:

 String value = cookies[i].getValue(); 

Cookies are stored as strings just like form parameters and hidden values. If a cookie represents a numeric value, you have to convert it into an integer or a double, using the parseInt method in the Integer class or the parseDouble method in the Double class.

By default, a newly created cookie persists until the browser exits. However, you can set an expiration date, using the setMaxAge method, to allow a cookie to stay in the browser for up to 2,147,483,647 seconds (approximately 24,855 days).

34.8.3. Session Tracking Using the Servlet API

You have now learned both session tracking using hidden values and session tracking using cookies. These two session-tracking methods have problems. They send data to the browser either as hidden values or as cookies. The data is not secure, and anybody with knowledge of computers can obtain it. The hidden data is in HTML form, which can be viewed from the browser. Cookies are stored in the Cache directory of the browser. Because of security concerns, some browsers do not accept cookies. The client can turn the cookies off and limit their number. Another problem is that hidden data and cookies pass data as strings. You cannot pass objects using these two methods.

To address these problems, Java servlet API provides the javax.servlet.http.HttpSession interface, which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The session enables tracking of a large set of data. The data can be stored as objects and is secure because they are kept on the server side.

To use the Java servlet API for session tracking, first create a session object using the getSession() method in the HttpServletRequest interface:

 HttpSession session = request.getSession(); 

This obtains the session or creates a new session if the client does not have a session on the server.

The HttpSession interface provides the methods for reading and storing data to the session, and for manipulating the session, as shown in Figure 34.20.

Figure 34.20. HttpSession establishes a persistent session between a client with multiple requests and the server.
(This item is displayed on page 1191 in the print version)

Note

HTTP is stateless. So how does the server associate a session with multiple requests from the same client? This is handled behind the scenes by the servlet container and is transparent to the servlet programmer.


To demonstrate using HttpSession , let us rewrite Listing 34.9, Registration.java, and Listing 34.10, RegistrationWithCookie.java. Instead of using hidden values or cookies for session tracking, it uses servlet HttpSession .

Create the servlet named RegistrationWithHttpSession in Listing 34.11. Compile it into c:\jakarta-tomcat-5.5.9\webapps\liangweb\WEB-INF\classes . Note that this servlet contains two class files, RegistrationWithHttpSession.class and RegistrationWithHttpSession$Student.class .

Create an HTML file named RegistrationWithHttpSession.html that is identical to Registration.html except that the action is replaced by

 http://localhost:8080/liangweb/RegistrationWithHttpSession 


[Page 1191]
Listing 34.11. RegistrationWithHttpSession.java
(This item is displayed on pages 1191 - 1194 in the print version)
 1   import   javax.servlet.*; 2   import   javax.servlet.http.*; 3   import   java.io.*; 4   import   java.sql.*; 5 6    public class   RegistrationWithHttpSession   extends   HttpServlet  { 7  // Use a prepared statement to store a student into the database  8   private   PreparedStatement pstmt; 9 10  /** Initialize variables */  11    public void   init()   throws   ServletException  { 12 initializeJdbc(); 13 } 14 15  /** Process the HTTP Get request */  16    public void   doGet(HttpServletRequest request, HttpServletResponse  17  response)   throws   ServletException, IOException  { 18  // Set response type and output stream to the browser  19 response.setContentType(   "text/html"   ); 20 PrintWriter out = response.getWriter(); 21 22  // Obtain data from the form  23 String lastName = request.getParameter(   "lastName"   ); 24 String firstName = request.getParameter(   "firstName"   ); 25 String mi = request.getParameter(   "mi"   ); 26 String telephone = request.getParameter(   "telephone"   ); 27 String email = request.getParameter(   "email"   ); 28 String street = request.getParameter(   "street"   ); 29 String city = request.getParameter(   "city"   ); 

[Page 1192]
 30 String state = request.getParameter(   "state"   ); 31 String zip = request.getParameter(   "zip"   ); 32 33   if   (lastName.length() ==     firstName.length() ==     ) { 34 out.println(   "Last Name and First Name are required"   ); 35   return   ;  // End the method  36 } 37 38  // Create a Student object  39  Student student =   new   Student(lastName, firstName,  40  mi, telephone, email, street, city, state, zip);  41 42  // Get an HttpSession or create one if it does not exist  43  HttpSession httpSession = request.getSession();  44 45  // Store student object to the session  46  httpSession.setAttribute(   "student"   , student);  47 48  // Ask for confirmation  49 out.println(   "You entered the following data"   ); 50 out.println(   "<p>Last name: "   + lastName); 51 out.println(   "<p>First name: "   + firstName); 52 out.println(   "<p>MI: "   + mi); 53 out.println(   "<p>Telephone: "   + telephone); 54 out.println(   "<p>Email: "   + email); 55 out.println(   "<p>Address: "   + street); 56 out.println(   "<p>City: "   + city); 57 out.println(   "<p>State: "   + state); 58 out.println(   "<p>Zip: "   + zip); 59 60  // Set the action for processing the answers  61 out.println(   "<p><form method=\"   post\   " action="   + 62   "/liangweb/RegistrationWithHttpSession>"   ); 63 out.println(   "<p><input type=\"   submit\   " value=\"   Confirm\   " >"   ); 64 out.println(   "</form>"   ); 65 66 out.close();  // Close stream  67 } 68 69  /** Process the HTTP Post request */  70    public void   doPost(HttpServletRequest request, HttpServletResponse  71  response)   throws   ServletException, IOException  { 72  // Set response type and output stream to the browser  73 response.setContentType(   "text/html"   ); 74 PrintWriter out = response.getWriter(); 75 76  // Obtain the HttpSession  77  HttpSession httpSession = request.getSession();  78 79  // Get the Student object in the HttpSession  80  Student student = (Student)(httpSession.getAttribute(   "student"   ));  81 82   try   { 83  storeStudent(student);  84 85 out.println(student.firstName +   " "   + student.lastName + 86   " is now registered in the database"   ); 87 out.close();  // Close stream  88 } 89   catch   (Exception ex) { 

[Page 1193]
 90 out.println(   "Error: "   + ex.getMessage()); 91   return   ;  // End the method  92 } 93 } 94 95  /** Initialize database connection */  96   private void   initializeJdbc() { 97   try   { 98  // Declare driver and connection string  99 String driver =   "sun.jdbc.odbc.JdbcOdbcDriver"   ; 100 String connectionString =   "jdbc:odbc:exampleMDBDataSource"   ; 101 102  // Load the Oracle JDBC Thin driver  103 Class.forName(driver); 104 System.out.println(   "Driver "   + driver +   " loaded"   ); 105 106  // Connect to the sample database  107 Connection conn = DriverManager.getConnection 108 (connectionString); 109 System.out.println(   "Database "   + connectionString + 110   " connected"   ); 111 112  // Create a Statement  113 pstmt = conn.prepareStatement(   "insert into Address "   + 114   "(lastName, firstName, mi, telephone, email, street, city, "   115 +   "state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"   ); 116 } 117   catch   (Exception ex) { 118 System.out.println(ex); 119 } 120 } 121 122  /** Store a student record to the database */  123   private void    storeStudent(Student student)   throws   SQLException  { 124  pstmt.setString(   1   , student.getLastName());  125 pstmt.setString(   2   , student.getFirstName()); 126 pstmt.setString(   3   , student.getMi()); 127 pstmt.setString(   4   , student.getTelephone()); 128 pstmt.setString(   5   , student.getEmail()); 129 pstmt.setString(   6   , student.getStreet()); 130 pstmt.setString(   7   , student.getCity()); 131 pstmt.setString(   8   , student.getState()); 132 pstmt.setString(   9   , student.getZip()); 133 pstmt.executeUpdate(); 134 } 135 136    class   Student  { 137   private   String lastName =   ""   ; 138   private   String firstName =   ""   ; 139   private   String mi =   ""   ; 140   private   String telephone =   ""   ; 141   private   String email =   ""   ; 142   private   String street =   ""   ; 143   private   String city =   ""   ; 144   private   String state =   ""   ; 145   private   String zip =   ""   ; 146 147 Student(String lastName, String firstName, 148 String mi, String telephone, String email, String street, 149 String city, String state, String zip) { 150   this   .lastName = lastName; 

[Page 1194]
 151   this   .firstName = firstName; 152   this   .mi = mi; 153   this   .telephone = telephone; 154   this   .email = email; 155   this   .street = street; 156   this   .city = city; 157   this   .state = state; 158   this   .zip = zip; 159 } 160 161   public   String getLastName() { 162   return   lastName; 163 } 164 165   public   String getFirstName() { 166   return   firstName; 167 } 168 169   public   String getMi() { 170   return   mi; 171 } 172 173   public   String getTelephone() { 174   return   telephone; 175 } 176 177   public   String getEmail() { 178   return   email; 179 } 180 181   public   String getStreet() { 182   return   street; 183 } 184 185   public   String getCity() { 186   return   city; 187 } 188 189   public   String getState() { 190   return   state; 191 } 192 193   public   String getZip() { 194   return   zip; 195 } 196 } 197 } 

The statement (line 43)

 HttpSession httpSession = request.getSession(); 

obtains a session, or creates a new session if the session does not exist.

Since objects can be stored in HttpSession , this program defines a Student class. A Student object is created and is stored in the session using the setAttribute method, which binds the object with a name like the one shown below (line 46):

 httpSession.setAttribute(   "student"   , student); 


[Page 1195]

To retrieve the object, use the following statement (line 80):

 Student student = (Student)(httpSession.getAttribute(   "student"   )); 

There is only one session between a client and a servlet. You can store any number of objects in a session. By default, a session stays alive as long as the servlet is not destroyed . You can explicitly set the session active time using the setMaxInactiveInterval method.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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