Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and.

Similar presentations


Presentation on theme: " 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and."— Presentation transcript:

1  2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and Architecture 30.2.1 Interface Servlet and the Servlet Life Cycle 30.2.2 HttpServlet Class 30.2.3 HttpServletRequest Interface 30.2.4 HttpServletResponse Interface 30.3 Handling HTTP get Requests 30.3.1 Setting Up the Apache Tomcat Server 30.3.2 Deploying a Web Application 30.4 Handling HTTP get Requests Containing Data 30.5 Handling HTTP post Requests 30.6 Redirecting Requests to Other Resources 30.7 Session Tracking 30.7.1 Cookies 30.7.2 Session Tracking with HttpSession 30.8 Multi-tier Applications: Using JDBC from a Servlet 30.9 HttpUtils Class 30.10 Internet and World Wide Web Resources

2  2001 Prentice Hall, Inc. All rights reserved. 2 30.1 Introduction Java Networking –Fundamental capabilities Network connections are sockets Contained in package java.net –Higher-level packages Java.rmi (Remote Method Invocation classes) –Allows JVMs to communicate via remote method calls –Based on capabilities of package java.net Org.omg (Contains CORBA classes) –Allows any two CORBA enabled applications to communicate.

3  2001 Prentice Hall, Inc. All rights reserved. 3 30.1 Introduction Client-Server Relationship –Client sends request, server responds Common implemetation – comunication between Web Server and Web Browser

4  2001 Prentice Hall, Inc. All rights reserved. 4 30.1 Introduction Servlets –Extend server functionality Often used with Web Servers –To generate dynamic XHTML –To provide secure access –To interact with a database –Packages javax.servlet, javax.servlet.http Provide classes and interfaces for servlets

5  2001 Prentice Hall, Inc. All rights reserved. 5 30.2 Servlet Overview and Architecture Hypertext Transfer Protocol –Basis to World Wide Web Communication –Uses URIs (Uniform Resource Identifiers) URIs locate resources on internet

6  2001 Prentice Hall, Inc. All rights reserved. 6 30.2 Servlet Overview and Architecture Servlet Containers (Servlet Engines) –Provide servlet runtime environment –Manage servlet lifecycle –Incorporated in many popular web servers Microsoft Internet Information Server (IIS) Apache HTTP Server Many more –Redirects HTTP requests to appropriate servlet

7  2001 Prentice Hall, Inc. All rights reserved. 7 30.2.1 Interface Servlet and the Servlet Life Cycle Interface Servlet –In package javax.servlet –Must be implemented by all servlets –Servlet methods automatically invoked by servlet container

8  2001 Prentice Hall, Inc. All rights reserved. 8 30.2.1 Interface Servlet and the Servlet Life Cycle

9  2001 Prentice Hall, Inc. All rights reserved. 9 30.2.1 Interface Servlet and the Servlet Life Cycle Servlet Container Manages Life Cycle –Invokes method init when servlet is initially loaded Usually in response to its first request –Invokes method service to handle request Servlet processes request –Obtains request from ServletRequest object Servlet responds to client –Writes to ServletResponse object Called once per request –Invokes method destroy to terminate servlet Releases servlet resources

10  2001 Prentice Hall, Inc. All rights reserved. 10 30.2.1 Interface Servlet and the Servlet Life Cycle Servlet Abstract Implementations –Provide default Servlet implementations GenericServlet –Package javax.servlet –Used in non-web servlets HttpServlet –Package javax.servlet.http –Used for Web-based servlets –Defines enhanced Web processing capabilities

11  2001 Prentice Hall, Inc. All rights reserved. 11 30.2.2 HttpServlet Class Class HttpServlet –Overrides method service Differentiates between HTTP get and post requests –Defines methods doGet and doPost to process requests Receives HttpServletRequest and HttpServletResponse objects

12  2001 Prentice Hall, Inc. All rights reserved. 12 30.2.2 HttpServlet Class

13  2001 Prentice Hall, Inc. All rights reserved. 13 30.2.3 HttpServletRequest Interface Interface HttpServletRequest –Created by servlet container and passed to service method HttpServlet relays the object to doGet or doPost –Contains client request and request processing methods

14  2001 Prentice Hall, Inc. All rights reserved. 14 30.2.3 HttpServletRequest Interface

