2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers...

86
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

Transcript of 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Servlets: Bonus for Java Developers...

2001 Prentice Hall, Inc. All rights reserved.

1

Chapter 30 - Servlets: Bonus for Java Developers

Outline30.1 Introduction30.2 Servlet Overview and Architecture

30.2.1 Interface Servlet and the Servlet Life Cycle30.2.2 HttpServlet Class30.2.3 HttpServletRequest Interface30.2.4 HttpServletResponse Interface

30.3 Handling HTTP get Requests30.3.1 Setting Up the Apache Tomcat Server30.3.2 Deploying a Web Application

30.4 Handling HTTP get Requests Containing Data30.5 Handling HTTP post Requests30.6 Redirecting Requests to Other Resources30.7 Session Tracking

30.7.1 Cookies30.7.2 Session Tracking with HttpSession

30.8 Multi-tier Applications: Using JDBC from a Servlet30.9 HttpUtils Class30.10 Internet and World Wide Web Resources

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.

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

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

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

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

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

2001 Prentice Hall, Inc. All rights reserved.

8

30.2.1 Interface Servlet and the Servlet Life Cycle

Method Description void init( ServletConfig config )

This method is automatically called once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet.

ServletConfig getServletConfig()

This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes).

String getServletInfo()

This method is defined by a servlet programmer to return a String containing servlet information such as the servlet’s author and version.

void service( ServletRequest request, ServletResponse response )

The servlet container calls this method to respond to a client request to the servlet.

void destroy()

This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.

Fig. 30.1 Methods of interface Servlet (package javax.servlet).

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

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

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

2001 Prentice Hall, Inc. All rights reserved.

12

30.2.2 HttpServlet Class

Method Description doDelete Called in response to an HTTP delete request. Such a request is normally used to delete a

file from a server. This may not be available on some servers, because of its inherent security risks (i.e., the client could delete a file that is critical to the execution of the server or an application).

doOptions Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the version of HTTP (1.0 or 1.1) and the request methods the server supports.

doPut Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers, because of its inherent security risks (i.e., the client could place an executable application on the server, which, if executed, could damage the server—perhaps by deleting critical files or occupying resources).

doTrace Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).

Fig. 30.2 Other methods of class HttpServlet.

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

2001 Prentice Hall, Inc. All rights reserved.

14

30.2.3 HttpServletRequest Interface

Method Description String getParameter( String name )

Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name.

Enumeration getParameterNames()

Returns the names of all the parameters sent to the servlet as part of a post request.

String[] getParameterValues( String name )

For a parameter with multiple values, this method returns an array of Strings containing the values for a specified servlet parameter.

Cookie[] getCookies()

Returns an array of Cookie objects stored on the client by the server. Cookies can be used to uniquely identify clients to the servlet.

HttpSession getSession( boolean create )

Returns an HttpSession object associated with the client’s current browsing session. An HttpSession object can be created by this method (true argument) if an HttpSession object does not already exist for the client. HttpSession objects can be used in similar ways to Cookies for uniquely identifying clients.

Fig. 30.3 Some methods of interface HttpServletRequest.

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

2001 Prentice Hall, Inc. All rights reserved.

16

30.2.4 HTTP ServletResponse Interface

Method Description void addCookie( Cookie cookie )

Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client.

ServletOutputStream getOutputStream()

Obtains a byte-based output stream that enables binary data to be sent to the client.

PrintWriter getWriter()

Obtains a character-based output stream that enables text data to be sent to the client.

void setContentType( String type )

Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an XHTML document, so the browser displays the XHTML page. For more information on

Fig. 30.4 Some methods of interface HttpServletResponse.

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

2001 Prentice Hall, Inc. All rights reserved.

18

Upcoming example demonstrates get request handling

2001 Prentice Hall, Inc.All rights reserved.

Outline19

WelcomeServlet.java

Define WelcomeServlet

doGet

