• No results found

Chapter 9: Servlets

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 9: Servlets"

Copied!
77
0
0

Loading.... (view fulltext now)

Full text

(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.)

Method Desc ription

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. 9.1 Methods of interfa c e Servlet (pa c ka ge javax.servlet).

(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.)

Method Desc ription

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 a\n HTML document to the client containing the request header information (data sent by the browser as part of the request).

Fig. 9.2 Other methods of class HttpServlet.

(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.)

Method Desc ription

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. 9.3 Some methods of interfa c e HttpServletRequest.

(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.)

Method Desc ription

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 for sending binary data to the client.

PrintWriter getWriter()

Obtains a character-based output stream for sending text data 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 HTML document, so the browser displays the HTML page. For more information on

Fig. 9.4 Some methods of interfac e HttpServletResponse.

(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( "<?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 document 32 out.println( "<head>" );

33 out.println( "<title>A Simple Servlet Example</title>" );

34 out.println( "</head>" );

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( "<body>" );

38 out.println( "<h1>Welcome to Servlets!</h1>" );

39 out.println( "</body>" );

40

41 // end XHTML document 42 out.println( "</html>" );

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 <?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 servlet

16 <input type = "submit" value = "Get HTML Document" />

17 </label></p>

18

19 </form>

20 </body>

21 </html>

(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.7 Tomcat 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.)

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. The examples of this chapter and Chapter 10 use advjhtp1 as the context root.

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. 9.8 Web application standard directories.

(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 <web-app>

6

7 <!-- General description of your Web application -->

8 <display-name>

9 Advanced Java How to Program JSP 10 and Servlet Chapter Examples

11 </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.WelcomeServlet 28 </servlet-class>

29 </servlet>

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 <!-- Servlet mappings -->

32 <servlet-mapping>

33 <servlet-name>welcome1</servlet-name>

34 <url-pattern>/welcome1</url-pattern>

35 </servlet-mapping>

36

37 </web-app>

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.)

WelcomeServlet Web applic ation direc tory and file struc ture advjhtp1

servlets

WelcomeServlet.html WEB-INF

web.xml classes com

deitel

advjhtp1 servlets

WelcomeServlet.class

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

(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( "<?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

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( "<head>" );

35 out.println(

36 "<title>Processing get requests with data</title>" );

37 out.println( "</head>" );

38

39 // body section of document 40 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 document 46 out.println( "</html>" );

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 <?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.12: 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 button 17 <br /><input type = "text" name = "firstname" />

18 <input type = "submit" value = "Submit" />

19 </p></label>

20

21 </form>

22 </body>

23 </html>

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.)

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. 9.13 Deployment descriptor information for servlet WelcomeServlet2.

(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( "<?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

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( "<head>" );

35 out.println(

36 "<title>Processing post requests with data</title>" );

37 out.println( "</head>" );

38

39 // body section of document 40 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 document 46 out.println( "</html>" );

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 <?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.15: 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 button 17 <br /><input type = "text" name = "firstname" />

18 <input type = "submit" value = "Submit" />

19 </label></p>

20

21 </form>

22 </body>

23 </html>

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.)

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. 9.16 Deployment descriptor information for servlet WelcomeServlet3.

(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( "<?xml version = \"1.0\"?>" );

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 document 43 out.println( "<head>" );

44 out.println( "<title>Invalid page</title>" );

45 out.println( "</head>" );

46

47 // body section of document 48 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 document 56 out.println( "</html>" );

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 <?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.18: 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>

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.)

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. 9.19 Deployment descriptor information for servlet RedirectServlet.

(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( "<?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 document 49 out.println( "<head>" );

50 out.println( "<title>Welcome to Cookies</title>" );

51 out.println( "</head>" );

52

53 // body section of document 54 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 document 67 out.println( "</html>" );

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( "<?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 document 93 out.println( "<head>" );

94 out.println( "<title>Recommendations</title>" );

95 out.println( "</head>" );

96

97 // body section of document 98 out.println( "<body>" );

99

100 // if there are any cookies, recommend a book for each ISBN 101 if ( cookies != null && cookies.length != 0 ) {

102 out.println( "<h1>Recommendations</h1>" );

103 out.println( "<p>" );

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() + "<br />" );

110

111 out.println( "</p>" );

112 }

113 else { // there were no cookies

114 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 document 121 out.println( "</html>" );

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 <?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.21: 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 6 29 </p>

30

31 <p><input type = "submit" value = "Submit" /></p>

32

33 </form>

34 </body>

35 </html>

(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.)

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. 9.22 Deployment descriptor information for servlet CookieServlet.

References

Related documents

4.1 The Select Committee is asked to consider the proposed development of the Customer Service Function, the recommended service delivery option and the investment required8. It

Using text mining of first-opinion electronic medical records from seven veterinary practices around the UK, Kaplan-Meier and Cox proportional hazard modelling, we were able to

In this PhD thesis new organic NIR materials (both π-conjugated polymers and small molecules) based on α,β-unsubstituted meso-positioning thienyl BODIPY have been

For the poorest farmers in eastern India, then, the benefits of groundwater irrigation have come through three routes: in large part, through purchased pump irrigation and, in a

• Follow up with your employer each reporting period to ensure your hours are reported on a regular basis?. • Discuss your progress with

The uniaxial compressive strengths and tensile strengths of individual shale samples after four hours exposure to water, 2.85x10 -3 M cationic surfactant

Proprietary Schools are referred to as those classified nonpublic, which sell or offer for sale mostly post- secondary instruction which leads to an occupation..