15  2001 Prentice Hall, Inc. All rights reserved. 15 30.2.4 HttpServletResponse Interface Interface HttpServletResponse –Created by servlet container and passed to service method HttpServlet relays the object to doGet or doPost –Provides methods to formulate responses

16  2001 Prentice Hall, Inc. All rights reserved. 16 30.2.4 HTTP ServletResponse Interface

17  2001 Prentice Hall, Inc. All rights reserved. 17 30.3 Handling HTTP get Requests HTTP get Request –Primarily used to retrieve content of a URI Usually HTML or XHTML Can be images or binary data

18  2001 Prentice Hall, Inc. All rights reserved. 18 Upcoming example demonstrates get request handling

19  2001 Prentice Hall, Inc. All rights reserved. Outline 19 WelcomeServlet.j ava Define WelcomeServlet doGet 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 Extends HttpServlet to create a Web- based Servlet. Process get request by creating an XHTML document.

20  2001 Prentice Hall, Inc. All rights reserved. Outline 20 WelcomeServlet.j ava 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 }

21  2001 Prentice Hall, Inc. All rights reserved. Outline 21 WelcomeServlet.h tml 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 Main XHTML page which sends a get request to the servlet.

22  2001 Prentice Hall, Inc. All rights reserved. Outline 22 WelcomeServlet.java

23  2001 Prentice Hall, Inc. All rights reserved. 23 30.3.1 Setting up the Apache Tomcat Server Tomcat –Fully functional JSP and Servlet container –Includes a Web Server –Integrates with popular Web Servers Apache Web Server Microsoft Internet Information Server (IIS) –Default Port is 8080

24  2001 Prentice Hall, Inc. All rights reserved. 24 Testing and Debugging Tip 30.1 Fig. 30.7Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)

25  2001 Prentice Hall, Inc. All rights reserved. 25 30.3.2 Deploying a Web Application Web Application –Consists of JSPs and servlets –Rigid directory structure Often within a Web Application Archive (WAR) –Configured via deployment descriptor Web.xml –Maps servlet name and location –Defines URL pattern

26  2001 Prentice Hall, Inc. All rights reserved. 26 30.3.2 Deploying a Web Application

27  2001 Prentice Hall, Inc. All rights reserved. Outline 27 1 2 <Context path = "/advjhtp1" 3 docBase = "webapps/advjhtp1" 4 reloadable = "true"> 5 Fig. 30.9Context element for servlet and JSP examples in Chapters 30 and 31.

28  2001 Prentice Hall, Inc. All rights reserved. Outline 28 Web.xml Map servlet name and class Map servlet name and URL 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 31 32 33 welcome1 Maps a servlet name to its fully qualified class name.

29  2001 Prentice Hall, Inc. All rights reserved. Outline 29 34 /welcome1 35 36 37 Fig. 30.10Deployment descriptor for the advjhtp1 Web application. Map servlet to URL pattern. The pattern is relative to the server address and application context root.

30  2001 Prentice Hall, Inc. All rights reserved. 30 30.3.2 Deploying a Web Application

31  2001 Prentice Hall, Inc. All rights reserved. 31 30.4 Handling HTTP get Requests Containing Data Requests and Data –Http request follows the format Servlet_url ? query_string –Query string format Parameter_name = value Name/value pairs separated by &

32  2001 Prentice Hall, Inc. All rights reserved. Outline 32 WelcomeServlet2. java Define Servlet WelcomeServlet2 Write XHTML response 1 // Fig. 9.12: 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 33 // head section of document 34 out.println( " " ); Obtain the parameter from the request and assign the value to a string.

33  2001 Prentice Hall, Inc. All rights reserved. Outline 33 WelcomeServlet2. java 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 } Include the value in the response.

34  2001 Prentice Hall, Inc. All rights reserved. Outline 34 WelcomeServlet2. html Send get request 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

35  2001 Prentice Hall, Inc. All rights reserved. Outline 35 Program Output

36  2001 Prentice Hall, Inc. All rights reserved. 36 30.4 Handling HTTP get Requests Containing Data

37  2001 Prentice Hall, Inc. All rights reserved. 37 30.5 Handling HTTP post Requests HTTP post Request –Posts data from HTML form Server-side form handler parses data –Not cached Ensures client has most updated version –Default HttpServlet doPost method disables post