1 // Fig. 9.5: WelcomeServlet.java2 // 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 clients12 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 client20 21 // start XHTML document22 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );30 31 // head section of document32 out.println( "<head>" );33 out.println( "<title>A Simple Servlet Example</title>" );34 out.println( "</head>" );35

Extends HttpServlet to create a Web-based Servlet.

Process get request by creating an XHTML document.

2001 Prentice Hall, Inc.All rights reserved.

Outline20

WelcomeServlet.java

36 // body section of document37 out.println( "<body>" );38 out.println( "<h1>Welcome to Servlets!</h1>" );39 out.println( "</body>" );40 41 // end XHTML document42 out.println( "</html>" );43 out.close(); // close stream to complete the page44 } 45 }

2001 Prentice Hall, Inc.All rights reserved.

Outline21

WelcomeServlet.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 9.6: WelcomeServlet.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Handling an HTTP Get Request</title>10 </head>11 12 <body>13 <form action = "/advjhtp1/welcome1" method = "get">14 15 <p><label>Click the button to invoke the servlet16 <input type = "submit" value = "Get HTML Document" />17 </label></p>18 19 </form>20 </body>21 </html>

Main XHTML page which sends a get request to the servlet.

2001 Prentice Hall, Inc.All rights reserved.

Outline22

WelcomeServlet.java

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

2001 Prentice Hall, Inc. All rights reserved.

24

Testing and Debugging Tip 30.1

Fig. 30.7 Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)

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

2001 Prentice Hall, Inc. All rights reserved.

26

30.3.2 Deploying a Web Application

Directory Description context root This is the root directory for the Web application. The name of this directory is chosen by the Web

application developer. All the JSPs, HTML documents, servlets and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the Web application creator. To provide structure in a Web application, subdirectories can be placed in the context root. For example, if your application uses many images, you might place an images subdirectory in this directory.

WEB-INF This directory contains the Web application deployment descriptor (web.xml). WEB-INF/classes This directory contains the servlet class files and other supporting class files used in a Web application.

If the classes are part of a package, the complete package directory structure would begin here.

WEB-INF/lib This directory contains Java archive (JAR) files. The JAR files can contain servlet class files and other supporting class files used in a Web application.

Fig. 30.8 Web application standard directories.

2001 Prentice Hall, Inc.All rights reserved.

Outline27

1 <!-- Advanced Java How to Program JSP/servlet context -->2 <Context path = "/advjhtp1" 3 docBase = "webapps/advjhtp1" 4 reloadable = "true">5 </Context>

Fig. 30.9 Context element for servlet and JSP examples in Chapters 30 and 31.

2001 Prentice Hall, Inc.All rights reserved.

Outline28

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 <web-app>6 7 <!-- General description of your Web application -->8 <display-name>9 Advanced Java How to Program JSP 10 and Servlet Chapter Examples11 </display-name>12 13 <description>14 This is the Web application in which we 15 demonstrate our JSP and Servlet examples.16 </description>17 18 <!-- Servlet definitions -->19 <servlet>20 <servlet-name>welcome1</servlet-name>21 22 <description>23 A simple servlet that handles an HTTP get request.24 </description>25 26 <servlet-class>27 com.deitel.advjhtp1.servlets.WelcomeServlet28 </servlet-class>29 </servlet>30 31 <!-- Servlet mappings -->32 <servlet-mapping>33 <servlet-name>welcome1</servlet-name>

Maps a servlet name to its fully qualified class name.

2001 Prentice Hall, Inc.All rights reserved.

Outline29

34 <url-pattern>/welcome1</url-pattern>35 </servlet-mapping>36 37 </web-app>

Fig. 30.10 Deployment descriptor for the advjhtp1 Web application.

Map servlet to URL pattern. The pattern is relative to the server address and application context root.

2001 Prentice Hall, Inc. All rights reserved.

30

30.3.2 Deploying a Web Application

WelcomeServlet Web application directory and file structure

advjhtp1 servlets WelcomeServlet.html WEB-INF web.xml classes com deitel advjhtp1 servlets WelcomeServlet.class

