Download presentation
Presentation is loading. Please wait.
Published byBuddy Carter Modified over 8 years ago
1
2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture 9.2.1 Interface Servlet and the Servlet Life Cycle 9.2.2 HttpServlet Class 9.2.3 HttpServletRequest Interface 9.2.4 HttpServletResponse Interface 9.3 Handling HTTP get Requests 9.3.1 Setting Up the Apache Tomcat Server 9.3.2 Deploying a Web Application 9.4 Handling HTTP get Requests Containing Data 9.5 Handling HTTP post Requests 9.6 Redirecting Requests to Other Resources 9.7 Session Tracking 9.7.1 Cookies 9.7.2 Session Tracking with HttpSession 9.8 Multi-Tier Applications: Using JDBC from a Servlet 9.9 HttpUtils Class 9.10 Internet and World Wide Web Resources
2
2002 Prentice Hall. All rights reserved. 9.1 Introduction Java networking capabilities –Socket-based and packet-based communications Package java.net –Remote Method Invocation (RMI) Package java.rmi –Servlets and Java Server Pages (JSP) Request-response model Packages javax.servlet javax.servlet.http javax.servlet.jsp javax.servlet.tagext Form the Web tier of J2EE
3
2002 Prentice Hall. All rights reserved. 9.1 Introduction (Cont.) Servlets –Thin clients –Request/response mechanism –Session-tracking capabilities –redirection Tomcat –Jakarta project –Official reference implementation of the JSP and servlet standards
4
2002 Prentice Hall. All rights reserved. 9.2 Servlet Overview and Architecture Servlet container (servlet engine) –Server that executes a servlet Web servers and application servers –Netscape iPlanet Application Server –Microsoft’s Internet Information Server (IIS) –Apache HTTP Server –BEA’s WebLogic Application Server –IBM’s WebSphere Application Server –World Wide Web Consortium’s Jigsaw Web Server
5
2002 Prentice Hall. All rights reserved. 9.2.1 Interface Servlet and the Servlet Life Cycle Interface Servlet –All servlets must implement this interface –All methods of interface Servlet are invoked automatically Servlet life cycle –Servlet container invokes the servlet’s init method –Servlet’s service method handles requests –Servlet’s destroy method releases servlet resources when the servlet container terminates the servlet Servlet implementation –GenericServlet –HttpServlet
6
2002 Prentice Hall. All rights reserved. 9.2.1 Interface Servlet and the Servlet Life Cycle (Cont.)
7
2002 Prentice Hall. All rights reserved. 9.2.2 HttpServlet Class Overrides method service Two most common HTTP request types –get requests –post requests Method doGet responds to get requests Method doPost responds to post requests HttpServletRequest and HttpServletResponse objects
8
2002 Prentice Hall. All rights reserved. 9.2.2 HttpServlet Class (Cont.)
9
2002 Prentice Hall. All rights reserved. 9.2.3 HttpServletRequest Interface Web server –creates an HttpServletRequest object –passes it to the servlet’s service method HttpServletRequest object contains the request from the client
10
2002 Prentice Hall. All rights reserved. 9.2.3 HttpServletRequest Interface (Cont.)
11
2002 Prentice Hall. All rights reserved. 9.2.4 HttpServletResponse Interface Web server –creates an HttpServletResponse object –passes it to the servlet’s service method
12
2002 Prentice Hall. All rights reserved. 9.2.4 HttpServletResponse Interface (Cont.)
13
2002 Prentice Hall. All rights reserved. 9.3 Handling HTTP get Requests get request –Retrieve the content of a URL Example: WelcomeServlet –a servlet handles HTTP get requests
14
2002 Prentice Hall. All rights reserved. Outline Fig. 9.5 WelcomeServlet that responds to a simple HTTP get request. Lines 5-6 Line 9 Lines 12-44 Line 16 Line 17 Lines 22-42 1 // Fig. 9.5: WelcomeServlet.java 2 // A simple servlet to process get requests. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet extends HttpServlet { 10 11 // process "get" requests from clients 12 protected void doGet( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 response.setContentType( "text/html" ); 17 PrintWriter out = response.getWriter(); 18 19 // send XHTML page to client 20 21 // start XHTML document 22 out.println( " " ); 23 24 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 25 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 26 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 27 28 out.println( 29 " " ); 30 31 // head section of document 32 out.println( " " ); 33 out.println( " A Simple Servlet Example " ); 34 out.println( " " ); 35 Import the javax.servlet and javax.servlet.http packages. Extends HttpServlet to handle HTTP get requests and HTTP post requests. Override method doGet to provide custom get request processing. Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client. Uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. Create the XHTML document by writing strings with the out object’s println method.
15
2002 Prentice Hall. All rights reserved. Outline Fig. 9.5 WelcomeServlet that responds to a simple HTTP get request. Line 43 36 // body section of document 37 out.println( " " ); 38 out.println( " Welcome to Servlets! " ); 39 out.println( " " ); 40 41 // end XHTML document 42 out.println( " " ); 43 out.close(); // close stream to complete the page 44 } 45 } Closes the output stream, flushes the output buffer and sends the information to the client.
16
2002 Prentice Hall. All rights reserved. Outline Fig. 9.6 HTML document in which the form’s action invokes WelcomeServlet through the alias welcome1 specified in web.xml. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Handling an HTTP Get Request 10 11 12 13 14 15 Click the button to invoke the servlet 16 17 18 19 20 21
17
2002 Prentice Hall. All rights reserved. Outline Fig. 9.6 HTML document in which the form’s action invokes WelcomeServlet through the alias welcome1 specified in web.xml. Program output
18
2002 Prentice Hall. All rights reserved. 9.3.1 Setting Up the Apache Tomcat Server Download Tomcat (version 3.2.3) –Jakarta.apache.org/builds/jakarta-tomcat/release/v3.2.3/bin/ Define environment variables –JAVA_HOME –TOMCAT_HOME Start the Tomcat server –tomcat start Launch the Tomcat server –http://localhost:8080/
19
2002 Prentice Hall. All rights reserved. 9.3.1 Setting Up the Apache Tomcat Server (Cont.). Fig. 9.7Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)
20
2002 Prentice Hall. All rights reserved. 9.3.2 Deploying a Web Application Web applications –JSPs, servlets and their supporting files Deploying a Web application –Directory structure Context root –Web application archive file (WAR file) –Deployment descriptor web.xml
21
2002 Prentice Hall. All rights reserved. 9.3.2 Deploying a Web Application (Cont.)
22
2002 Prentice Hall. All rights reserved. Outline Fig. 9.9 Deployment descriptor (web.xml) for the advjhtp1 Web application. Lines 5-37 Lines 8-11 Lines 13-16 Lines 19-29 Line 20 Lines 22-24 Lines 26-28 1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" 3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> 4 5 6 7 8 9 Advanced Java How to Program JSP 10 and Servlet Chapter Examples 11 12 13 14 This is the Web application in which we 15 demonstrate our JSP and Servlet examples. 16 17 18 19 20 welcome1 21 22 23 A simple servlet that handles an HTTP get request. 24 25 26 27 com.deitel.advjhtp1.servlets.WelcomeServlet 28 29 30 Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. Element display-name specifies a name that can be displayed to the administrator of the server on which the Web application is installed. Element description specifies a description of the Web application that might be displayed to the administrator of the server. Element servlet describes a servlet.Element servlet-name is the name for the servlet. Element description specifies a description for this particular servlet. Element servlet-class specifies compiled servlet’s fully qualified class name.
23
2002 Prentice Hall. All rights reserved. Outline Fig. 9.9 Deployment descriptor (web.xml) for the advjhtp1 Web application. Lines 32-35 31 32 33 welcome1 34 /welcome1 35 36 37 Element servlet-mapping specifies servlet-name and url-pattern elements.
24
2002 Prentice Hall. All rights reserved. 9.3.2 Deploying a Web Application (Cont.) Invoke WelcomeServlet example –/advjhtp1/welcome1 /advjhtp1 specifies the context root /welcome1 specifies the URL pattern URL pattern formats –Exact match /advjhtp1/welcome1 –Path mappings /advjhtp1/example/* –Extension mappings *.jsp –Default servlet /advjhtp1/example/
25
2002 Prentice Hall. All rights reserved. 9.3.2 Deploying a Web Application (Cont.)
26
2002 Prentice Hall. All rights reserved. 9.4 Handling HTTP get Requests Containing Data Servlet WelcomeServlet2 –Responds to a get request that contains data
27
2002 Prentice Hall. All rights reserved. Outline Fig. 9.11 WelcomeServlet2 responds to a get request that contains data. Line 16 1 // Fig. 9.11: WelcomeServlet2.java 2 // Processing HTTP get requests containing data. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet2 extends HttpServlet { 10 11 // process "get" request from client 12 protected void doGet( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 String firstName = request.getParameter( "firstname" ); 17 18 response.setContentType( "text/html" ); 19 PrintWriter out = response.getWriter(); 20 21 // send XHTML document to client 22 23 // start XHTML document 24 out.println( " " ); 25 26 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 27 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 28 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 29 30 out.println( 31 " " ); 32 The request object’s getParameter method receives the parameter name and returns the corresponding String value.
28
2002 Prentice Hall. All rights reserved. Outline Fig. 9.11 WelcomeServlet2 responds to a get request that contains data. Line 41 33 // head section of document 34 out.println( " " ); 35 out.println( 36 " Processing get requests with data " ); 37 out.println( " " ); 38 39 // body section of document 40 out.println( " " ); 41 out.println( " Hello " + firstName + ", " ); 42 out.println( "Welcome to Servlets! " ); 43 out.println( " " ); 44 45 // end XHTML document 46 out.println( " " ); 47 out.close(); // close stream to complete the page 48 } 49 } Uses the result of line 16 as part of the response to the client.
29
2002 Prentice Hall. All rights reserved. Outline Fig. 9.12 HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Line 17 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Processing get requests with data 10 11 12 13 14 15 16 Type your first name and press the Submit button 17 18 19 20 21 22 23 Get the first name from the user.
30
2002 Prentice Hall. All rights reserved. Outline Fig. 9.12 HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Program output
31
2002 Prentice Hall. All rights reserved. 9.4 Handling HTTP get Requests Containing Data (Cont.)
32
2002 Prentice Hall. All rights reserved. 9.5 Handling HTTP post Requests HTTP post request –Post data from an HTML form to a server-side form handler –Browsers cache Web pages Servlet WelcomeServlet3 –Responds to a post request that contains data
33
2002 Prentice Hall. All rights reserved. Outline Fig. 9.14 WelcomeServlet3 responds to a post request that contains data. Lines 12-48 1 // Fig. 9.14: WelcomeServlet3.java 2 // Processing post requests containing data. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class WelcomeServlet3 extends HttpServlet { 10 11 // process "post" request from client 12 protected void doPost( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 String firstName = request.getParameter( "firstname" ); 17 18 response.setContentType( "text/html" ); 19 PrintWriter out = response.getWriter(); 20 21 // send XHTML page to client 22 23 // start XHTML document 24 out.println( " " ); 25 26 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 27 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 28 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 29 30 out.println( 31 " " ); 32 Define a doPost method to responds to post requests.
34
2002 Prentice Hall. All rights reserved. Outline WelcomeServlet3. java 33 // head section of document 34 out.println( " " ); 35 out.println( 36 " Processing post requests with data " ); 37 out.println( " " ); 38 39 // body section of document 40 out.println( " " ); 41 out.println( " Hello " + firstName + ", " ); 42 out.println( "Welcome to Servlets! " ); 43 out.println( " " ); 44 45 // end XHTML document 46 out.println( " " ); 47 out.close(); // close stream to complete the page 48 } 49 }
35
2002 Prentice Hall. All rights reserved. Outline Fig. 9.15 HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Lines 13-21 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Handling an HTTP Post Request with Data 10 11 12 13 14 15 16 Type your first name and press the Submit button 17 18 19 20 21 22 23 Provide a form in which the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet3.
36
2002 Prentice Hall. All rights reserved. Outline Fig. 9.15 HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Program output
37
2002 Prentice Hall. All rights reserved. 9.5 Handling HTTP post Requests (Cont.)
38
2002 Prentice Hall. All rights reserved. 9.6 Redirecting Requests to Other Resources Servlet RedirectServlet –Redirects the request to a different resource
39
2002 Prentice Hall. All rights reserved. Outline Fig. 9.17 Redirecting requests to other resources. Line 16 Lines 20-24 Line 21 Line 24 Lines 29-56 1 // Fig. 9.17: RedirectServlet.java 2 // Redirecting a user to a different Web page. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 9 public class RedirectServlet extends HttpServlet { 10 11 // process "get" request from client 12 protected void doGet( HttpServletRequest request, 13 HttpServletResponse response ) 14 throws ServletException, IOException 15 { 16 String location = request.getParameter( "page" ); 17 18 if ( location != null ) 19 20 if ( location.equals( "deitel" ) ) 21 response.sendRedirect( "http://www.deitel.com" ); 22 else 23 if ( location.equals( "welcome1" ) ) 24 response.sendRedirect( "welcome1" ); 25 26 // code that executes only if this servlet 27 // does not redirect the user to another page 28 29 response.setContentType( "text/html" ); 30 PrintWriter out = response.getWriter(); 31 Obtains the page parameter from the request. Determine if the value is either “deitel” or “welcome1” Redirects the request to www.deitel.com. Redirects the request to the servlet WelcomeServlet. Output a Web page indicating that an invalid request was made if method sendRedirect is not called.
40
2002 Prentice Hall. All rights reserved. Outline Fig. 9.17 Redirecting requests to other resources. 32 // start XHTML document 33 out.println( " " ); 34 35 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 36 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 37 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 38 39 out.println( 40 " " ); 41 42 // head section of document 43 out.println( " " ); 44 out.println( " Invalid page " ); 45 out.println( " " ); 46 47 // body section of document 48 out.println( " " ); 49 out.println( " Invalid page requested " ); 50 out.println( " <a href = " + 51 "\"servlets/RedirectServlet.html\">" ); 52 out.println( "Click here to choose again " ); 53 out.println( " " ); 54 55 // end XHTML document 56 out.println( " " ); 57 out.close(); // close stream to complete the page 58 } 59 }
41
2002 Prentice Hall. All rights reserved. Outline Fig. 9.18 RedirectServlet. html document to demonstrate redirecting requests to other resources. Lines 15-16 Lines 17-18 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Redirecting a Request to Another Site 10 11 12 13 Click a link to be redirected to the appropriate page 14 15 16 www.deitel.com 17 18 Welcome servlet 19 20 21 Provide hyperlinks that allow the user to invoke the servlet RedirectServlet.
42
2002 Prentice Hall. All rights reserved. Outline Fig. 9.18 RedirectServlet. html document to demonstrate redirecting requests to other resources. Program output
43
2002 Prentice Hall. All rights reserved. 9.6 Redirecting Requests to other Resources (Cont.)
44
2002 Prentice Hall. All rights reserved. 9.7 Session Tracking Personalization Privacy invasion HTTP – stateless protocol –Does not support persistent information Track clients individually –Cookies –Session tracking –hidden type input –URL rewriting
45
2002 Prentice Hall. All rights reserved. 9.7.1 Cookies Stored on the user’s computer for retrieval later Text-based data sent by servlets Maximum age of a cookie Deleted automatically when they expire Servlet CookieServlet –Handles both get and post requests
46
2002 Prentice Hall. All rights reserved. Outline Fig. 9.20 Storing user data on the client computer with cookies. Lines 14-20 Line 28 Line 29 Line 30 Line 32 1 // Fig. 9.20: CookieServlet.java 2 // Using cookies to store data on the client computer. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import java.util.*; 9 10 public class CookieServlet extends HttpServlet { 11 private final Map books = new HashMap(); 12 13 // initialize Map books 14 public void init() 15 { 16 books.put( "C", "0130895725" ); 17 books.put( "C++", "0130895717" ); 18 books.put( "Java", "0130125075" ); 19 books.put( "VB6", "0134569555" ); 20 } 21 22 // receive language selection and send cookie containing 23 // recommended book to the client 24 protected void doPost( HttpServletRequest request, 25 HttpServletResponse response ) 26 throws ServletException, IOException 27 { 28 String language = request.getParameter( "language" ); 29 String isbn = books.get( language ).toString(); 30 Cookie cookie = new Cookie( language, isbn ); 31 32 response.addCookie( cookie ); // must precede getWriter 33 response.setContentType( "text/html" ); 34 PrintWriter out = response.getWriter(); 35 Method init populates books with four key/value pair of books. Uses method getParameter to obtain the user’s language selection. Gets the ISBN number for the selected language from books. Creates a new Cookie object, using the language and isbn values as the cookie name and cookie value, respectively. Adds the cookie to the response with method addCookie of interface HttpServletResponse.
47
2002 Prentice Hall. All rights reserved. Outline Fig. 9.20 Storing user data on the client computer with cookies. 36 // send XHTML page to client 37 38 // start XHTML document 39 out.println( " " ); 40 41 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 42 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 43 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 44 45 out.println( 46 " " ); 47 48 // head section of document 49 out.println( " " ); 50 out.println( " Welcome to Cookies " ); 51 out.println( " " ); 52 53 // body section of document 54 out.println( " " ); 55 out.println( " Welcome to Cookies! You selected " + 56 language + " " ); 57 58 out.println( " <a href = " + 59 "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" + 60 "Click here to choose another language " ); 61 62 out.println( " " + 63 "Click here to get book recommendations " ); 64 out.println( " " ); 65 66 // end XHTML document 67 out.println( " " ); 68 out.close(); // close stream 69 } 70
48
2002 Prentice Hall. All rights reserved. Outline Fig. 9.20 Storing user data on the client computer with cookies. Line 77 71 // read cookies from client and create XHTML document 72 // containing recommended books 73 protected void doGet( HttpServletRequest request, 74 HttpServletResponse response ) 75 throws ServletException, IOException 76 { 77 Cookie cookies[] = request.getCookies(); // get cookies 78 79 response.setContentType( "text/html" ); 80 PrintWriter out = response.getWriter(); 81 82 // start XHTML document 83 out.println( " " ); 84 85 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 86 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 87 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 88 89 out.println( 90 " " ); 91 92 // head section of document 93 out.println( " " ); 94 out.println( " Recommendations " ); 95 out.println( " " ); 96 97 // body section of document 98 out.println( " " ); 99 100 // if there are any cookies, recommend a book for each ISBN 101 if ( cookies != null && cookies.length != 0 ) { 102 out.println( " Recommendations " ); 103 out.println( " " ); 104 Retrieves the cookies from the client using HttpServletRequest method getCookies, which returns an array of Cookie objects.
49
2002 Prentice Hall. All rights reserved. Outline Fig. 9.20 Storing user data on the client computer with cookies. 105 // get the name of each cookie 106 for ( int i = 0; i < cookies.length; i++ ) 107 out.println( cookies[ i ].getName() + 108 " How to Program. ISBN#: " + 109 cookies[ i ].getValue() + " " ); 110 111 out.println( " " ); 112 } 113 else { // there were no cookies 114 out.println( " No Recommendations " ); 115 out.println( " You did not select a language. " ); 116 } 117 118 out.println( " " ); 119 120 // end XHTML document 121 out.println( " " ); 122 out.close(); // close stream 123 } 124 }
50
2002 Prentice Hall. All rights reserved. Outline Fig. 9.21 CookieSelectLang uage.html document for selecting a programming language and posting the data to the CookieServlet. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Using Cookies 10 11 12 13 14 15 Select a programming language: 16 17 <input type = "radio" name = "language" 18 value = "C" />C 19 20 <input type = "radio" name = "language" 21 value = "C++" />C++ 22 23 24 <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java 26 27 <input type = "radio" name = "language" 28 value = "VB6" />VB 6 29 30 31 32 33 34 35
51
2002 Prentice Hall. All rights reserved. Outline Fig. 9.21 CookieSelectLang uage.html document for selecting a programming language and posting the data to the CookieServlet. Program output
52
2002 Prentice Hall. All rights reserved. Outline Fig. 9.21 CookieSelectLang uage.html document for selecting a programming language and posting the data to the CookieServlet. Program output
53
2002 Prentice Hall. All rights reserved. 9.7.1 Cookies (Cont.)
54
2002 Prentice Hall. All rights reserved. 9.7.1 Cookies (Cont.) Fig. 9.23 (Part 1 of 2)Important methods of class Cookie.
55
2002 Prentice Hall. All rights reserved. 9.7.1 Cookies (Cont.)
56
2002 Prentice Hall. All rights reserved. 9.7.2 Session Tracking with HttpSession Interface HttpSession –Supports session tracking Servlet SessionServlet –Uses HttpSession objects –Handles both get and post requests
57
2002 Prentice Hall. All rights reserved. Outline Fig. 9.24 Maintaining state information with HttpSession objects. Line 28 Line 32 Line 35 1 // Fig. 9.24: SessionServlet.java 2 // Using HttpSession to maintain client state information. 3 package com.deitel.advjhtp1.servlets; 4 5 import javax.servlet.*; 6 import javax.servlet.http.*; 7 import java.io.*; 8 import java.util.*; 9 10 public class SessionServlet extends HttpServlet { 11 private final Map books = new HashMap(); 12 13 // initialize Map books 14 public void init() 15 { 16 books.put( "C", "0130895725" ); 17 books.put( "C++", "0130895717" ); 18 books.put( "Java", "0130125075" ); 19 books.put( "VB6", "0134569555" ); 20 } 21 22 // receive language selection and create HttpSession object 23 // containing recommended book for the client 24 protected void doPost( HttpServletRequest request, 25 HttpServletResponse response ) 26 throws ServletException, IOException 27 { 28 String language = request.getParameter( "language" ); 29 30 // Get the user's session object. 31 // Create a session (true) if one does not exist. 32 HttpSession session = request.getSession( true ); 33 34 // add a value for user's choice to session 35 session.setAttribute( language, books.get( language ) ); Gets the user’s language selection. Uses method getSession of interface HttpServletRequest to obtain the HttpSession object for the client. Uses setAttribute to put the language and the corresponding recommended book’s ISBN number into the HttpSession object.
58
2002 Prentice Hall. All rights reserved. Outline Fig. 9.24 Maintaining state information with HttpSession objects. Line 64 Line 67 36 37 response.setContentType( "text/html" ); 38 PrintWriter out = response.getWriter(); 39 40 // send XHTML page to client 41 42 // start XHTML document 43 out.println( " " ); 44 45 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 46 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 47 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 48 49 out.println( 50 " " ); 51 52 // head section of document 53 out.println( " " ); 54 out.println( " Welcome to Sessions " ); 55 out.println( " " ); 56 57 // body section of document 58 out.println( " " ); 59 out.println( " Welcome to Sessions! You selected " + 60 language + ". " ); 61 62 // display information about the session 63 out.println( " Your unique session ID is: " + 64 session.getId() + " " ); 65 66 out.println( 67 "This " + ( session.isNew() ? "is" : "is not" ) + 68 " a new session " ); 69 Uses HttpSession method getID to obtain the session’s unique ID number. Determines whether the session is new or already exists with method isNew.
59
2002 Prentice Hall. All rights reserved. Outline Fig. 9.24 Maintaining state information with HttpSession objects. Line 71 Line 74 Line 77 Line 100 70 out.println( "The session was created at: " + 71 new Date( session.getCreationTime() ) + " " ); 72 73 out.println( "You last accessed the session at: " + 74 new Date( session.getLastAccessedTime() ) + " " ); 75 76 out.println( "The maximum inactive interval is: " + 77 session.getMaxInactiveInterval() + " seconds " ); 78 79 out.println( " <a href = " + 80 "\"servlets/SessionSelectLanguage.html\">" + 81 "Click here to choose another language " ); 82 83 out.println( " " + 84 "Click here to get book recommendations " ); 85 out.println( " " ); 86 87 // end XHTML document 88 out.println( " " ); 89 out.close(); // close stream 90 } 91 92 // read session attributes and create XHTML document 93 // containing recommended books 94 protected void doGet( HttpServletRequest request, 95 HttpServletResponse response ) 96 throws ServletException, IOException 97 { 98 // Get the user's session object. 99 // Do not create a session (false) if one does not exist. 100 HttpSession session = request.getSession( false ); 101 102 // get names of session object's values 103 Enumeration valueNames; 104 Obtains the time at which the session was created with method getCreationTime. Obtains the time at which the session was last accessed with method getLastAccessedTime. Uses method getMaxInactiveInterval to obtain the maximum amount of time that an HttpSession object can be inactive before the servlet container discards it. Obtains the HttpSession object for the client with method getSession.
60
2002 Prentice Hall. All rights reserved. Outline Fig. 9.24 Maintaining state information with HttpSession objects. Line 106 105 if ( session != null ) 106 valueNames = session.getAttributeNames(); 107 else 108 valueNames = null; 109 110 PrintWriter out = response.getWriter(); 111 response.setContentType( "text/html" ); 112 113 // start XHTML document 114 out.println( " " ); 115 116 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 117 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 118 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 119 120 out.println( 121 " " ); 122 123 // head section of document 124 out.println( " " ); 125 out.println( " Recommendations " ); 126 out.println( " " ); 127 128 // body section of document 129 out.println( " " ); 130 131 if ( valueNames != null && 132 valueNames.hasMoreElements() ) { 133 out.println( " Recommendations " ); 134 out.println( " " ); 135 136 String name, value; 137 Uses HttpSession method getAttributeNames to retrieve an Enumeration of the attribute names.
61
2002 Prentice Hall. All rights reserved. Outline Fig. 9.24 Maintaining state information with HttpSession objects. Line 141 138 // get value for each name in valueNames 139 while ( valueNames.hasMoreElements() ) { 140 name = valueNames.nextElement().toString(); 141 value = session.getAttribute( name ).toString(); 142 143 out.println( name + " How to Program. " + 144 "ISBN#: " + value + " " ); 145 } 146 147 out.println( " " ); 148 } 149 else { 150 out.println( " No Recommendations " ); 151 out.println( " You did not select a language. " ); 152 } 153 154 out.println( " " ); 155 156 // end XHTML document 157 out.println( " " ); 158 out.close(); // close stream 159 } 160 } Invokes method getAttribute of HttpSession to retrieve the ISBN of a book from the HttpSession object.
62
2002 Prentice Hall. All rights reserved. Outline Fig. 9.25 SessionSelectLan guage.html document for selecting a programming language and posting the data to the SessionServlet. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Using Sessions 10 11 12 13 14 15 Select a programming language: 16 17 <input type = "radio" name = "language" 18 value = "C" />C 19 20 <input type = "radio" name = "language" 21 value = "C++" />C++ 22 23 24 <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java 26 27 <input type = "radio" name = "language" 28 value = "VB6" />VB 6 29 30 31 32 33 34 35
63
2002 Prentice Hall. All rights reserved. Outline Fig. 9.25 SessionSelectLan guage.html document for selecting a programming language and posting the data to the SessionServlet. Program output
64
2002 Prentice Hall. All rights reserved. Outline Fig. 9.25 SessionSelectLan guage.html document for selecting a programming language and posting the data to the SessionServlet. Program output
65
2002 Prentice Hall. All rights reserved. Outline Fig. 9.25 SessionSelectLan guage.html document for selecting a programming language and posting the data to the SessionServlet. Program output
66
2002 Prentice Hall. All rights reserved. Outline Fig. 9.25 SessionSelectLan guage.html document for selecting a programming language and posting the data to the SessionServlet. Program output
67
2002 Prentice Hall. All rights reserved. 9.7.2 Session Tracking with HttpSession (Cont.)
68
2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business logic –Database access Web servers often represent the middle tier Three-tier distributed application example –SurveyServlet –Survey.html –Cloudscape database
69
2002 Prentice Hall. All rights reserved. Outline Fig. 9.27 Multi- tier Web-based survey using XHTML, servlets and JDBC. Lines 16-54 Line 21 Lines 22-23 Lines 27-31 1 // Fig. 9.27: SurveyServlet.java 2 // A Web-based survey that uses JDBC from a servlet. 3 package com.deitel.advjhtp1.servlets; 4 5 import java.io.*; 6 import java.text.*; 7 import java.sql.*; 8 import javax.servlet.*; 9 import javax.servlet.http.*; 10 11 public class SurveyServlet extends HttpServlet { 12 private Connection connection; 13 private PreparedStatement updateVotes, totalVotes, results; 14 15 // set up database connection and prepare SQL statements 16 public void init( ServletConfig config ) 17 throws ServletException 18 { 19 // attempt database connection and create PreparedStatements 20 try { 21 Class.forName( "COM.cloudscape.core.RmiJdbcDriver" ); 22 connection = DriverManager.getConnection( 23 "jdbc:rmi:jdbc:cloudscape:animalsurvey" ); 24 25 // PreparedStatement to add one to vote total for a 26 // specific animal 27 updateVotes = 28 connection.prepareStatement( 29 "UPDATE surveyresults SET votes = votes + 1 " + 30 "WHERE id = ?" 31 ); 32 Servlets are initialized by overriding method init. Loads the database driver. Attempt to open a connection to the animalsurvey database. Create PreparedStatement updateVotes object.
70
2002 Prentice Hall. All rights reserved. Outline Fig. 9.27 Multi- tier Web-based survey using XHTML, servlets and JDBC. Lines 34-44 33 // PreparedStatement to sum the votes 34 totalVotes = 35 connection.prepareStatement( 36 "SELECT sum( votes ) FROM surveyresults" 37 ); 38 39 // PreparedStatement to obtain surveyoption table's data 40 results = 41 connection.prepareStatement( 42 "SELECT surveyoption, votes, id " + 43 "FROM surveyresults ORDER BY id" 44 ); 45 } 46 47 // for any exception throw an UnavailableException to 48 // indicate that the servlet is not currently available 49 catch ( Exception exception ) { 50 exception.printStackTrace(); 51 throw new UnavailableException(exception.getMessage()); 52 } 53 54 } // end of init method 55 56 // process survey response 57 protected void doPost( HttpServletRequest request, 58 HttpServletResponse response ) 59 throws ServletException, IOException 60 { 61 // set up response to client 62 response.setContentType( "text/html" ); 63 PrintWriter out = response.getWriter(); 64 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 65 Create PreparedStatement totalVotes and results objects.
71
2002 Prentice Hall. All rights reserved. Outline Fig. 9.27 Multi- tier Web-based survey using XHTML, servlets and JDBC. Lines 80-81 Lines 87-88 Lines 91-93 Lines 96-123 66 // start XHTML document 67 out.println( " " ); 68 69 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + 70 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + 71 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 72 73 out.println( 74 " " ); 75 76 // head section of document 77 out.println( " " ); 78 79 // read current survey response 80 int value = 81 Integer.parseInt( request.getParameter( "animal" ) ); 82 83 // attempt to process a vote and display current results 84 try { 85 86 // update total for current surevy response 87 updateVotes.setInt( 1, value ); 88 updateVotes.executeUpdate(); 89 90 // get total of all survey responses 91 ResultSet totalRS = totalVotes.executeQuery(); 92 totalRS.next(); 93 int total = totalRS.getInt( 1 ); 94 95 // get results 96 ResultSet resultsRS = results.executeQuery(); 97 out.println( " Thank you! " ); 98 out.println( " " ); 99 Obtain the survey response Set the first parameter of PreparedStatement updateVotes to the survey response and update the database. Execute PreparedStatement totalVotes to retrieve the total number of votes received. Execute PreparedStatement results and process the ResultSet to create the survey summary for the client.
72
2002 Prentice Hall. All rights reserved. Outline Fig. 9.27 Multi- tier Web-based survey using XHTML, servlets and JDBC. 100 out.println( " " ); 101 out.println( " Thank you for participating." ); 102 out.println( " Results: " ); 103 104 // process results 105 int votes; 106 107 while ( resultsRS.next() ) { 108 out.print( resultsRS.getString( 1 ) ); 109 out.print( ": " ); 110 votes = resultsRS.getInt( 2 ); 111 out.print( twoDigits.format( 112 ( double ) votes / total * 100 ) ); 113 out.print( "% responses: " ); 114 out.println( votes ); 115 } 116 117 resultsRS.close(); 118 119 out.print( "Total responses: " ); 120 out.print( total ); 121 122 // end XHTML document 123 out.println( " " ); 124 out.close(); 125 } 126 127 // if database exception occurs, return error page 128 catch ( SQLException sqlException ) { 129 sqlException.printStackTrace(); 130 out.println( " Error " ); 131 out.println( " " ); 132 out.println( " Database error occurred. " ); 133 out.println( "Try again later. " ); 134 out.close();
73
2002 Prentice Hall. All rights reserved. Outline Fig. 9.27 Multi- tier Web-based survey using XHTML, servlets and JDBC. Lines 140-154 135 } 136 137 } // end of doPost method 138 139 // close SQL statements and database when servlet terminates 140 public void destroy() 141 { 142 // attempt to close statements and database connection 143 try { 144 updateVotes.close(); 145 totalVotes.close(); 146 results.close(); 147 connection.close(); 148 } 149 150 // handle database exceptions by returning error to client 151 catch( SQLException sqlException ) { 152 sqlException.printStackTrace(); 153 } 154 } // end of destroy method 155 } Method destroy closes each PreparedStatement and database connection.
74
2002 Prentice Hall. All rights reserved. Outline Fig. 9.28 Survey.html document that allows users to submit survey responses to SurveyServlet. 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 Survey 10 11 12 13 14 15 What is your favorite pet? 16 17 18 <input type = "radio" name = "animal" 19 value = "1" />Dog 20 <input type = "radio" name = "animal" 21 value = "2" />Cat 22 <input type = "radio" name = "animal" 23 value = "3" />Bird 24 <input type = "radio" name = "animal" 25 value = "4" />Snake 26 <input type = "radio" name = "animal" 27 value = "5" checked = "checked" />None 28 29 30 31 32 33 34
75
2002 Prentice Hall. All rights reserved. Outline Fig. 9.28 Survey.html document that allows users to submit survey responses to SurveyServlet.
76
2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet (Cont.)
77
2002 Prentice Hall. All rights reserved. 9.9 HttpUtils Class
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.