38  2001 Prentice Hall, Inc. All rights reserved. Outline 38 WelcomeServlet3. java Define Servlet WelcomeServlet3 Handle doPost Write XHTML response 1 // Fig. 9.15: 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 33 // head section of document 34 out.println( " " ); Obtain the firstname parameter from the post request.

39  2001 Prentice Hall, Inc. All rights reserved. Outline 39 WelcomeServlet3. java 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 }

40  2001 Prentice Hall, Inc. All rights reserved. Outline 40 WelcomeServlet3. html 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 Submit a post request with a firstname parameter

41  2001 Prentice Hall, Inc. All rights reserved. Outline 41 Program Output

42  2001 Prentice Hall, Inc. All rights reserved. 42 30.5 Handling HTTP post Requests

43  2001 Prentice Hall, Inc. All rights reserved. 43 30.6 Redirecting Requests to Other Resources Redirection –Allows a Servlet to redirect a request –Use sendRedirect method of HttpServletResponse

44  2001 Prentice Hall, Inc. All rights reserved. Outline 44 RedirectServlet. java Define Servlet RedirectServlet Process get request 1 // Fig. 9.18: 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 32 // start XHTML document 33 out.println( " " ); Obtain the page parameter for redirection location. Redirect user to another page or servlet.

45  2001 Prentice Hall, Inc. All rights reserved. Outline 45 RedirectServlet. java Create error page 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 }

46  2001 Prentice Hall, Inc. All rights reserved. Outline 46 RedirectServlet. html 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 Send get request to RedirectServlet with the page parameter.

47  2001 Prentice Hall, Inc. All rights reserved. Outline 47 Program Output

48  2001 Prentice Hall, Inc. All rights reserved. 48 30.6 Redirecting Requests to Other Resources

49  2001 Prentice Hall, Inc. All rights reserved. 49 30.7 Session Tracking Session Tracking –Information techniques Track consumer internet movement Integrate user supplied information –Personalization benefits Product targeting Individualized attention Bypass irrelevant content –Tracking pitfalls Privacy issues Security of sensitive information

50  2001 Prentice Hall, Inc. All rights reserved. 50 30.7 Session Tracking Tracking Technologies –Cookies Section 30.7.1 –Session tracking Section 30.7.2 –URL rewriting Information embedded in URL parameters –Hidden form elements Information contained in hidden form elements Each form retains previous form information

51  2001 Prentice Hall, Inc. All rights reserved. 51 30.7.1 Cookies Cookies –Small text data files –Often contain unique user identifiers Locates server-side client information –Transmitted in HTTP header information –Persists for browsing session or maximum age Expires when maximum age reached Lasts for browsing session by default

52  2001 Prentice Hall, Inc. All rights reserved. Outline 52 CookieServlet.ja va Define Servlet CookieServlet Init book ISBN doPost writes cookie 1 // Fig. 9.21: 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 Create a new cookie containing the client language and ordered book ISBN number.

53  2001 Prentice Hall, Inc. All rights reserved. Outline 53 CookieServlet.ja va Write XHTML response 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

54  2001 Prentice Hall, Inc. All rights reserved. Outline 54 CookieServlet.ja va doGet process get request Obtain user cookies 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 105 // get the name of each cookie Get any cookies from client.

55  2001 Prentice Hall, Inc. All rights reserved. Outline 55 CookieServlet.ja va 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 } Cycle through cookies and display book recommendation.

56  2001 Prentice Hall, Inc. All rights reserved. Outline 56 CookieSelectLang uage.html Static XHTML page 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 Post user selected language.

57  2001 Prentice Hall, Inc. All rights reserved. Outline 57 Program Output

58  2001 Prentice Hall, Inc. All rights reserved. Outline 58 Program Output

59  2001 Prentice Hall, Inc. All rights reserved. Outline 59 Program Output

60  2001 Prentice Hall, Inc. All rights reserved. 60 30.7.1 Cookies

61  2001 Prentice Hall, Inc. All rights reserved. 61 30.7.1 Cookies

62  2001 Prentice Hall, Inc. All rights reserved. 62 30.7.1 Cookies

63  2001 Prentice Hall, Inc. All rights reserved. 63 30.7.2 Session Tracking with HttpSession HttpSession interface –Assigns a unique ID to user –Stores name/value pairs, attributes Values are any Java object –Expire Browser Session ends Servlet invalidate d Servlet container restart