Fig. 30.11 Web application directory and file structure for WelcomeServlet.

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 &

2001 Prentice Hall, Inc.All rights reserved.

Outline32

WelcomeServlet2.java

Define Servlet WelcomeServlet2

Write XHTML response

1 // Fig. 9.12: WelcomeServlet2.java2 // 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 client12 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 client22 23 // start XHTML document24 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );32 33 // head section of document34 out.println( "<head>" );

Obtain the parameter from the request and assign the value to a string.

2001 Prentice Hall, Inc.All rights reserved.

Outline33

WelcomeServlet2.java

35 out.println( 36 "<title>Processing get requests with data</title>" );37 out.println( "</head>" );38 39 // body section of document40 out.println( "<body>" );41 out.println( "<h1>Hello " + firstName + ",<br />" );42 out.println( "Welcome to Servlets!</h1>" );43 out.println( "</body>" );44 45 // end XHTML document46 out.println( "</html>" );47 out.close(); // close stream to complete the page48 } 49 }

Include the value in the response.

2001 Prentice Hall, Inc.All rights reserved.

Outline34

WelcomeServlet2.html

Send get request

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 9.13: WelcomeServlet2.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Processing get requests with data</title>10 </head>11 12 <body>13 <form action = "/advjhtp1/welcome2" method = "get">14 15 <p><label>16 Type your first name and press the Submit button17 <br /><input type = "text" name = "firstname" />18 <input type = "submit" value = "Submit" />19 </p></label>20 21 </form>22 </body>23 </html>

2001 Prentice Hall, Inc.All rights reserved.

Outline35

Program Output

form data specified in URL’s query string as part of a get request

2001 Prentice Hall, Inc. All rights reserved.

36

30.4 Handling HTTP get Requests Containing Data

Descriptor element Value

servlet element

servlet-name welcome2

description Handling HTTP get requests with data.

servlet-class com.deitel.advjhtp1.servlets.WelcomeServlet2

servlet-mapping element servlet-name welcome2

url-pattern /welcome2

Fig. 30.14 Deployment descriptor information for servlet WelcomeServlet2.

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

2001 Prentice Hall, Inc.All rights reserved.

Outline38

WelcomeServlet3.java

Define Servlet WelcomeServlet3

Handle doPost

Write XHTML response

1 // Fig. 9.15: WelcomeServlet3.java2 // 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 client12 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 client22 23 // start XHTML document24 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );32 33 // head section of document34 out.println( "<head>" );

Obtain the firstname parameter from the post request.

2001 Prentice Hall, Inc.All rights reserved.

Outline39

WelcomeServlet3.java

35 out.println( 36 "<title>Processing post requests with data</title>" );37 out.println( "</head>" );38 39 // body section of document40 out.println( "<body>" );41 out.println( "<h1>Hello " + firstName + ",<br />" );42 out.println( "Welcome to Servlets!</h1>" );43 out.println( "</body>" );44 45 // end XHTML document46 out.println( "</html>" );47 out.close(); // close stream to complete the page48 } 49 }

2001 Prentice Hall, Inc.All rights reserved.

Outline40

WelcomeServlet3.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 9.16: WelcomeServlet3.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Handling an HTTP Post Request with Data</title>10 </head>11 12 <body>13 <form action = "/advjhtp1/welcome3" method = "post">14 15 <p><label>16 Type your first name and press the Submit button17 <br /><input type = "text" name = "firstname" />18 <input type = "submit" value = "Submit" />19 </label></p>20 21 </form>22 </body>23 </html>

Submit a post request with a firstname parameter

2001 Prentice Hall, Inc.All rights reserved.

Outline41

Program Output

2001 Prentice Hall, Inc. All rights reserved.

42

30.5 Handling HTTP post Requests

Descriptor element Value

servlet element

servlet-name welcome3

description Handling HTTP post requests with data.

servlet-class com.deitel.advjhtp1.servlets.WelcomeServlet3

