5.1 servlets n http request

Upload: chidambaram

Post on 14-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 5.1 Servlets n Http Request

    1/57

    2004 Prentice Hall, Inc. All rights reserved.

    Chapter 36 - Servlets:

    Bonus for Java DevelopersOutline

    36.1 Introduction36.2 Servlet Overview and Architecture

    36.2.1 Interface Servlet and the Servlet Life Cycle36.2.2 HttpServlet Class36.2.3 HttpServletRequest Interface36.2.4 HttpServletResponse Interface

    36.3 Handling HTTP get Requests36.3.1 Setting Up the Apache Tomcat Server

    36.3.2 Deploying a Web Application

    36.4 Handling HTTP get Requests Containing Data36.5 Handling HTTP post Requests36.6 Redirecting Requests to Other Resources

    36.7 Multi-Tier Applications: Using JDBC from a Servlet

    36.8 Web Resources

  • 7/30/2019 5.1 Servlets n Http Request

    2/57

    2004 Prentice Hall, Inc. All rights reserved.

    Objectives

    In this lesson, you will learn: To execute servlets with the Apache Tomcat server.

    To be able to respond to HTTP requests from an

    HttpServlet.

    To be able to redirect requests to static and dynamic Webresources.

  • 7/30/2019 5.1 Servlets n Http Request

    3/57

    2004 Prentice Hall, Inc. All rights reserved.

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

  • 7/30/2019 5.1 Servlets n Http Request

    4/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.1 Introduction (Cont.)

    Servlets Thin clients

    Request/response mechanism

    redirection

    Tomcat Jakarta project

    Official reference implementation of the JSP and servlet

    standards

  • 7/30/2019 5.1 Servlets n Http Request

    5/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.2 Servlet Overview and Architecture

    Servlet container (servlet engine) Server that executes a servlet

    Web servers and application servers Sun ONE Application Server

    Microsofts Internet Information Server (IIS)

    Apache HTTP Server

    BEAs WebLogic Application Server

    IBMs WebSphere Application Server

    World Wide Web Consortiums Jigsaw Web Server

  • 7/30/2019 5.1 Servlets n Http Request

    6/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.2.1 Interface Servlet and the Servlet LifeCycle

    Interface Servlet All servlets must implement this interface

    All methods of interface Servlet are invoked by servlet

    container

    Servlet life cycle Servlet container invokes the servlets init method

    Servlets service method handles requests

    Servlets destroy method releases servlet resources when

    the servlet container terminates the servlet Servlet implementation

    GenericServlet

    HttpServlet

  • 7/30/2019 5.1 Servlets n Http Request

    7/57 2004 Prentice Hall, Inc. All rights reserved.

    36.2.1 Interface Servlet and the Servlet LifeCycle (Cont.)

    Method Descriptionvoid init(ServletConfigconfig )

    The servlet container calls this method once during a servlets execution cycle to initialize theservlet. The ServletConfig argument is supplied by the servlet container that executes theservlet.

    ServletConfiggetServletConfig()

    This method returns a reference to an object that implements interface ServletConfig. This

    object provides access to the servlets configuration information such as servlet initializationparameters and the servlets ServletContext, which provides the servlet with access to itsenvironment (i.e., the servlet container in which the servlet executes).

    StringgetServletInfo()

    This method is defined by a servlet programmer to return a string containing servlet informationsuch as the servlets author and version.

    void service(ServletRequestrequest,ServletResponseresponse )

    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. 36.1 Methods of interface Servlet (package javax.servlet).

  • 7/30/2019 5.1 Servlets n Http Request

    8/57 2004 Prentice Hall, Inc. All rights reserved.

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

  • 7/30/2019 5.1 Servlets n Http Request

    9/57 2004 Prentice Hall, Inc. All rights reserved.

    36.2.2 HttpServlet Class (Cont.)

    Method DescriptiondoDelete 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, becauseof its inherent security risks (e.g., the client could delete a file that is critical tothe execution of the server or an application).

    doHead Called in response to an HTTP headrequest. Such a request is normally usedwhen the client only wants the headers of a response, such as the content type andcontent length of the response.

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

    doPut Called in response to an HTTPput request. Such a request is normally used tostore a file on the server. This may not be available on some servers, because ofits inherent security risks (e.g., the client could place an executable application onthe server, which, if executed, could damage the serverperhaps by deletingcritical files or occupying resources).

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

    Fig.36.2 Other methods of class HttpServlet.

  • 7/30/2019 5.1 Servlets n Http Request

    10/57 2004 Prentice Hall, Inc. All rights reserved.

    36.2.3 HttpServletRequest Interface

    Web server creates an HttpServletRequest object

    passes it to the servlets service method

    HttpServletRequest object contains the request

    from the client

  • 7/30/2019 5.1 Servlets n Http Request

    11/57 2004 Prentice Hall, Inc. All rights reserved.

    36.2.3 HttpServletRequest Interface(Cont.)

    Method DescriptionStringgetParameter(String name )

    Obtains the value of a parameter sent to the servlet as part of a get orpost request. Thename argument represents the parameter name.

    EnumerationgetParameterNames()

    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 thevalues for a specified servlet parameter.

    Cookie[]getCookies()

    Returns an array ofCookie objects stored on the client by the server. Cookie objects canbe used to uniquely identify clients to the servlet.

    HttpSessiongetSession(boolean create )

    Returns an HttpSession object associated with the clients current browsing session.This method can create an HttpSession object (true argument) if one does not alreadyexist for the client. HttpSession objects are used in similar ways to Cookies foruniquely identifying clients.

    Fig. 36.3 Some methods of interface HttpServletRequest.

  • 7/30/2019 5.1 Servlets n Http Request

    12/57 2004 Prentice Hall, Inc. All rights reserved.

    36.2.4 HttpServletResponse Interface

    Web server creates an HttpServletResponse object

    passes it to the servlets service method

  • 7/30/2019 5.1 Servlets n Http Request

    13/57 2004 Prentice Hall, Inc. All rights reserved.

    36.2.4 HttpServletResponse Interface(Cont.)

    Method Descriptionvoid addCookie(Cookie cookie )

    Used to add a Cookie to the header of the response to the client. The

    Cookies maximum age and whetherCookies are enabled on the clientdetermine ifCookies are stored on the client.

    ServletOutputStreamgetOutputStream()

    Obtains a byte-based output stream for sending binary data to the client.

    PrintWritergetWriter()

    Obtains a character-based output stream for sending text data to the client.

    voidsetContentType(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 thebrowser displays the HTML page.

    Fig. 36.4 Some methods of interface HttpServletResponse.

  • 7/30/2019 5.1 Servlets n Http Request

    14/57 2004 Prentice Hall, Inc. All rights reserved.

    36.3 Handling HTTP get Requests

    get request Retrieve the content of a URL

    Example: WelcomeServlet a servlet handles HTTP get requests

    1 // Fig 36 5: WelcomeServlet java

  • 7/30/2019 5.1 Servlets n Http Request

    15/57

    2004 Prentice Hall, Inc.

    All rights reserved.

    Outline

    1 // Fig. 36.5: WelcomeServlet.java

    2 // A simple servlet to process get requests.

    3

    4 import javax.servlet.*;

    5 import javax.servlet.http.*;

    6 import java.io.*;

    7

    8 publicclass WelcomeServlet extends HttpServlet {

    9

    10 // process "get" requests from clients

    11 protectedvoid doGet( HttpServletRequest request,

    12 HttpServletResponse response )

    13 throws ServletException, IOException

    14{

    15 response.setContentType( "text/html" );

    16 PrintWriter out = response.getWriter();

    17

    18 // send XHTML page to client

    19

    20 // start XHTML document

    21 out.println( "" );22

    23 out.println( "" );

    WelcomeServlet.java

    (1 of 2)

    Import the javax.servlet andjavax.servlet.http packages.

    Extends HttpServlet tohandle HTTP get requestsand HTTP post requests.

    Override method doGet toprovide custom get request

    processing.

    Uses the response objectssetContentType method tospecify the content type of the data to

    be sent as the response to the client.

    Uses the response objectsgetWriter method to obtain areference to the PrintWriterobject that enables the servlet to send

    content to the client.Create the XHTML document

    by writing strings with theoutobjects println method.

    26

  • 7/30/2019 5.1 Servlets n Http Request

    16/57

    2004 Prentice Hall, Inc.

    All rights reserved.

    Outline

    26

    27 out.println( "" );

    28

    29 // head section of document

    30 out.println( "" );

    31 out.println( "A Simple Servlet Example" );

    32 out.println( "" );

    33

    34 // body section of document

    35 out.println( "" );

    36 out.println( "Welcome to Servlets!" );

    37 out.println( "" );

    38

    39 // end XHTML document40 out.println( "" );

    41 out.close(); // close stream to complete the page

    42 }

    43 }

    WelcomeServlet.java

    (2 of 2)

    Closes the output stream,

    flushes the output buffer

    and sends the information

    to the client.

    1

  • 7/30/2019 5.1 Servlets n Http Request

    17/57

    2004 Prentice Hall, Inc.

    All rights reserved.

    Outline

    WelcomeServlet.html

    (1 of 1)

    1

    2

    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

  • 7/30/2019 5.1 Servlets n Http Request

    18/57

    2004 Prentice Hall, Inc.

    All rights reserved.

    Outline

    Program output

  • 7/30/2019 5.1 Servlets n Http Request

    19/57 2004 Prentice Hall, Inc. All rights reserved.

    36.3.1 Setting Up the Apache Tomcat Server

    Download Tomcat (version 4.1.27) jakarta.apache.org/site/binindex.cgi

    Define environment variables JAVA_HOME

    CATALINA_HOME

    Start the Tomcat server startup

    Launch the Tomcat server http://localhost:8080/

  • 7/30/2019 5.1 Servlets n Http Request

    20/57 2004 Prentice Hall, Inc. All rights reserved.

    36.3.1 Setting Up the Apache Tomcat Server

    (Cont.).

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

  • 7/30/2019 5.1 Servlets n Http Request

    21/57 2004 Prentice Hall, Inc. All rights reserved.

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

  • 7/30/2019 5.1 Servlets n Http Request

    22/57 2004 Prentice Hall, Inc. All rights reserved.

    36.3.2 Deploying a Web Application (Cont.)

    Directory Descriptioncontext root This is the root directory for the Web application. 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 use jhtp5 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 JARfiles can contain servlet class files and other supporting class

    files used in a Web application.

    Fig. 36.8 Web application standard directories.

    1

  • 7/30/2019 5.1 Servlets n Http Request

    23/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline

    pp

    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 Internet World Wide Web How to Program JSP

    10 and Servlet Chapter Examples

    11

    12

    13

    14 This is the Web application in which we15 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

    web.xml

    (1 of 2)

    Element web-app defines the configurationof each servlet in the Web application and

    the servlet mapping for each servlet.

    Element display-name specifiesa name that can be displayed to the

    administrator of the server on which

    the Web application is installed.

    Element description specifies adescription 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 descriptionspecifies a description for

    this particular servlet.

    26

  • 7/30/2019 5.1 Servlets n Http Request

    24/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline27 WelcomeServlet28

    29

    30

    31

    32

    33 welcome1

    34 /welcome1

    35

    36

    37

    web.xml

    (2 of 2)Element servlet-mapping

    specifies servlet-name andurl-pattern elements.

    Element servlet-classspecifies compiled servlets

    fully qualified class name.

  • 7/30/2019 5.1 Servlets n Http Request

    25/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.3.2 Deploying a Web Application (Cont.)

    Invoke WelcomeServlet example /iw3htp3/welcome1 /iw3htp3 specifies the context root

    /welcome1 specifies the URL pattern

    URL pattern formats Exact match

    /iw3htp3/welcome1

    Path mappings

    /iw3htp3/example/*

    Extension mappings

    *.jsp

    Default servlet

    /

  • 7/30/2019 5.1 Servlets n Http Request

    26/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.3.2 Deploying a Web Application (Cont.)

    WelcomeServlet Web application directory and file structureiw3htp3servlets

    WelcomeServlet.htmlWEB-INF

    web.xmlclasses

    WelcomeServlet.classFig. 36.10 Web application directory and file structure for

    WelcomeServlet.

  • 7/30/2019 5.1 Servlets n Http Request

    27/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.4 Handling HTTP get RequestsContaining Data

    Servlet WelcomeServlet2 Responds to a get request that contains data

    1 // Fig. 36.11: WelcomeServlet2.java

  • 7/30/2019 5.1 Servlets n Http Request

    28/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline2 // Processing HTTP get requests containing data.3

    4 import javax.servlet.*;

    5 import javax.servlet.http.*;

    6 import java.io.*;

    7

    8 publicclass WelcomeServlet2 extends HttpServlet {

    9

    10 // process "get" request from client

    11 protectedvoid doGet( HttpServletRequest request,

    12 HttpServletResponse response )

    13 throws ServletException, IOException

    14

    {15 String firstName = request.getParameter( "firstname" );

    16

    17 response.setContentType( "text/html" );

    18 PrintWriter out = response.getWriter();

    19

    20 // send XHTML document to client

    21

    22 // start XHTML document

    23 out.println( "" );

    24

    WelcomeServlet2

    (1 of 2)

    The request objectsgetParametermethod receives the

    parameter name and

    returns the

    correspondingStringvalue.

    25 out.println( "

  • 7/30/2019 5.1 Servlets n Http Request

    29/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline26 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +27 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

    28

    29 out.println( "" );

    30

    31 // head section of document

    32 out.println( "" );

    33 out.println(

    34 "Processing get requests with data" );

    35 out.println( "" );

    36

    37 // body section of document

    38out.println( "" );

    39 out.println( "Hello " + firstName + ",
    " );

    40 out.println( "Welcome to Servlets!" );

    41 out.println( "" );

    42

    43 // end XHTML document

    44 out.println( "" );

    45 out.close(); // close stream to complete the page

    46 }

    47 }

    WelcomeServlet2

    (2 of 2)

    Uses the result of line15 as part of the

    response to the client.

    1

  • 7/30/2019 5.1 Servlets n Http Request

    30/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline2

    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

    WelcomeServlet2

    .html

    (1 of 1)

    Get the first name

    from the user.

  • 7/30/2019 5.1 Servlets n Http Request

    31/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline

    Program output

  • 7/30/2019 5.1 Servlets n Http Request

    32/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.4 Handling HTTP get RequestsContaining Data (Cont.)

    Descriptor elementValueservletelementservlet-name welcome2description Handling HTTP get requests with data.servlet-class WelcomeServlet2servlet-mappingelementservlet-name welcome2url-pattern /welcome2Fig. 36.13 Deployment descriptor information for servlet

    WelcomeServlet2.

  • 7/30/2019 5.1 Servlets n Http Request

    33/57

    2004 Prentice Hall, Inc. All rights reserved.

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

    O tli

    1 // Fig. 36.14: WelcomeServlet3.java

  • 7/30/2019 5.1 Servlets n Http Request

    34/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline2 // Processing post requests containing data.3

    4 import javax.servlet.*;

    5 import javax.servlet.http.*;

    6 import java.io.*;

    7

    8 publicclass WelcomeServlet3 extends HttpServlet {

    9

    10 // process "post" request from client

    11 protectedvoid doPost( HttpServletRequest request,

    12 HttpServletResponse response )

    13 throws ServletException, IOException

    14{

    15 String firstName = request.getParameter( "firstname" );

    16

    17 response.setContentType( "text/html" );

    18 PrintWriter out = response.getWriter();

    19

    20 // send XHTML page to client

    21

    22 // start XHTML document

    23 out.println( "" );

    24

    WelcomeServlet3

    .java

    (1 of 2)

    Declare a doPost methodto responds to post requests.

    O tli

    25 out.println( "

  • 7/30/2019 5.1 Servlets n Http Request

    35/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline26 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +27 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

    28

    29 out.println( "" );

    30

    31 // head section of document

    32 out.println( "" );

    33 out.println(

    34 "Processing post requests with data" );

    35 out.println( "" );

    36

    37 // body section of document

    38

    out.println( "" );39 out.println( "Hello " + firstName + ",
    " );

    40 out.println( "Welcome to Servlets!" );

    41 out.println( "" );

    42

    43 // end XHTML document

    44 out.println( "" );

    45 out.close(); // close stream to complete the page

    46 }

    47 }

    WelcomeServlet3

    .java

    (1 of 2)

    O tli

    1 2 !DOCTYPE ht l PUBLIC " //W3C//DTD XHTML 1 0 St i t//EN"

  • 7/30/2019 5.1 Servlets n Http Request

    36/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline2

    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

    WelcomeServlet3

    .html

    (1 of 1)

    Provide a form in which theuser can input a name in the

    text input elementfirstname, then click theSubmit button to invokeWelcomeServlet3.

    O tli

  • 7/30/2019 5.1 Servlets n Http Request

    37/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline

    Program output

  • 7/30/2019 5.1 Servlets n Http Request

    38/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.5 Handling HTTP post Requests (Cont.)

    Descriptorelement Valueservletelementservlet-name welcome3description Handling HTTP post requests with

    data.servlet-class WelcomeServlet3

    servlet-mappingelementservlet-name welcome3url-pattern /welcome3Fig. 36.16 Deployment descriptor information for servlet

    WelcomeServlet3.

    36 6 R di ti R t t Oth

  • 7/30/2019 5.1 Servlets n Http Request

    39/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.6 Redirecting Requests to Other

    Resources

    Servlet RedirectServlet Redirects the request to a different resource

    Outline

    1 // Fig. 36.17: RedirectServlet.java

    2 // R di cti g t diff t W b g

  • 7/30/2019 5.1 Servlets n Http Request

    40/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline2 // Redirecting a user to a different Web page.3

    4 import javax.servlet.*;

    5 import javax.servlet.http.*;

    6 import java.io.*;

    7

    8 publicclass RedirectServlet extends HttpServlet {

    9

    10 // process "get" request from client

    11 protectedvoid doGet( HttpServletRequest request,

    12 HttpServletResponse response )

    13 throws ServletException, IOException

    14

    {15 String location = request.getParameter( "page" );

    16

    17 if ( location != null )

    18

    19 if ( location.equals( "deitel" ) )

    20 response.sendRedirect( "http://www.deitel.com" );

    21 else

    22 if ( location.equals( "welcome1" ) )

    23 response.sendRedirect( "welcome1" );

    24

    RedirectServlet.java

    (1 of 3)

    Obtains the pageparameter from the request.

    Determine if the value is either

    deitel or welcome1Redirects the request to

    www.deitel.com.

    Redirects the request to the

    servlet WelcomeServlet.

    Outline

    25 // code that executes only if this servlet26 // does not redirect the user to another page

  • 7/30/2019 5.1 Servlets n Http Request

    41/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline26 // does not redirect the user to another page27

    28 response.setContentType( "text/html" );

    29 PrintWriter out = response.getWriter();

    30

    31 // start XHTML document

    32 out.println( "" );

    33

    34 out.println( "" );

    37

    38

    out.println(39 "" );

    40

    41 // head section of document

    42 out.println( "" );

    43 out.println( "Invalid page" );

    44 out.println( "" );

    45

    46 // body section of document

    47 out.println( "" );

    48 out.println( "Invalid page requested" );

    RedirectServlet.java

    (2 of 3)

    Output a Web page indicating that aninvalid request was made if method

    sendRedirect is not called.

    Outline

    49 out.println( "

    " );

  • 7/30/2019 5.1 Servlets n Http Request

    42/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline50 \ servlets/RedirectServlet.html\ > );51 out.println( "Click here to choose again

    " );

    52 out.println( "" );

    53

    54 // end XHTML document

    55 out.println( "" );

    56 out.close(); // close stream to complete the page

    57 }

    58 }

    RedirectServlet.java

    (3 of 3)

    Outline

    1 2

  • 7/30/2019 5.1 Servlets n Http Request

    43/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline2

    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

    RedirectServlet.html

    (1 of 1)

    Provide hyperlinks that allow

    the user to invoke the servlet

    RedirectServlet.

    Outline

  • 7/30/2019 5.1 Servlets n Http Request

    44/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline

    Program output

    36 6 Redirecting Requests to other

  • 7/30/2019 5.1 Servlets n Http Request

    45/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.6 Redirecting Requests to other

    Resources (Cont.)

    Descriptor

    elementValue

    servletelementservlet-name

    redirect

    descriptionRedirecting to static Web pages and otherservlets.

    servlet-class

    com.deitel.iw3htp3.servlets.RedirectServlet

    servlet-mappingelementservlet-name

    redirect

    url-pattern/redirectFig. 36.19 Deployment descriptor information for servlet

    RedirectServlet.

    36 7 Multi Tier Applications: Using JDBC

  • 7/30/2019 5.1 Servlets n Http Request

    46/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.7 Multi-Tier Applications: Using JDBC

    from a Servlet

    Three-tier distributed applications User interface Business logic

    Database access

    Web servers often represent the middle tier Three-tier distributed application example

    SurveyServlet

    Survey.html

    MS Access database

    Outline

    1 // Fig. 36.20: SurveyServlet.java2 // A Web-based survey that uses JDBC from a servlet.

  • 7/30/2019 5.1 Servlets n Http Request

    47/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline// A Web based survey that uses JDBC from a servlet.3 package com.deitel.iw3htp3.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 Statement statement;

    14

    15 // set up database connection and create SQL statement

    16 public void init( ServletConfig config ) throws ServletException

    17 {

    18 // attempt database connection and create Statements

    19 try {

    20 Class.forName( config.getInitParameter( "databaseDriver" ) );

    21 connection = DriverManager.getConnection(22 config.getInitParameter( "databaseName" ) );

    23

    SurveyServlet.java

    (1 of 6)

    Servlets are initialized by

    overriding method init.

    Attempt to open a connection to

    the animalsurvey database.

    Loads the

    database driver.

    Outline

    24 // create Statement to query database25 statement = connection.createStatement();

    Create Statement tod t b

  • 7/30/2019 5.1 Servlets n Http Request

    48/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline();26 }

    27

    28 // for any exception throw an UnavailableException to

    29 // indicate that the servlet is not currently available

    30 catch ( Exception exception ) {

    31 exception.printStackTrace();

    32 throw new UnavailableException(exception.getMessage());

    33 }

    34

    35 } // end of init method

    36

    37

    // process survey response38 protected void doPost( HttpServletRequest request,

    39 HttpServletResponse response )

    40 throws ServletException, IOException

    41 {

    42 // set up response to client

    43 response.setContentType( "text/html" );

    44 PrintWriter out = response.getWriter();45 DecimalFormat twoDigits = new DecimalFormat( "0.00" );

    46

    47 // start XHTML document

    48 out.println( "" );

    49

    SurveyServlet.java

    (2 of 6)

    query database.

    Outline

    50 out.println( "

  • 7/30/2019 5.1 Servlets n Http Request

    49/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline// \ \ p // g52 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

    53

    54 out.println(

    55 "" );

    56

    57 // head section of document

    58 out.println( "" );

    59

    60 // read current survey response

    61 int value =

    62 Integer.parseInt( request.getParameter( "animal" ) );

    63

    String query;64

    65 // attempt to process a vote and display current results

    66 try {

    67

    68 // update total for current survey response

    69 query = "UPDATE surveyresults SET votes = votes + 1 " +

    70 "WHERE id = " + value;71 statement.executeUpdate( query );

    72

    SurveyServlet.java

    (3 of 6)

    Obtain the survey

    response

    Create query to update total

    for current survey response

    Execute queryto update total

    for current survey response

    Outline

    73 // get total of all survey responses74 query = "SELECT sum( votes ) FROM surveyresults";

    Create query to get total of all

    E l f

  • 7/30/2019 5.1 Servlets n Http Request

    50/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outlineq y y75 ResultSet totalRS = statement.executeQuery( query );

    76 totalRS.next();

    77 int total = totalRS.getInt( 1 );

    78

    79 // get results

    80 query = "SELECT surveyoption, votes, id FROM surveyresults " +

    81 "ORDER BY id";

    82 ResultSet resultsRS = statement.executeQuery( query );

    83 out.println( "Thank you!" );

    84 out.println( "" );

    85

    86 out.println( "" );

    87 out.println( "

    Thank you for participating." );

    88 out.println( "
    Results:

    " );

    89

    90 // process results

    91 int votes;

    92

    93 while ( resultsRS.next() ) {94 out.print( resultsRS.getString( 1 ) );

    95 out.print( ": " );

    96 votes = resultsRS.getInt( 2 );

    97 out.print( twoDigits.format(

    98 ( double ) votes / total * 100 ) );

    SurveyServlet.java

    (4 of 6)

    survey responsesExecute queryto get total of

    all survey responses

    Create query to getsurvey results

    Execute query to get

    survey results

    Outline

    99 out.print( "% responses: " );100 out.println( votes );

  • 7/30/2019 5.1 Servlets n Http Request

    51/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline101 }

    102

    103 resultsRS.close();

    104

    105 out.print( "Total responses: " );

    106 out.print( total );

    107

    108 // end XHTML document

    109 out.println( "" );

    110 out.close();

    111

    112 } // end try

    113

    114 // if database exception occurs, return error page

    115 catch ( SQLException sqlException ) {

    116 sqlException.printStackTrace();

    117 out.println( "Error" );

    118 out.println( "" );

    119 out.println( "

    Database error occurred. " );120 out.println( "Try again later.

    " );

    121 out.close();

    122 }

    123

    124 } // end of doPost method

    SurveyServlet.java

    (5 of 6)

    OutlineM h d d l

    125

    126 // close SQL statements and database when servlet terminates

  • 7/30/2019 5.1 Servlets n Http Request

    52/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline

    SurveyServlet.java

    (6 of 6)

    Method destroy closes

    Statement anddatabase connection.

    127 public void destroy()

    128 {

    129 // attempt to close statements and database connection

    130 try {

    131 statement.close();

    132 connection.close();

    133 }

    134

    135 // handle database exceptions by returning error to client

    136 catch ( SQLException sqlException ) {

    137 sqlException.printStackTrace();

    138 }

    139 }

    140

    141 } // end class SurveyServlet

    Outline

    1 2

  • 7/30/2019 5.1 Servlets n Http Request

    53/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline3 "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 Dog

    20 Cat
    22 Bird

    24 Snake

    Survey.html

    (1 of 2)

    Outline

    26 None

  • 7/30/2019 5.1 Servlets n Http Request

    54/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline28

    29

    30

    31

    32

    33

    34

    Survey.html

    (2 of 2)

    Outline

  • 7/30/2019 5.1 Servlets n Http Request

    55/57

    2004 Prentice Hall, Inc.All rights reserved.

    Outline

    36 7 Multi-Tier Applications: Using JDBC

  • 7/30/2019 5.1 Servlets n Http Request

    56/57

    2004 Prentice Hall, Inc. All rights reserved.

    36.7 Multi-Tier Applications: Using JDBC

    from a Servlet (Cont.)

    Descriptor element

    Valueservletelement

    servlet-name animalsurvey

    description Connecting to a database from a servlet.

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

    init-param

    param-name databaseDriverparam-value sun.jdbc.odbc.JdbcOdbcDriver

    init-param

    param-name databaseName

    param-value jdbc:odbc:animalsurvey

    servlet-mappingelement

    servlet-name animalsurveyurl-pattern /animalsurvey

    Fig. 36.22 Deployment descriptor information for servlet SurveyServlet.

  • 7/30/2019 5.1 Servlets n Http Request

    57/57

    36.8 Web Resources

    Servlet resources java.sun.com/products/servlet/index.html

    www.servlets.com

    www.servletsource.com

    www.servletforum.com

    www.coolservlets.com