64  2001 Prentice Hall, Inc. All rights reserved. Outline 64 SessionServlet.j ava Define Servlet SessionServlet 1 // Fig. 9.25: 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 Obtain client session, if the client does not have a session, create one.

65  2001 Prentice Hall, Inc. All rights reserved. Outline 65 SessionServlet.j ava Process post request 35 session.setAttribute( language, books.get( language ) ); 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

66  2001 Prentice Hall, Inc. All rights reserved. Outline 66 SessionServlet.j ava process get request 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 Obtain the client session, but do not create one if it does not exist.

67  2001 Prentice Hall, Inc. All rights reserved. Outline 67 SessionServlet.j ava 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 138 // get value for each name in valueNames 139 while ( valueNames.hasMoreElements() ) { Obtain the attributes of the client. Then display any recommendations.

68  2001 Prentice Hall, Inc. All rights reserved. Outline 68 SessionServlet.j ava 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 }

69  2001 Prentice Hall, Inc. All rights reserved. Outline 69 SessionSelectLan guage.html 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 XHTML page that allows the client to select a programming language they would like a recommendation for.

70  2001 Prentice Hall, Inc. All rights reserved. Outline 70 Program Output

71  2001 Prentice Hall, Inc. All rights reserved. Outline 71 Program Output

72  2001 Prentice Hall, Inc. All rights reserved. Outline 72 Program Output

73  2001 Prentice Hall, Inc. All rights reserved. 73 30.7.2 Session Tracking with HttpSession

74  2001 Prentice Hall, Inc. All rights reserved. 74 30.8 Multi-tier Applications: Using JDBC from a Servlet Multi-tier Architecture –Client Commonly Web browser –XHTML –HTML –Applet –Middle Tier Logic component examples: –Servlets –JSPs Provides interface between client and database

75  2001 Prentice Hall, Inc. All rights reserved. 75 30.8 Multi-tier Applications: Using JDBC from a Servlet Multi-tier Architecture –Backend tier Usually a Database –Accessed via JDBC from servlets Stores information –Client information –Product information

76  2001 Prentice Hall, Inc. All rights reserved. 76 30.8 Multi-tier Applications: Using JDBC from a Servlet Java Database Connectivity (JDBC) –Provides uniform access to database systems Middle tier will work with any JDBC database Developer not required to write for a specific database Works with SQL-based queries Database interaction handled by JDBC driver –Driver usually provided by database vendor

77  2001 Prentice Hall, Inc. All rights reserved. Outline 77 SurveyServlet.ja va Define servlet SurveyServlet set up database 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 33 // PreparedStatement to sum the votes 34 totalVotes = 35 connection.prepareStatement( Specify database driver. Connect to database through that driver. Define SQL query to obtain database information

78  2001 Prentice Hall, Inc. All rights reserved. Outline 78 SurveyServlet.ja va handle post request 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 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" +

79  2001 Prentice Hall, Inc. All rights reserved. Outline 79 SurveyServlet.ja va 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 survey 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 100 out.println( " " ); 101 out.println( " Thank you for participating." ); 102 out.println( " Results: " ); 103 104 // process results 105 int votes; Update database with post parameter. Obtain the survey totals and information via SQL requests.

80  2001 Prentice Hall, Inc. All rights reserved. Outline 80 SurveyServlet.ja va 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(); 135 } 136 137 } // end of doPost method 138 139 // close SQL statements and database when servlet terminates 140 public void destroy() Display results in XHTML response.

81  2001 Prentice Hall, Inc. All rights reserved. Outline 81 SurveyServlet.ja va Close database 141 { 142 // attempt to close statements and database connection 143 try { 144 updateVo\tes.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 }

82  2001 Prentice Hall, Inc. All rights reserved. Outline 82 Survey.html 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 Static survey XHTML page.

83  2001 Prentice Hall, Inc. All rights reserved. Outline 83 Program Output

84  2001 Prentice Hall, Inc. All rights reserved. 84 30.8.1 Configuring animalsurvey Database and SurveyServlet

85  2001 Prentice Hall, Inc. All rights reserved. 85 30.9 HttpUtils Class HttpUtils Class –Three static utility methods to simplify servlet development

86  2001 Prentice Hall, Inc. All rights reserved. 86 30.9 HttpUtils Class


Download ppt " 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers Outline 30.1 Introduction 30.2 Servlet Overview and."

Similar presentations


Ads by Google