servlet-mapping element servlet-name welcome3

url-pattern /welcome3

Fig. 30.17 Deployment descriptor information for servlet WelcomeServlet3.

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

2001 Prentice Hall, Inc.All rights reserved.

Outline44

RedirectServlet.java

Define Servlet RedirectServlet

Process get request

1 // Fig. 9.18: RedirectServlet.java2 // 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 client12 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 servlet27 // does not redirect the user to another page28 29 response.setContentType( "text/html" );30 PrintWriter out = response.getWriter(); 31 32 // start XHTML document33 out.println( "<?xml version = \"1.0\"?>" );

Obtain the page parameter for redirection location.

Redirect user to another page or servlet.

2001 Prentice Hall, Inc.All rights reserved.

Outline45

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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );41 42 // head section of document43 out.println( "<head>" );44 out.println( "<title>Invalid page</title>" );45 out.println( "</head>" );46 47 // body section of document48 out.println( "<body>" );49 out.println( "<h1>Invalid page requested</h1>" );50 out.println( "<p><a href = " + 51 "\"servlets/RedirectServlet.html\">" );52 out.println( "Click here to choose again</a></p>" );53 out.println( "</body>" );54 55 // end XHTML document56 out.println( "</html>" );57 out.close(); // close stream to complete the page 58 } 59 }

2001 Prentice Hall, Inc.All rights reserved.

Outline46

RedirectServlet.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 9.19: RedirectServlet.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Redirecting a Request to Another Site</title>10 </head>11 12 <body>13 <p>Click a link to be redirected to the appropriate page</p>14 <p>15 <a href = "/advjhtp1/redirect?page=deitel">16 www.deitel.com</a><br />17 <a href = "/advjhtp1/redirect?page=welcome1">18 Welcome servlet</a>19 </p>20 </body>21 </html>

Send get request to RedirectServlet with the page parameter.

2001 Prentice Hall, Inc.All rights reserved.

Outline47

Program Output

2001 Prentice Hall, Inc. All rights reserved.

48

30.6 Redirecting Requests to Other Resources

Descriptor element Value

servlet element

servlet-name redirect

description Redirecting to static Web pages and other servlets.

servlet-class com.deitel.advjhtp1.servlets.RedirectServlet

servlet-mapping element servlet-name redirect

url-pattern /redirect

Fig. 30.20 Deployment descriptor information for servlet RedirectServlet.

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

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

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

2001 Prentice Hall, Inc.All rights reserved.

Outline52

CookieServlet.java

Define Servlet CookieServlet

Init book ISBN

doPost writes cookie

1 // Fig. 9.21: CookieServlet.java2 // 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 books14 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 containing23 // recommended book to the client24 protected void doPost( HttpServletRequest request,25 HttpServletResponse response )26 throws ServletException, IOException27 {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.

2001 Prentice Hall, Inc.All rights reserved.

Outline53

CookieServlet.java

Write XHTML response

36 // send XHTML page to client37 38 // start XHTML document39 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );47 48 // head section of document49 out.println( "<head>" );50 out.println( "<title>Welcome to Cookies</title>" ); 51 out.println( "</head>" );52 53 // body section of document54 out.println( "<body>" );55 out.println( "<p>Welcome to Cookies! You selected " +56 language + "</p>" );57 58 out.println( "<p><a href = " +59 "\"/advjhtp1/servlets/CookieSelectLanguage.html\">" +60 "Click here to choose another language</a></p>" );61 62 out.println( "<p><a href = \"/advjhtp1/cookies\">" + 63 "Click here to get book recommendations</a></p>" );64 out.println( "</body>" );65 66 // end XHTML document67 out.println( "</html>" );68 out.close(); // close stream69 }70

2001 Prentice Hall, Inc.All rights reserved.

Outline54

CookieServlet.java

doGet process get request

Obtain user cookies

71 // read cookies from client and create XHTML document72 // containing recommended books73 protected void doGet( HttpServletRequest request,74 HttpServletResponse response )75 throws ServletException, IOException76 {77 Cookie cookies[] = request.getCookies(); // get cookies78 79 response.setContentType( "text/html" ); 80 PrintWriter out = response.getWriter();81 82 // start XHTML document83 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );91 92 // head section of document93 out.println( "<head>" );94 out.println( "<title>Recommendations</title>" );95 out.println( "</head>" );96 97 // body section of document98 out.println( "<body>" );99 100 // if there are any cookies, recommend a book for each ISBN101 if ( cookies != null && cookies.length != 0 ) {102 out.println( "<h1>Recommendations</h1>" );103 out.println( "<p>" );104 105 // get the name of each cookie

Get any cookies from client.

2001 Prentice Hall, Inc.All rights reserved.

Outline55

CookieServlet.java

106 for ( int i = 0; i < cookies.length; i++ ) 107 out.println( cookies[ i ].getName() + 108 " How to Program. ISBN#: " + 109 cookies[ i ].getValue() + "<br />" );110 111 out.println( "</p>" );112 }113 else { // there were no cookies114 out.println( "<h1>No Recommendations</h1>" );115 out.println( "<p>You did not select a language.</p>" );116 }117 118 out.println( "</body>" );119 120 // end XHTML document121 out.println( "</html>" );122 out.close(); // close stream123 }124 }

Cycle through cookies and display book recommendation.

2001 Prentice Hall, Inc.All rights reserved.

Outline56

CookieSelectLanguage.html

Static XHTML page

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 9.22: CookieSelectLanguage.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Using Cookies</title> 10 </head>11 12 <body>13 <form action = "/advjhtp1/cookies" method = "post"> 14 15 <p>Select a programming language:</p>16 <p>17 <input type = "radio" name = "language" 18 value = "C" />C <br />19 20 <input type = "radio" name = "language" 21 value = "C++" />C++ <br />22 23 <!-- this radio button checked by default -->24 <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java<br />26 27 <input type = "radio" name = "language" 28 value = "VB6" />VB 629 </p>30 31 <p><input type = "submit" value = "Submit" /></p>32 33 </form>34 </body>35 </html>

Post user selected language.

2001 Prentice Hall, Inc.All rights reserved.

Outline57

Program Output

2001 Prentice Hall, Inc.All rights reserved.

Outline58

Program Output

2001 Prentice Hall, Inc.All rights reserved.

Outline59

Program Output

2001 Prentice Hall, Inc. All rights reserved.

60

30.7.1 Cookies

Descriptor element Value

servlet element

servlet-name cookies

description Using cookies to maintain state information.

servlet-class com.deitel.advjhtp1.servlets.CookieServlet

servlet-mapping element servlet-name cookies

url-pattern /cookies

Fig. 30.23 Deployment descriptor information for servlet CookieServlet.

2001 Prentice Hall, Inc. All rights reserved.

61

30.7.1 Cookies

Method Description

getComment() Returns a String describing the purpose of the cookie (null if no comment

has been set with setComment).

getDomain() Returns a String containing the cookie’s domain. This determines which servers can receive the cookie. By default, cookies are sent to the server that originally sent the cookie to the client.

getMaxAge() Returns an int representing the maximum age of the cookie in seconds.

getName() Returns a String containing the name of the cookie as set by the constructor.

getPath() Returns a String containing the URL prefix for the cookie. Cookies can be “targeted” to specific URLs that include directories on the Web server. By default, a cookie is returned to services operating in the same directory as the service that sent the cookie or a subdirectory of that directory.

getSecure() Returns a boolean value indicating if the cookie should be transmitted using a

secure protocol (true).

getValue() Returns a String containing the value of the cookie as set with setValue or the constructor.

Fig. 30.24 Important methods of class Cookie.

2001 Prentice Hall, Inc. All rights reserved.

62

30.7.1 Cookies

Method Description getVersion() Returns an int containing the version of the cookie protocol used to create the

cookie. A value of 0 (the default) indicates the original cookie protocol as defined by

Netscape. A value of 1 indicates the current version, which is based on Request for Comments (RFC) 2109.

setComment( String ) The comment describing the purpose of the cookie that is presented by the browser to the user. (Some browsers allow the user to accept cookies on a per-cookie basis.)

setDomain( String ) This determines which servers can receive the cookie. By default, cookies are sent to the server that originally sent the cookie to the client. The domain is specified in the form ".deitel.com", indicating that all servers ending with .deitel.com can receive this cookie.

setMaxAge( int ) Sets the maximum age of the cookie in seconds.

setPath( String ) Sets the “target” URL prefix indicating the directories on the server that lead to the services that can receive this cookie.

setSecure( boolean ) A true value indicates that the cookie should only be sent using a secure protocol.

setValue( String ) Sets the value of a cookie.

setVersion( int ) Sets the cookie protocol for this cookie.

Fig. 30.24 Important methods of class Cookie.

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 invalidated

• Servlet container restart

2001 Prentice Hall, Inc.All rights reserved.

Outline64

SessionServlet.java

Define Servlet SessionServlet

1 // Fig. 9.25: SessionServlet.java2 // 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 books14 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 object23 // containing recommended book for the client24 protected void doPost( HttpServletRequest request,25 HttpServletResponse response )26 throws ServletException, IOException27 {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.

2001 Prentice Hall, Inc.All rights reserved.

Outline65

SessionServlet.java

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 client41 42 // start XHTML document43 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );51 52 // head section of document53 out.println( "<head>" );54 out.println( "<title>Welcome to Sessions</title>" );55 out.println( "</head>" );56 57 // body section of document58 out.println( "<body>" );59 out.println( "<p>Welcome to Sessions! You selected " +60 language + ".</p>" );61 62 // display information about the session63 out.println( "<p>Your unique session ID is: " + 64 session.getId() + "<br />" );65 66 out.println( 67 "This " + ( session.isNew() ? "is" : "is not" ) +68 " a new session<br />" );69

2001 Prentice Hall, Inc.All rights reserved.

Outline66

SessionServlet.java

process get request

70 out.println( "The session was created at: " + 71 new Date( session.getCreationTime() ) + "<br />" );72 73 out.println( "You last accessed the session at: " + 74 new Date( session.getLastAccessedTime() ) + "<br />" );75 76 out.println( "The maximum inactive interval is: " + 77 session.getMaxInactiveInterval() + " seconds</p>" );78 79 out.println( "<p><a href = " +80 "\"servlets/SessionSelectLanguage.html\">" +81 "Click here to choose another language</a></p>" );82 83 out.println( "<p><a href = \"sessions\">" +84 "Click here to get book recommendations</a></p>" );85 out.println( "</body>" );86 87 // end XHTML document88 out.println( "</html>" );89 out.close(); // close stream90 }91 92 // read session attributes and create XHTML document93 // containing recommended books94 protected void doGet( HttpServletRequest request,95 HttpServletResponse response )96 throws ServletException, IOException97 {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 values103 Enumeration valueNames;104

Obtain the client session, but do not create one if it does not exist.

2001 Prentice Hall, Inc.All rights reserved.

Outline67

SessionServlet.java

105 if ( session != null )106 valueNames = session.getAttributeNames();107 else108 valueNames = null;109 110 PrintWriter out = response.getWriter();111 response.setContentType( "text/html" ); 112 113 // start XHTML document114 out.println( "<?xml version = \"1.0\"?>" );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 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );122 123 // head section of document124 out.println( "<head>" );125 out.println( "<title>Recommendations</title>" );126 out.println( "</head>" );127 128 // body section of document129 out.println( "<body>" );130 131 if ( valueNames != null && 132 valueNames.hasMoreElements() ) {133 out.println( "<h1>Recommendations</h1>" );134 out.println( "<p>" );135 136 String name, value; 137 138 // get value for each name in valueNames139 while ( valueNames.hasMoreElements() ) {

Obtain the attributes of the client. Then display any recommendations.

2001 Prentice Hall, Inc.All rights reserved.

Outline68

SessionServlet.java

140 name = valueNames.nextElement().toString();141 value = session.getAttribute( name ).toString();142 143 out.println( name + " How to Program. " +144 "ISBN#: " + value + "<br />" );145 } 146 147 out.println( "</p>" );148 }149 else {150 out.println( "<h1>No Recommendations</h1>" );151 out.println( "<p>You did not select a language.</p>" );152 }153 154 out.println( "</body>" );155 156 // end XHTML document157 out.println( "</html>" );158 out.close(); // close stream159 }160 }

2001 Prentice Hall, Inc.All rights reserved.

Outline69

SessionSelectLanguage.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Fig. 9.26: SessionSelectLanguage.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Using Sessions</title> 10 </head>11 12 <body>13 <form action = "/advjhtp1/sessions" method = "post"> 14 15 <p>Select a programming language:</p>16 <p>17 <input type = "radio" name = "language" 18 value = "C" />C <br />19 20 <input type = "radio" name = "language" 21 value = "C++" />C++ <br />22 23 <!-- this radio button checked by default -->24 <input type = "radio" name = "language" 25 value = "Java" checked = "checked" />Java<br />26 27 <input type = "radio" name = "language" 28 value = "VB6" />VB 629 </p>30 31 <p><input type = "submit" value = "Submit" /></p>32 33 </form>34 </body>35 </html>

XHTML page that allows the clientto select a programming languagethey would like a recommendationfor.

2001 Prentice Hall, Inc.All rights reserved.

Outline70

Program Output

2001 Prentice Hall, Inc.All rights reserved.

Outline71

Program Output

2001 Prentice Hall, Inc.All rights reserved.

Outline72

Program Output

2001 Prentice Hall, Inc. All rights reserved.

73

30.7.2 Session Tracking with HttpSession

Descriptor element Value

servlet element

servlet-name sessions

description Using sessions to maintain state information.

servlet-class com.deitel.advjhtp1.servlets.SessionServlet

servlet-mapping element servlet-name sessions

url-pattern /sessions

Fig. 30.27 Deployment descriptor information for servlet WelcomeServlet2.

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

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

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

2001 Prentice Hall, Inc.All rights reserved.

Outline77

SurveyServlet.java

Define servlet SurveyServlet

set up database

1 // Fig. 9.27: SurveyServlet.java2 // 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 statements16 public void init( ServletConfig config ) 17 throws ServletException18 {19 // attempt database connection and create PreparedStatements20 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 votes34 totalVotes =35 connection.prepareStatement(

Specify database driver. Connect to database through that driver.

Define SQL query to obtain database information

2001 Prentice Hall, Inc.All rights reserved.

Outline78

SurveyServlet.java

handle post request

36 "SELECT sum( votes ) FROM surveyresults"37 );38 39 // PreparedStatement to obtain surveyoption table's data40 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 available49 catch ( Exception exception ) {50 exception.printStackTrace();51 throw new UnavailableException(exception.getMessage());52 }53 54 } // end of init method55 56 // process survey response57 protected void doPost( HttpServletRequest request,58 HttpServletResponse response )59 throws ServletException, IOException60 {61 // set up response to client62 response.setContentType( "text/html" ); 63 PrintWriter out = response.getWriter();64 DecimalFormat twoDigits = new DecimalFormat( "0.00" );65 66 // start XHTML document67 out.println( "<?xml version = \"1.0\"?>" );68 69 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +70 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +

2001 Prentice Hall, Inc.All rights reserved.

Outline79

SurveyServlet.java

71 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 72 73 out.println( 74 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );75 76 // head section of document77 out.println( "<head>" ); 78 79 // read current survey response80 int value = 81 Integer.parseInt( request.getParameter( "animal" ) );82 83 // attempt to process a vote and display current results84 try {85 86 // update total for current survey response87 updateVotes.setInt( 1, value );88 updateVotes.executeUpdate();89 90 // get total of all survey responses91 ResultSet totalRS = totalVotes.executeQuery();92 totalRS.next();93 int total = totalRS.getInt( 1 );94 95 // get results96 ResultSet resultsRS = results.executeQuery();97 out.println( "<title>Thank you!</title>" );98 out.println( "</head>" ); 99 100 out.println( "<body>" ); 101 out.println( "<p>Thank you for participating." );102 out.println( "<br />Results:</p><pre>" );103 104 // process results105 int votes;

Update database with post parameter.

Obtain the survey totals and information via SQL requests.

2001 Prentice Hall, Inc.All rights reserved.

Outline80

SurveyServlet.java

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 document123 out.println( "</pre></body></html>" ); 124 out.close();125 }126 127 // if database exception occurs, return error page128 catch ( SQLException sqlException ) {129 sqlException.printStackTrace();130 out.println( "<title>Error</title>" );131 out.println( "</head>" ); 132 out.println( "<body><p>Database error occurred. " );133 out.println( "Try again later.</p></body></html>" );134 out.close();135 }136 137 } // end of doPost method138 139 // close SQL statements and database when servlet terminates140 public void destroy()

Display results in XHTML response.

2001 Prentice Hall, Inc.All rights reserved.

Outline81

SurveyServlet.java

Close database

141 {142 // attempt to close statements and database connection143 try {144 updateVo\tes.close();145 totalVotes.close();146 results.close();147 connection.close();148 }149 150 // handle database exceptions by returning error to client151 catch( SQLException sqlException ) {152 sqlException.printStackTrace();153 }154 } // end of destroy method155 }

2001 Prentice Hall, Inc.All rights reserved.

Outline82

Survey.html

1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4 5 <!-- Survey.html -->6 7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Survey</title>10 </head>11 12 <body>13 <form method = "post" action = "/advjhtp1/animalsurvey">14 15 <p>What is your favorite pet?</p>16 17 <p>18 <input type = "radio" name = "animal" 19 value = "1" />Dog<br />20 <input type = "radio" name = "animal" 21 value = "2" />Cat<br />22 <input type = "radio" name = "animal" 23 value = "3" />Bird<br />24 <input type = "radio" name = "animal" 25 value = "4" />Snake<br />26 <input type = "radio" name = "animal" 27 value = "5" checked = "checked" />None28 </p>29 30 <p><input type = "submit" value = "Submit" /></p>31 32 </form>33 </body>34 </html>

Static survey XHTML page.

2001 Prentice Hall, Inc.All rights reserved.

Outline83

Program Output

2001 Prentice Hall, Inc. All rights reserved.

84

30.8.1 Configuring animalsurvey Database and SurveyServlet

Descriptor element Value

servlet element

servlet-name animalsurvey

description Connecting to a database from a servlet.

servlet-class com.deitel.advjhtp1.servlets.SurveyServlet

servlet-mapping element servlet-name animalsurvey

url-pattern /animalsurvey

Fig. 30.30 Deployment descriptor information for servlet SurveyServlet.

2001 Prentice Hall, Inc. All rights reserved.

85

30.9 HttpUtils Class

• HttpUtils Class– Three static utility methods to simplify servlet development

2001 Prentice Hall, Inc. All rights reserved.

86

30.9 HttpUtils Class

Method Description getRequestURL This method takes the HttpServletRequest object as an argument and returns a

StringBuffer containing the original URL that initiated the request.

parsePostData This method receives an integer and ServletInputStream as arguments. The integer represents the number of bytes in the ServletInputStream. The ServletInputStream contains the key/value pairs posted to the servlet from a form. The method returns a Hashtable containing the key/value pairs.

parseQueryString This method receives a String representing the query string in a get request as an argument and returns a Hashtable containing the key/value pairs in the query string. The value of each key is an array of Strings. The query string can be obtained with HttpServletRequest method getQueryString.

Fig. 30.31 HttpUtils class methods.