java servlet specification version 2 - java community...

267
PROPOSED FINAL DRAFT PROPOSED FINAL DRAFT JavaServlet Specification Version 2.3 Please send technical comments to: [email protected] Please send business comments to: [email protected] Proposed Final Draft - October 20th 2000 Danny Coward ([email protected])

Upload: others

Post on 07-Feb-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

  • PROPOSED FINAL DRAFT

    PROPOSED FINAL DRAFT

    Java™ Servlet SpecificationVersion 2.3Please send technical comments to: [email protected] send business comments to: [email protected]

    Proposed Final Draft - October 20th 2000 Danny Coward ([email protected])

  • Java(TM) Servlet API Specification ("Specification")Version: 2.3Status: Pre-FCSRelease: October 20th, 2000

    Copyright 2000 Sun Microsystems, Inc.901 San Antonio Road, Palo Alto, California 94303, U.S.A.All rights reserved.

    NOTICEThe Specification is protected by copyright and the informationdescribed therein may be protected by one or more U.S. pat-ents, foreign patents, or pendingapplications. Except as provided under the following license, nopart of the Specification may be reproduced in any form by anymeans without the priorwritten authorization of Sun Microsystems, Inc. ("Sun") and itslicensors, if any. Any use of the Specification and the informa-tion described therein will begoverned by the terms and conditions of this license and theExport Control and General Terms as set forth in Sun’s websiteLegal Terms. By viewing,downloading or otherwise copying the Specification, you agreethat you have read, understood, and will comply with all of theterms and conditions set forthherein.

    Subject to the terms and conditions of this license, Sun herebygrants you a fully-paid, non-exclusive, non-transferable, world-wide, limited license (withoutthe right to sublicense) under Sun’s intellectual property rightsto review the Specification internally for the purposes of evalua-tion only. Other than thislimited license, you acquire no right, title or interest in or to theSpecification or any other Sun intellectual property. The Speci-fication contains theproprietary and confidential information of Sun and may only beused in accordance with the license terms set forth herein. Thislicense will expire ninety(90) days from the date of Release listed above and will termi-nate immediately without notice from Sun if you fail to complywith any provision of thislicense. Upon termination, you must cease use of or destroythe Specification.

    TRADEMARKSNo right, title, or interest in or to any trademarks, service marks,or trade names of Sun or Sun’s licensors is granted hereunder.Sun, Sun Microsystems, theSun logo, Java, and the Java Coffee Cup logo, are trademarksor registered trademarks of Sun Microsystems, Inc. in the U.S.and other countries.

    DISCLAIMER OF WARRANTIESTHE SPECIFICATION IS PROVIDED "AS IS" AND IS EXPERI-MENTAL AND MAY CONTAIN DEFECTS OR DEFICIENCIESWHICHCANNOT OR WILL NOT BE CORRECTED BY SUN. SUNMAKES NO REPRESENTATIONS OR WARRANTIES, EITHEREXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIESOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PUR-POSE, OR

    NON-INFRINGEMENT THAT THE CONTENTS OF THE SPEC-IFICATION ARE SUITABLE FOR ANY PURPOSE OR THATANY PRACTICEOR IMPLEMENTATION OF SUCH CONTENTS WILL NOTINFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,TRADE SECRETS OROTHER RIGHTS. This document does not represent any com-mitment to release or implement any portion of the Specificationin any product.

    THE SPECIFICATION COULD INCLUDE TECHNICAL INAC-CURACIES OR TYPOGRAPHICAL ERRORS. CHANGESARE PERIODICALLYADDED TO THE INFORMATION THEREIN; THESECHANGES WILL BE INCORPORATED INTO NEW VERSIONSOF THE SPECIFICATION,IF ANY. SUN MAY MAKE IMPROVEMENTS AND/ORCHANGES TO THE PRODUCT(S) AND/OR THE PRO-GRAM(S) DESCRIBED IN THESPECIFICATION AT ANY TIME. Any use of such changes inthe Specification will be governed by the then-current license forthe applicable version ofthe Specification.

    LIMITATION OF LIABILITYTO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENTWILL SUN OR ITS LICENSORS BE LIABLE FOR ANY DAM-AGES, INCLUDINGWITHOUT LIMITATION, LOST REVENUE, PROFITS OR DATA,OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDEN-TAL ORPUNITIVE DAMAGES, HOWEVER CAUSED AND REGARD-LESS OF THE THEORY OF LIABILITY, ARISING OUT OF ORRELATED TO ANYFURNISHING, PRACTICING, MODIFYING OR ANY USE OFTHE SPECIFICATION, EVEN IF SUN AND/OR ITS LICEN-SORS HAVE BEENADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

    You will indemnify, hold harmless, and defend Sun and its licen-sors from any claims based on your use of the Specification forany purposes other than thoseof internal evaluation, and from any claims that later versions orreleases of any Specification furnished to you are incompatiblewith the Specificationprovided to you under this license.

    RESTRICTED RIGHTS LEGENDIf this Software is being acquired by or on behalf of the U.S.Government or by a U.S. Government prime contractor or sub-contractor (at any tier), then theGovernment’s rights in the Software and accompanyingdocumentation shall be only as set forth in this license; this is inaccordance with 48 C.F.R. 227.7201 through 227.7202-4 (forDepartment of Defense (DoD)acquisitions) and with 48 C.F.R. 2.101 and 12.212 (for non-DoDacquisitions).

    REPORTYou may wish to report any ambiguities, inconsistencies or inac-curacies you may find in connection with your evaluation of theSpecification ("Feedback").To the extent that you provide Sun with any Feedback, youhereby: (i) agree that such Feedback is provided on a non-pro-prietary and non-confidential

  • basis, and (ii) grant Sun a perpetual, non-exclusive, worldwide,fully paid-up, irrevocable license, with the right to sublicensethrough multiple levels ofsublicensees, to incorporate, disclose, and use without limita-tion the Feedback for any purpose related to the Specificationand future versions,implementations, and test suites thereof.

  • PROPOSED FINAL DRAFT

    Contents

    Status .................................................................................................12

    Changes in this document since v2.2........................................... 12

    Preface ...............................................................................................14

    Who should read this document .................................................. 14

    API Reference ............................................................................. 14

    Other Java™ Platform Specifications.......................................... 14

    Other Important References ........................................................ 15

    Providing Feedback..................................................................... 16

    Acknowledgements ..................................................................... 16

    Chapter 1: Overview.......................................................................... 18

    What is a Servlet?........................................................................ 18

    What is a Servlet Container? ....................................................... 18

    An Example................................................................................. 19

    Comparing Servlets with Other Technologies ............................. 19

    Relationship to Java 2 Platform Enterprise Edition ..................... 20

    Chapter 2: The Servlet Interface...................................................... 22

    Request Handling Methods ......................................................... 22

    HTTP Specific Request Handling Methods........................ 22

    Contents 4

  • PROPOSED FINAL DRAFT

    Conditional GET Support ...................................................23

    Number of Instances ....................................................................23

    Note about SingleThreadModel ..........................................24

    Servlet Life Cycle ........................................................................24

    Loading and Instantiation ...................................................24

    Initialization........................................................................24

    Request Handling ...............................................................25

    End of Service ....................................................................27

    Chapter 3: Servlet Context................................................................28

    Scope of a ServletContext............................................................28

    Initialization Parameters ..............................................................28

    Context Attributes........................................................................29

    Context Attributes in a Distributed Container.....................29

    Resources.....................................................................................29

    Multiple Hosts and Servlet Contexts............................................30

    Reloading Considerations ............................................................30

    Temporary Working Directories ..................................................31

    Chapter 4: The Request.....................................................................32

    Parameters ...................................................................................32

    Attributes .....................................................................................33

    Headers ........................................................................................33

    Request Path Elements.................................................................34

    Path Translation Methods ............................................................35

    Cookies ........................................................................................36

    SSL Attributes .............................................................................36

    Internationalization ......................................................................37

    Request data encoding .................................................................37

    5 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    Chapter 5: The Response.................................................................. 38

    Buffering ..................................................................................... 38

    Headers........................................................................................ 39

    Convenience Methods ................................................................. 40

    Internationalization...................................................................... 40

    Closure of Response Object ........................................................ 41

    Chapter 6: Servlet Filtering .............................................................. 42

    What is a filter ? .......................................................................... 42

    Examples of Filtering Components .................................... 43

    Main Concepts............................................................................. 43

    Filter Lifecycle................................................................... 43

    Filter environment .............................................................. 45

    Configuration of Filters in a Web Application ................... 45

    Chapter 7: Sessions............................................................................ 48

    Session Tracking Mechanisms .................................................... 48

    URL Rewriting................................................................... 48

    Cookies .............................................................................. 49

    SSL Sessions...................................................................... 49

    Session Integrity................................................................. 49

    Creating a Session ....................................................................... 49

    Session Scope.............................................................................. 50

    Binding Attributes into a Session ................................................ 50

    Session Timeouts......................................................................... 50

    Last Accessed Times ................................................................... 51

    Important Session Semantics....................................................... 51

    Threading Issues ................................................................ 51

    Distributed Environments................................................... 51

    Contents 6

  • PROPOSED FINAL DRAFT

    Client Semantics .................................................................52

    Chapter 8: Dispatching Requests......................................................54

    Obtaining a RequestDispatcher....................................................54

    Query Strings in Request Dispatcher Paths.........................55

    Using a Request Dispatcher .........................................................55

    Include .........................................................................................56

    Included Request Parameters ..............................................56

    Forward........................................................................................56

    Query String .......................................................................57

    Error Handling .............................................................................57

    Chapter 9: Web Applications.............................................................58

    Relationship to ServletContext ....................................................58

    Elements of a Web Application ...................................................58

    Distinction Between Representations...........................................59

    Directory Structure ......................................................................59

    Sample Web Application Directory Structure.....................60

    Web Application Archive File .....................................................60

    Web Application Configuration Descriptor .................................61

    Dependencies on extensions: Library Files.........................61

    Web Application Classloader..............................................62

    Replacing a Web Application ......................................................62

    Error Handling .............................................................................62

    Welcome Files .............................................................................63

    Web Application Environment ....................................................64

    Chapter 10: Application Lifecycle Events........................................66

    Introduction .................................................................................66

    Event Listeners ............................................................................66

    7 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    Configuration of Listener Classes ............................................... 68

    Listener Instances and Threading ................................................ 69

    Distributed Containers................................................................. 69

    Session Events- Invalidation vs Timeout..................................... 69

    Chapter 11: Mapping Requests to Servlets...................................... 70

    Use of URL Paths........................................................................ 70

    Specification of Mappings........................................................... 71

    Implicit Mappings .............................................................. 71

    Example Mapping Set ........................................................ 71

    Chapter 12: Security.......................................................................... 74

    Introduction ................................................................................. 74

    Declarative Security .................................................................... 75

    Programmatic Security ................................................................ 75

    Roles ........................................................................................... 76

    Authentication ............................................................................. 76

    HTTP Basic Authentication ............................................... 76

    HTTP Digest Authentication.............................................. 77

    Form Based Authentication................................................ 77

    HTTPS Client Authentication ............................................ 78

    Server Tracking of Authentication Information .......................... 79

    Propogation of Security Identity.................................................. 79

    Specifying Security Constraints .................................................. 80

    Default Policies .................................................................. 80

    Chapter 13: Deployment Descriptor................................................. 82

    Deployment Descriptor Elements................................................ 82

    Deployment Descriptor DOCTYPE ................................... 82

    DTD ............................................................................................ 83

    Contents 8

  • PROPOSED FINAL DRAFT

    Examples .....................................................................................96

    A Basic Example ................................................................97

    An Example of Security......................................................98

    Chapter 14: API Details.....................................................................100

    Config.................................................................................... 104

    Filter ...................................................................................... 106

    FilterConfig........................................................................... 108

    GenericServlet....................................................................... 110

    RequestDispatcher ................................................................ 115

    Servlet ................................................................................... 117

    ServletConfig ........................................................................ 120

    ServletContext....................................................................... 121

    ServletContextAttributeEvent ............................................... 129

    ServletContextAttributesListener.......................................... 131

    ServletContextEvent ............................................................. 133

    ServletContextListener.......................................................... 135

    ServletException ................................................................... 136

    ServletInputStream................................................................ 139

    ServletOutputStream............................................................. 141

    ServletRequest ...................................................................... 146

    ServletRequestWrapper ........................................................ 153

    ServletResponse .................................................................... 159

    ServletResponseWrapper ...................................................... 163

    SingleThreadModel............................................................... 167

    UnavailableException ........................................................... 168

    Cookie ................................................................................... 173

    HttpServlet ............................................................................ 179

    9 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    HttpServletRequest ............................................................... 185

    HttpServletRequestWrapper ................................................. 193

    HttpServletResponse............................................................. 200

    HttpServletResponseWrapper ............................................... 212

    HttpSession ........................................................................... 217

    HttpSessionAttributesListener .............................................. 222

    HttpSessionBindingEvent ..................................................... 224

    HttpSessionBindingListener ................................................. 227

    HttpSessionContext............................................................... 228

    HttpSessionEvent .................................................................. 229

    HttpSessionListener .............................................................. 231

    HttpUtils................................................................................ 232

    Appendix A: Deployment Descriptor Version 2.2............................ 236

    Appendix B: Glossary ........................................................................ 250

    Contents 10

  • PROPOSED FINAL DRAFT

    11 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    ent

    draft

    Status

    This specification is being developed following the Java Community Process. This documis the Proposed Final Draft version of the Java Servlet 2.3 Specification.

    Changes in this document since version 2.2• Incorporation of Javadoc API definitions into the specification document

    • Application Events

    • Servlet Filtering

    • Requirement of J2SE as the underlying platform for web containers

    • Dependencies on installed extensions

    • Internationalization fixes

    • Incorporation of Servlet 2.2 errata and numerous other clarifications

    Changes since Public DraftHere is a summary of the main items that have changed in the specification since publicbased on a large amount of feedback.

    Specification document changes• Added 2.2 deployment descriptor as appendix

    • Added change list

    • Many editorial changes

    Status 12

  • PROPOSED FINAL DRAFT

    see

    Servlets - Chapter 2• Added doHead() method back to HttpServlet (see API)

    ServletContexts - Chapter 3• added getServletContextName() (see API)

    • added getResourcePaths() (see API)

    Request - Chapter 4• Add attributes for error processing

    • Added UnsupportedCharacterEncoding to throws clause of setCharacterEncoding() (API)

    • getQueryString() - specify value is not decoded (see API)

    • getParameterMap() - return value is immutable (see API)

    • clarify getAuthType() javadoc, added statics for authentication types (see API)

    • clarify default character encoding

    • clarify behavior of getRealPath() (see API)

    • clarification of HttpServletRequest.getHeaders() when name not found (see API)

    Response - Chapter 5• clarify status code on response when errors occur (see API)

    • added resetBuffer() method to ServletResponse (see API)

    • sendError clarifrications (see API))

    • disallow container defaulting the content type of a response

    • clarify behavior of flush() on PrintWriter and ServletOutputStream (see API)

    • clarify default character encoding of response

    • clarify what container does with headers on setStatus() (see API)

    • sendRedirect() clarification for non-absolute URLs (API doc)

    • sendError() clarifications (API doc)

    13 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT • October 20, 2000

  • PROPOSED FINAL DRAFT

    o

    Filters - Chapter 6• Scoping of filter instances

    • Clarification of filters acting on static resources

    • Added FilterChain interface and minor refactoring

    • Removed Config interface

    • Added set{Response,Request} methods to filter wrapper classes

    Sessions - Chapter 7• Addition of HttpSessionActivationListener interface used in distributed containers (als

    see API)

    • Clarification of semantics for persisting & migrating sessions in distributed containers

    • many clarifications of session expiry and notification, order of notification (see API)

    Application Event Listeners - Chapter 10• Clarifying notifications on shutdown and ordering thereof

    RequestMappings - Chapter 11• clarified servlet mapped to /foo/* is called by a request for /foo

    • Request matching is done by case-sensitive string match

    Security - Chapter 12• Specify a default behavior for isUserInRole() in absernce of role-refs

    • Clarify interaction between RequestDispatcher and security model

    • Clarify policy for processing multiple security constraints

    • Added security attributes for SSL algorithm

    • Specify status code for failed form login

    • Specify allowed methods of return for form login error page

    Status 14

  • PROPOSED FINAL DRAFT

    king

    Deployment Descriptor - Chapter 13• corrected bad comment for ejb-ref-type

    • clarifying web container policy for whitespace in the deployment descriptor

    • clarifying paths in deployment descriptor are assumed decoded

    • recommend validation of deployment descriptor documents and some semantic checby web containers as aid to developers

    • policy for paths refering to resources in the WAR: must start with ’/’

    • clarify policy for relativizing policy of paths in web.xml

    • added display name to security-constraint for tool manipulation

    • fix security example

    • Use of "*" to mean ’all roles’ in the security-constraint element

    • syntax for specifying sharing scope for connection factory connections

    • syntax for declaring dependencies on administered objects in J2EE

    • clarify path usage

    • clarify path usage

    • snyc with EJB and EE specs on allowed strings in res-auth element

    • clarify 2.2 dtd must be supported for backwards compatibility

    15 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT • October 20, 2000

  • PROPOSED FINAL DRAFT

    ce

    ility

    ssues.

    t

    to

    as

    ces,s the

    Preface

    This document, the Java™ Servlet Specification, v2.3 the Java Servlet API. The referenimplementation provides a behavioral benchmark. In the case of an area where thespecification leaves implementation of a particular feature open to interpretation,implementors should look first to the reference implementation and then to the compatibtest suite. If further clarification is required, the working group for the Java Servlet APIunder the Java Community Process should be consulted and is the final arbiter of such i

    Who should read this documentThis document is intended for consumption by:

    • Web Server and Application Server vendors that want to provide Servlet Engines thaconform with this specification.

    • Web Authoring Tool developers that want to generate Web Applications that conformthis specification

    • Sophisticated Servlet authors who want to understand the underlying mechanisms ofServlet technology.

    Please note that this specification is not a User’s Guide and is not intended to be usedsuch.

    API ReferenceThe Java Servlet API Reference, v2.3 provides the complete description of all the interfaclasses, exceptions, and methods that compose the Servlet API. This document containfull specification of class, interfaces, method signatures and accompanying javadoc thatdefines the Servlet API.

    Preface 14

  • PROPOSED FINAL DRAFT

    d

    P

    Other Java™ Platform SpecificationsThe following Java API Specifications are referenced throughout this specification:

    • Java2 Platform Enterprise Edition, v1.3 (J2EE)

    • JavaServer Pages™, v1.2 (JSP)

    • Java Naming and Directory Interface (JNDI)

    These specifications may be found at the Java2 Enterprise Edition website:http://java.sun.com/j2ee/

    Other Important ReferencesThe following Internet Specifications provide relevant information to the development animplementation of the Servlet API and engines which support the Servlet API:

    • RFC 1630 Uniform Resource Identifiers (URI)

    • RFC 1738 Uniform Resource Locators (URL)

    • RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax

    • RFC 1808 Relative Uniform Resource Locators

    • RFC 1945 Hypertext Transfer Protocol (HTTP/1.0)

    • RFC 2045 MIME Part One: Format of Internet Message Bodies

    • RFC 2046 MIME Part Two: Media Types

    • RFC 2047 MIME Part Three: Message Header Extensions for non-ASCII text

    • RFC 2048 MIME Part Four: Registration Procedures

    • RFC 2049 MIME Part Five: Conformance Criteria and Examples

    • RFC 2109 HTTP State Management Mechanism

    • RFC 2145 Use and Interpretation of HTTP Version Numbers

    • RFC 2324 Hypertext Coffee Pot Control Protocol (HTCPCP/1.0)1

    • RFC 2616 Hypertext Transfer Protocol (HTTP/1.1)

    • RFC 2617 HTTP Authentication: Basic and Digest Authentication

    You can locate the online versions of any of these RFCs at:

    http://www.rfc-editor.org/

    The World Wide Web Consortium (http://www.w3.org/ ) is a definitive source ofHTTP related information that affects this specification and its implementations.

    1. This reference is mostly tongue-in-cheek although most of the concepts described in the HTCPCRFC are relevant to all well designed web servers.

    15 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    g

    unity.s to:

    eivehived

    The Extensible Markup Language (XML) is utilized by the Deployment Descriptorsdescribed in this specification. More information about XML can be found at the followinwebsites:

    http://java.sun.com/

    http://www.xml.org/

    Providing FeedbackThe success of the Java Community Process depends on your participation in the commWe welcome any and all feedback about this specification. Please e-mail your comment

    [email protected]

    Please note that due to the volume of feedback that we receive, you will not normally reca reply from an engineer. However, each and every comment is read, evaluated, and arcby the specification team.

    AcknowledgementsThis public draft represents the team work of the JSR053 expert group.

    Preface 16

  • PROPOSED FINAL DRAFT

    17 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    t.alwith

    TTP).

    euests,rvlets

    an

    may). The

    as

    CHAPTER 1

    Overview

    This chapter provides an overview of the Servlet API.

    1.1 What is a Servlet?A servlet is a web component, managed by a container, that generates dynamic contenServlets are small, platform independent Java classes compiled to an architecture neutrbytecode that can be loaded dynamically into and run by a web server. Servlets interactweb clients via a request response paradigm implemented by the servlet container. Thisrequest-response model is based on the behavior of the Hypertext Transfer Protocol (H

    1.2 What is a Servlet Container?The servlet container, in conjunction with a web server or application server, provides thnetwork services over which requests and responses are set, decodes MIME based reqand formats MIME based responses. A servlet container also contains and manages sethrough their lifecycle.

    A servlet container can either be built into a host web server or installed as an add-oncomponent to a Web Server via that server’s native extension API. Servlet Containers calso be built into or possibly installed into web-enabled Application Servers.

    All servlet containers must support HTTP as a protocol for requests and responses, butalso support other request / response based protocols such as HTTPS (HTTP over SSLminimum required version of the HTTP specification that a container must implement isHTTP/1.0. It is strongly suggested that containers implement the HTTP/1.1 specificationwell.

    Overview 18

  • PROPOSED FINAL DRAFT

    risenlimit

    quest.Thendn ina

    rvletback

    se is

    esams

    s

    A Servlet Container may place security restrictions on the environment that a servletexecutes in. In a Java 2 Platform Standard Edition 1.2 (J2SE) or Java 2 Platform EnterpEdition 1.3 (J2EE) environment, these restrictions should be placed using the permissioarchitecture defined by Java 2 Platform. For example, high end application servers maycertain action, such as the creation of aThread object, to insure that other components ofthe container are not negatively impacted.

    1.3 An ExampleA client program, such as a web browser, accesses a web server and makes an HTTP reThis request is processed by the web server and is handed off to the servlet container.servlet container determines which servlet to invoke based on its internal configuration acalls it with objects representing the request and response. The servlet container can ruthe same process as the host web server, in a different process on the same host, or ondifferent host from the web server for which it processes requests.

    The servlet uses the request object to find out who the remote user is, what HTML formparameters may have been sent as part of this request, and other relevant data. The secan then perform whatever logic it was programmed with and can generate data to sendto the client. It sends this data back to the client via the response object.

    Once the servlet is done with the request, the servlet container ensures that the responproperly flushed and returns control back to the host web server.

    1.4 Comparing Servlets with Other TechnologiIn functionality, servlets lie somewhere between Common Gateway Interface (CGI) progrand proprietary server extensions such as the Netscape Server API (NSAPI) or ApacheModules.

    Servlets have the following advantages over other server extension mechanisms:

    • They are generally much faster than CGI scripts because a different process model iused.

    • They use a standard API that is supported by many web servers.

    • They have all the advantages of the Java programming language, including ease ofdevelopment and platform independence.

    • They can access the large set of APIs available for the Java platform.

    19 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    that

    1.5 Relationship to Java 2 Platform EnterpriseEditionThe Servlet API v2.3 is a required API of the Java 2 Platform Enterprise Edition, v1.31. TheJ2EE specification describes additional requirements for servlet containers, and servletsare deployed into them, that are executing in a J2EE environment.

    1. Please see the Java 2 Platform Enterprise Edition specification available athttp://java.sun.com/j2ee/

    Chapter 1 Overview 20

  • PROPOSED FINAL DRAFT

    21 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    nte

    rvlet.

    CHAPTER 2

    The Servlet Interface

    TheServlet interface is the central abstraction of the Servlet API. All servlets implemethis interface either directly, or more commonly, by extending a class that implements thinterface. The two classes in the API that implement theServlet interface areGenericServlet andHttpServlet . For most purposes, developers will typicallyextendHttpServlet to implement their servlets.

    2.1 Request Handling MethodsThe basicServlet interface defines aservice method for handling client requests. Thismethod is called for each request that the servlet container routes to an instance of a seMultiple request threads may be executing within the service method at any time.

    2.1.1 HTTP Specific Request Handling Methods

    The HttpServlet abstract subclass adds additional methods which are automaticallycalled by theservice method in theHttpServlet class to aid in processing HTTPbased requests. These methods are:

    • doGet for handling HTTP GET requests

    • doPost for handling HTTP POST requests

    • doPut for handling HTTP PUT requests

    • doDelete for handling HTTP DELETE requests

    • doHead for handling HTTP HEAD requests

    • doOptions for handling HTTP OPTIONS requests

    • doTrace for handling HTTP TRACE requests

    The Servlet Interface 22

  • PROPOSED FINAL DRAFT

    to

    ts

    ders

    s abody

    ient

    aass

    te

    Typically when developing HTTP based servlets, a Servlet Developer will only concernhimself with thedoGet anddoPost methods. The rest of these methods are consideredbe advanced methods for use by programmers very familiar with HTTP programming.

    ThedoPut anddoDelete methods allow Servlet Developers to support HTTP/1.1 clienwhich support these features. ThedoHead method inHttpServlet is a specializedmethod that will execute thedoGet method, but only return the headers produced by thedoGet method to the client. ThedoOptions method automatically determines whichHTTP methods are directly supported by the servlet and returns that information to theclient. ThedoTrace method causes a response with a message containing all of the heasent in the TRACE request.

    In containers that only support HTTP/1.0, only thedoGet , doHead anddoPost methodswill be used as HTTP/1.0 does not define the PUT, DELETE, OPTIONS, or TRACEmethods.

    2.1.2 Conditional GET Support

    The HttpServlet interface defines thegetLastModified method to supportconditional get operations. A conditional get operation is one in which the client requestresource with the HTTP GET method and adds a header that indicates that the contentshould only be sent if it has been modified since a specified time.

    Servlets that implement thedoGet method and that provide content that does notnecessarily change from request to request should implement this method to aid in efficutilization of network resources.

    2.2 Number of InstancesIn the default case of a servlet not implementing SingleThreadModel and not hosted indistributed environment, the servlet container must use only one instance of a servlet clper servlet definition.

    In the case of a servlet that implements theSingleThreadModel interface, the servletcontainer may instantiate multiple instances of that servlet so that it can handle a heavyrequest load while still serializing requests to a single instance.

    In the case where a servlet was deployed as part of an application that is marked in thedeployment descriptor asdistributable, there is one instance of a servlet class per servletdefinition per VM in a container. If the servlet implements theSingleThreadModelinterface as well as is part of a distributable web application, the container may instantiamultiple instances of that servlet in each VM of the container.

    23 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    l

    one

    ice.

    tionr

    ele

    t

    et

    tread

    2.2.1 Note about SingleThreadModel

    The use of theSingleThreadModel interface guarantees that one thread at a time wilexecute through a given servlet instance’sservice method. It is important to note that thisguarantee only applies to servlet instance. Objects that can be accessible to more thanservlet instance at a time, such as instances ofHttpSession , may be available to multipleservlets, including those that implementSingleThreadModel , at any particular time.

    2.3 Servlet Life CycleA servlet is managed through a well defined life cycle that defines how it is loaded,instantiated and initialized, handles requests from clients, and how it is taken out of servThis life cycle is expressed in the API by theinit , service , anddestroy methods ofthe javax.servlet.Servlet interface that all servlets must, directly or indirectlythrough theGenericServlet or HttpServlet abstract classes, implement.

    2.3.1 Loading and Instantiation

    The servlet container is responsible for loading and instantiating a servlet. The instantiaand loading can occur when the engine is started or it can be delayed until the containedetermines that it needs the servlet to service a request.

    First, a class of the servlet’s type must be located by the servlet container. If needed, thservlet container loads a servlet using normal Java class loading facilities from a local fisystem, a remote file system, or other network services.

    After the container has loaded theServlet class, it instantiates an object instance of thaclass for use.

    It is important to note that there can be more than one instance of a givenServlet class inthe servlet container. For example, this can occur where there was more than one servldefinition that utilized a specific servlet class with different initialization parameters. Thiscan also occur when a servlet implements theSingleThreadModel interface and thecontainer creates a pool of servlet instances to use.

    2.3.2 Initialization

    After the servlet object is loaded and instantiated, the container must initialize the servlebefore it can handle requests from clients. Initialization is provided so that a servlet canany persistent configuration data, initialize costly resources (such as JDBC™ based

    Chapter 2 The Servlet Interface 24

  • PROPOSED FINAL DRAFT

    let

    ject

    and

    nd

    red.

    or

    ts.

    connection), and perform any other one-time activities. The container initializes the servby calling theinit method of theServlet interface with a unique (per servlet definition)object implementing theServletConfig interface. This configuration object allows theservlet to access name-value initialization parameters from the servlet container’sconfiguration information. The configuration object also gives the servlet access to an obimplementing theServletContext interface which describes the runtime environmentthat the servlet is running within. See Chapter 3, “Servlet Context” for more informationabout theServletContext interface.

    2.3.2.1 Error Conditions on Initialization

    During initialization, the servlet instance can signal that it is not to be placed into activeservice by throwing anUnavailableException or ServletException . If aservlet instance throws an exception of this type, it must not be placed into active servicethe instance must be immediately released by the servlet container. Thedestroy method isnot called in this case as initialization was not considered to be successful.

    After the instance of the failed servlet is released, a new instance may be instantiated ainitialized by the container at any time. The only exception to this rule is if theUnavailableException thrown by the failed servlet which indicates the minimumtime of unavailability. In this case, the container must wait for the minimum time ofunavailability to pass before creating and initializing a new servlet instance.

    2.3.2.2 Tool Considerations

    When a tool loads and introspects a web application, it may load and introspect membeclasses of the web application. This will trigger static initialization methods to be executBecause of this behavior, a Developer should not assume that a servlet is in an activecontainer runtime unless theinit method of theServlet interface is called. Forexample, this means that a servlet should not try to establish connections to databasesEnterprise JavaBeans™ compenent architecture containers when its static (class)initialization methods are invoked.

    2.3.3 Request Handling

    After the servlet is properly initialized, the servlet container may use it to handle requesEach request is represented by a request object of typeServletRequest and the servletcan create a response to the request by using the provided object of typeServletResponse . These objects are passed as parameters to theservice method ofthe Servlet interface. In the case of an HTTP request, the container must provide therequest and response objects as implementations ofHttpServletRequest andHttpServletResponse .

    25 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    a

    ple

    A

    enVM

    ce

    sures

    d ofust

    se

    It is important to note that a servlet instance may be created and placed into service byservlet container but may handle no requests during its lifetime.

    2.3.3.1 Multithreading Issues

    During the course of servicing requests from clients, a servlet container may send multirequests from multiple clients through theservice method of the servlet at any one time.This means that the Developer must take care to make sure that the servlet is properlyprogrammed for concurrency.

    If a Developer wants to prevent this default behavior, he can program the servlet toimplement theSingleThreadModel interface. Implementing this interface willguarantee that only one request thread at a time will be allowed in the service method.servlet container may satisfy this guarantee by serializing requests on a servlet or bymaintaining a pool of servlet instances. If the servlet is part of an application that has bemarked as distributable, the container may maintain a pool of servlet instances in eachthat the application is distributed across.

    If a Developer defines aservice method (or methods such asdoGet or doPost whichare dispatched to from theservice method of theHttpServlet abstract class) with thesynchronized keyword, the servlet container will, by necessity of the underlying Javaruntime, serialize requests through it. However, the container must not create an instanpool as it does for servlets that implement theSingleThreadModel . It is stronglyrecommended that developers not synchronize the service method or any of theHttpServlet service methods such asdoGet , doPost , etc.

    2.3.3.2 Exceptions During Request Handling

    A servlet may throw either aServletException or anUnavailableExceptionduring the service of a request. AServletException signals that some error occurredduring the processing of the request and that the container should take appropriate meato clean up the request. AnUnavailableException signals that the servlet is unable tohandle requests either temporarily or permanently.

    If a permanent unavailability is indicated by theUnavailableException , the servletcontainer must remove the servlet from service, call itsdestroy method, and release theservlet instance.

    If temporary unavailability is indicated by theUnavailableException , then thecontainer may choose to not route any requests through the servlet during the time periothe temporary unavailability. Any requests refused by the container during this period mbe returned with aSERVICE_UNAVAILABLE(503) response status along with aRetry-After header indicating when the unavailability will terminate. The container may chooto ignore the distinction between a permanent and temporary unavailability and treat allUnavailableExceptions as permanent, thereby removing a servlet that throws anyUnavailableException from service.

    Chapter 2 The Servlet Interface 26

  • PROPOSED FINAL DRAFT

    notf thegiven

    vletheany

    oring

    a

    nythe

    2.3.3.3 Thread Safety

    A Developer should note that implementations of the request and response objects areguaranteed to be thread safe. This means that they should only be used in the scope orequest handling thread. References to the request and response objects should not beto objects executing in other threads as the behavior may be nondeterministic.

    2.3.4 End of Service

    The servlet container is not required to keep a servlet loaded for any period of time. A serinstance may be kept active in a servlet container for a period of only milliseconds, for tlifetime of the servlet container (which could be measured in days, months, or years), oramount of time in between.

    When the servlet container determines that a servlet should be removed from service (fexample, when a container wants to conserve memory resources, or when it itself is beshut down), it must allow the servlet to release any resources it is using and save anypersistent state. To do this the servlet container calls thedestroy method of theServletinterface.

    Before the servlet container can call thedestroy method, it must allow any threads thatare currently running in theservice method of the servlet to either complete, or exceedserver defined time limit, before the container can proceed with calling thedestroymethod.

    Once thedestroy method is called on a servlet instance, the container may not route amore requests to that particular instance of the servlet. If the container needs to enableservlet again, it must do so with a new instance of the servlet’s class.

    After the destroy method completes, the servlet container must release the servletinstance so that it is eligible for garbage collection

    27 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    any

    are

    CHAPTER 3

    Servlet Context

    The ServletContext defines a servlet’s view of the web application within which theservlet is running. TheServletContext also allows a servlet to access resourcesavailable to it. Using such an object, a servlet can log events, obtain URL references toresources, and set and store attributes that other servlets in the context can use. TheContainer Provider is responsible for providing an implementation of theServletContext interface in the servlet container.

    A ServletContext is rooted at a specific path within a web server. For example acontext could be located athttp://www.mycorp.com/catalog . All requests thatstart with the/catalog request path, which is known as thecontext path, will be routed tothis servlet context.

    3.1 Scope of a ServletContextThere is one instance of theServletContext interface associated with each webapplication deployed into a container. In cases where the container is distributed over mvirtual machines, there is one instance per web application per VM.

    Servlets that exist in a container that were not deployed as part of a web application areimplicitly part of a “default” web application and are contained by a defaultServletContext . In a distributed container, the defaultServletContext is non-distributable and must only exist on one VM.

    3.2 Initialization ParametersA set of context initialization parameters can be associated with a web application andmade available by the following methods of theServletContext interface:

    Servlet Context 28

  • PROPOSED FINAL DRAFT

    ritical

    Ifhatset in

    oftion

    • getInitParameter

    • getInitParameterNames

    Initialization parameters can be used by an application developer to convey setupinformation, such as a webmaster’s e-mail address or the name of a system that holds cdata.

    3.3 Context AttributesA servlet can bind an object attribute into the context by name. Any object bound into acontext is available to any other servlet that is part of the same web application. Thefollowing methods ofServletContext interface allow access to this functionality:

    • setAttribute

    • getAttribute

    • getAttributeNames

    • removeAttribute

    3.3.1 Context Attributes in a Distributed Container

    Context attributes exist locally to the VM in which they were created and placed. Thisprevents theServletContext from being used as a distributed shared memory store.information needs to be shared between servlets running in a distributed environment, tinformation should be placed into a session (See Chapter 8, “Sessions”), a database oran Enterprise JavaBean.

    3.4 ResourcesThe ServletContext interface allows direct access to the static document hierarchycontent documents, such as HTML, GIF, and JPEG files, that are part of the web applicavia the following methods of theServletContext interface:

    • getResource

    • getResourceAsStream

    Both thegetResource andgetResourceAsStream methods take aStringargument giving the path of the resource relative to the root of the context.

    29 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    webnotages

    ts” for

    ress

    wntual

    f

    to

    fded incted

    It is important to note that these methods give access to static resources from whateverrepository the server uses. This hierarchy of documents may exist in a file system, in aapplication archive file, on a remote server, or some other location. These methods areused to obtain dynamic content. For example, in a container supporting the JavaServer Pspecification1, a method call of the formgetResource("/index.jsp") would returnthe JSP source code and not the processed output. See Chapter 8, “Dispatching Requesmore information about accessing dynamic content.

    3.5 Multiple Hosts and Servlet ContextsMany web servers support the ability for multiple logical hosts to share the same IP addon a server. This capability is sometimes referred to as "virtual hosting". If a servletcontainer’s host web server has this capability, each unique logical host must have its oservlet context or set of servlet contexts. A servlet context can not be shared across virhosts.

    3.6 Reloading ConsiderationsMany servlet containers support servlet reloading for ease of development. Reloading oservlet classes has been accomplished by previous generations of servlet containers bycreating a new class loader to load the servlet which is distinct from class loaders usedload other servlets or the classes that they use in the servlet context. This can have theundesirable side effect of causing object references within a servlet context to point at adifferent class or object than expected which can cause unexpected behavior.

    Therefore, when a Container Provider implements a class reloading scheme for ease odevelopment, they must ensure that all servlets, and classes that they may use, are loathe scope of a single class loader guaranteeing that the application will behave as expeby the Developer.

    1. The JavaServer Pages specification can be found athttp://java.sun.com/products/jsp

    Chapter 3 Servlet Context 30

  • PROPOSED FINAL DRAFT

    al

    e

    3.7 Temporary Working DirectoriesIt is often useful for Application Developers to have a temporary working area on the locfilesystem. All servlet containers must provide a private temporary directory per servletcontext and make it available via the context attribute ofjavax.servlet.context.tempdir . The object associated with the attribute must bof type java.io.File .

    31 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    rs

    uest.

    n

    estover

    the

    CHAPTER 4

    The Request

    The request object encapsulates all information from the client request. In the HTTPprotocol, this information is transmitted from the client to the server by the HTTP headeand the message body of the request.

    4.1 ParametersRequest parameters are strings sent by the client to a servlet container as part of a reqWhen the request is aHttpServletRequest , the attributes are populated from the URIquery string and possibly posted form data. The parameters are stored by the servletcontainer as a set of name-value pairs. Multiple parameter values can exist for any giveparameter name. The following methods of theServletRequest interface are availableto access parameters:

    • getParameter

    • getParameterNames

    • getParameterValues

    The getParameterValues method returns an array ofString objects containing allthe parameter values associated with a parameter name. The value returned from thegetParameter method must always equal the first value in the array ofString objectsreturned bygetParameterValues .

    All form data from both the query string and the post body are aggregated into the requparameter set. The order of this aggregation is that query string data takes precedencepost body parameter data. For example, if a request is made with a query string ofa=helloand a post body ofa=goodbye&a=world , the resulting parameter set would be ordereda=(hello, goodbye, world) .

    Posted form data is only read from the input stream of the request and used to populateparameter set when all of the following conditions are met:

    The Request 32

  • PROPOSED FINAL DRAFT

    toy a

    d

    the

    ls

    1. The request is an HTTP or HTTPS request.

    2. The HTTP method is POST

    3. The content type isapplication/x-www-form-urlencoded

    4. The servlet calls any of thegetParameter family of methods on the request object.

    If any of thegetParameter family of methods is not called, or not all of the aboveconditions are met, the post data must remain available for the servlet to read via therequest’s input stream.

    4.2 AttributesAttributes are objects associated with a request. Attributes may be set by the containerexpress information that otherwise could not be expressed via the API, or may be set bservlet to communicate information to another servlet (viaRequestDispatcher ).Attributes are accessed with the following methods of theServletRequest interface:

    • getAttribute

    • getAttributeNames

    • setAttribute

    Only one attribute value may be associated with an attribute name.

    Attribute names beginning with the prefixes of “java.” and “javax. ” are reserved fordefinition by this specification. Similarly attribute names beginning with the prefixes of“sun.” , and “com.sun. ” are reserved for definition by Sun Microsystems. It is suggestethat all attributes placed into the attribute set be named in accordance with the reversepackage name convention suggested by the Java Programming Language Specification1 forpackage naming.

    4.3 HeadersA servlet can access the headers of an HTTP request through the following methods ofHttpServletRequest interface:

    • getHeader

    • getHeaders

    1. The Java Programming Language Specification is available at http://java.sun.com/docs/books/j

    33 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    tanta the

    r’s

    ed

    let

    RI

    • getHeaderNames

    The getHeader method allows access to the value of a header given the name of theheader. Multiple headers, such as theCache-Control header, can be present in an HTTPrequest. If there are multiple headers with the same name in a request, thegetHeadermethod returns the first header contained in the request. ThegetHeaders method allowaccess to all the header values associated with a particular header name returning anEnumeration of String objects.

    Headers may contain data that is better expressed as anint or a Date object. Thefollowing convenience methods of theHttpServletRequest interface provide access toheader data in a one of these formats:

    • getIntHeader

    • getDateHeader

    If the getIntHeader method cannot translate the header value to anint , aNumberFormatException is thrown. If thegetDateHeader method cannottranslate the header to aDate object, anIllegalArgumentException is thrown.

    4.4 Request Path ElementsThe request path that leads to a servlet servicing a request is composed of many imporsections. The following elements are obtained from the request URI path and exposed virequest object:

    • Context Path: The path prefix associated with theServletContext that this servletis a part of. If this context is the “default” context rooted at the base of the web serveURL namespace, this path will be an empty string. Otherwise, this path starts with a’/’character but does not end with a’/’ character.

    • Servlet Path: The path section that directly corresponds to the mapping which activatthis request. This path starts with a’/’ character.

    • PathInfo: The part of the request path that is not part of the Context Path or the ServPath.

    The following methods exist in theHttpServletRequest interface to access thisinformation:

    • getContextPath

    • getServletPath

    • getPathInfo

    It is important to note that, except for URL encoding differences between the request Uand the path parts, the following equation is always true:requestURI = contextPath + servletPath + pathInfo

    Chapter 4 The Request 34

  • PROPOSED FINAL DRAFT

    ods

    To give a few examples to clarify the above points, consider the following:

    The following behavior is observed:

    4.5 Path Translation MethodsThere are two convenience methods in theHttpServletRequest interface which allowthe Developer to obtain the file system path equivalent to a particular path. These methare:

    • getRealPath

    • getPathTranslated

    Table 1: Example Context Set Up

    ContextPath /catalog

    Servlet Mapping Pattern: /lawn/*Servlet: LawnServlet

    Servlet Mapping Pattern: /garden/*Servlet: GardenServlet

    Servlet Mapping Pattern: *.jspServlet: JSPServlet

    Table 2: Observed Path Element Behavior

    Request Path Path Elements

    /catalog/lawn/index.html ContextPath: /catalogServletPath: /lawnPathInfo: /index.html

    /catalog/garden/implements/ ContextPath: /catalogServletPath: /gardenPathInfo: /implements/

    /catalog/help/feedback.jsp ContextPath: /catalogServletPath: /help/feedback.jspPathInfo: null

    35 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    ods,not

    ent to

    okiere not

    ion

    t

    let

    The getRealPath method takes aString argument and returns aStringrepresentation of a file on the local file system to which that path corresponds. ThegetPathTranslated method computes the real path of thepathInfo of this request.

    In situations where the servlet container cannot determine a valid file path for these methsuch as when the web application is executed from an archive, on a remote file systemaccessible locally, or in a database, these methods must return null.

    4.6 CookiesThe HttpServletRequest interface provides thegetCookies method to obtain anarray of cookies that are present in the request. These cookies are data sent from the clithe server on every request that the client makes. Typically, the only information that theclient sends back as part of a cookie is the cookie name and the cookie value. Other coattributes that can be set when the cookie is sent to the browser, such as comments, atypically returned.

    4.7 SSL AttributesIf a request has been transmitted over a secure protocol, such as HTTPS, this informatmust be exposed via theisSecure method of theServletRequest interface. The webcontainer must expose the following attributes to the servlet programmer

    • the cipher suite

    • the bit size of the algothm

    as java objects of typeString andInteger respectively. The names of the attributes musbe javax.servlet.request.cipher-suite andjavax.servet.request.key-size .

    If there is an SSL certificate associated with the request, it must be exposed by the servcontainer to the servlet programmer as an array of objects of typejava.security.cert.X509Certificate and accessible via aServletRequest attribute ofjavax.servlet.request.X509Certificate .

    Chapter 4 The Request 36

  • PROPOSED FINAL DRAFT

    nt

    the

    es alatform

    odling

    nt

    4.8 InternationalizationClients may optionally indicate to a web server what language they would prefer theresponse be given in. This information can be communicated from the client using theAccept-Language header along with other mechanisms described in the HTTP/1.1specification. The following methods are provided in theServletRequest interface todetermine the preferred locale of the sender:

    • getLocale

    • getLocales

    The getLocale method will return the preferred locale that the client will accept contein. See section 14.4 of RFC 2616 (HTTP/1.1) for more information about how theAccept-Language header must interpreted to determine the preferred language of the client.

    The getLocales method will return anEnumeration of Locale objects indicating,in decreasing order starting with the preferred locale, the locales that are acceptable toclient.

    If no preferred locale is specified by the client, the locale returned by thegetLocalemethod must be the default locale for the servlet container and thegetLocales methodmust contain an enumeration of a single Locale element of the default locale.

    4.9 Request data encodingCurrently, many browsers do not send a char encoding qualifier with the Content-Typeheader. This leaves open the determination of the character encoding for reading Httprequests. Many containers default in this case to the JVM default encoding, which causbreakage when the request data has not been encoded with the same encoding as the pdefault.

    To aid this situation, a new methodsetCharacterEncoding(String enc) has beenadded to the ServletRequest interface. Developers can override the character encodingsupplied by the container in this situation if necessary by calling this method. This methmust be called prior to parsing any post data or reading any input from the request. Calthis method once data has been read will not affect the encoding.

    The default encoding of a request is “ISO-8859-1” if none has been specified by the clierequest.

    37 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    lient.y

    lt,

    bezeer

    CHAPTER 5

    The Response

    The response object encapsulates all information to be returned from the server to the cIn the HTTP protocol, this information is transmitted from the server to the client either bHTTP headers or the message body of the request.

    5.1 BufferingIn order to improve efficiency, a servlet container is allowed, but not required to by defauto buffer output going to the client. The following methods are provided via theServletResponse interface to allow a servlet access to, and the setting of, bufferinginformation:

    • getBufferSize

    • setBufferSize

    • isCommitted

    • reset• flushBuffer

    These methods are provided on theServletResponse interface to allow bufferingoperations to be performed whether the servlet is using aServletOutputStream or aWriter .

    The getBufferSize method returns the size of the underlying buffer being used. If nobuffering is being used for this response, this method must return theint value of0(zero) .

    The servlet can request a preferred buffer size for the response by using thesetBufferSize method. The actual buffer assigned to this request is not required tothe same size as requested by the servlet, but must be at least as large as the buffer sirequested. This allows the container to reuse a set of fixed size buffers, providing a larg

    The Response 38

  • PROPOSED FINAL DRAFT

    itten

    otto the

    ted

    e

    eror the

    Ifnew

    buffer than requested if appropriate. This method must be called before any content is wrusing aServletOutputStream or Writer . If any content has been written, thismethod must throw anIllegalStateException .

    The isCommitted method returns a boolean value indicating whether or not any bytesfrom the response have yet been returned to the client. TheflushBuffer method forcesany content in the buffer to be written to the client.

    The reset method clears any data that exists in the buffer as long as the response is nconsidered to be committed. All headers and the status code set by the servlet previousreset called must be cleared as well.

    If the response is committed and thereset method is called, anIllegalStateException must be thrown. In this case, the response and its associabuffer will be unchanged.

    When buffering is in use is filled, the container must immediatly flush the contents of thebuffer to the client. If this is the first time for this request that data is sent to the client, thresponse is considered to be committed at this point.

    5.2 HeadersA servlet can set headers of an HTTP response via the following methods of theHttpServletResponse interface:

    • setHeader

    • addHeader

    The setHeader method sets a header with a given name and value. If a previous headexists, it is replaced by the new header. In the case where a set of header values exist fgiven name, all values are cleared and replaced with the new value.

    The addHeader method adds a header value to the set of headers with a given name.there are no headers already associated with the given name, this method will create aset.

    Headers may contain data that is better expressed as anint or a Date object. Thefollowing convenience methods of theHttpServletResponse interface allow a servletto set a header using the correct formatting for the appropriate data type:

    • setIntHeader

    • setDateHeader

    • addIntHeader

    • addDateHeader

    39 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    eby

    thervlet.

    ecter

    t be

    the

    ehods

    onsedata

    tion

    In order to be successfully transmitted back to the client, headers must be set before thresponse is committed. Any headers set after the response is committed will be ignoredthe servlet container.

    Servlet programmers are resoponsible for ensuring that the Content-Type header isappropriately set on the response object for the content the servlet is generating. SinceHttp 1.1 specification does not require that this header be set on an HTTP response, secontainers must not set a default content type if the servlet programmer has not set one

    5.3 Convenience MethodsThe following convenience methods exist in theHttpServletResponse interface:

    • sendRedirect

    • sendError

    The sendRedirect method will set the appropriate headers and content body to redirthe client to a different URL. It is legal to call this method with a relative URL path, howevthe underlying container must translate the relative path to a fully qualified URL fortransmission back to the client. If a partial URL is given and, for whatever reason, cannoconverted into a valid URL, then this method must throw anIllegalArgumentException .

    The sendError method will set the appropriate headers and content body to return toclient. An optionalString argument can be provided to thesendError method whichcan be used in the content body of the error.

    These methods will have the side effect of committing the response, if it had not alreadybeen committed, and terminating it. No further output to the client should be made by thservlet after these methods are called. If data is written to the response after these metare called, the data is ignored.

    If data has been written to the response buffer, but not returned to the client (i.e. the respis not committed), the data in the response buffer must be cleared and replaced with theset by these methods. If the response is committed, these methods must throw anIllegalStateException .

    TBD Make it clearer that these mechanisms should not destroy existing header informalike Cookies

    Chapter 5 The Response 40

  • PROPOSED FINAL DRAFT

    rhapsonse

    a

    e the

    rvlet

    the

    5.4 InternationalizationIn response to a request by a client to obtain a document of a particular language, or pedue to preference setting by a client, a servlet can set the language attributes of a respback to a client. This information is communicated via theContent-Language headeralong with other mechanisms described in the HTTP/1.1 specification. The language ofresponse can be set with thesetLocale method of theServletResponse interface.This method must correctly set the appropriate HTTP headers to accurately communicatLocale to the client.

    For maximum benefit, thesetLocale method should be called by the Developer beforethe getWriter method of theServletResponse interface is called. This will ensurethat the returnedPrintWriter is configured appropriately for the targetLocale .

    If the setContentType method is called after thesetLocale method and there is acharset component to the given content type, thecharset specified in the content typeoverrides the value set via the call tosetLocale .

    The default encoding of a response is “ISO-8859-1” if none has been specified by the seprogrammer.

    5.5 Closure of Response ObjectA number of events can indicate that the servlet has provided all of the content to satisfyrequest and that the response object can be considered to be closed. The events are:

    • The termination of the service method of the servlet.

    • When the amount of content specified in thesetContentLength method of theresponse has been written to the response.

    • The sendError method is called.

    • The sendRedirect method is called.

    When a response is closed, all content in the response buffer, if any remains, must beimmediately flushed to the client.

    41 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    thetsbbe

    e

    t ordoquestweb

    s

    ions

    CHAPTER 6

    Filtering

    Filters are a new feature in the Java servlet API for version 2.3. This chapter describesnew API classes and methods that provide a lightweight framework for filtering of Servleand static content in the API. It describes the ways that filters can be configured in a weapplication, and describes some of the conventions and semantics around how they canimplemented.

    Filters allow on the fly transformations of the payload and header information both of threquest in to a resource and on the response from a resource.

    API documentation for this model is provided in the API definitions chapters of thisdocument. Configuration syntax for filters is given by the Document Type Definition inChapter 13. Both should be referenced when reading this chapter.

    6.1 What is a filter?A filter is a reusable piece of code that transforms either the content of an HTTP requesresponse and can also modify header information. Filters differ from Servlets in that theynot themselves usually create a response, rather, they are there to modify or adapt the refor a resource and modify or adapt the response from a request for a resource within theapplication.

    The main functionality areas that are available to the Filter author are

    • They can intercept the invocation of a servlet or static resource before the resource iinvoked.

    • They can look at the request for a resource before it is invoked.

    • They can modify the request headers and request data by providing customized versof the request object that wrap the real request.

    • They can modify the response headers and response data by providing customizedversions of the response object that wrap the real response.

    Filtering 42

  • PROPOSED FINAL DRAFT

    in a

    e in

    tent

    be.by

    of

    the

    • They can intercept the invocation of a resource after the it is called.

    • They can be configured to act on a Servlet, on groups of Servlets or static content

    • Servlets or static content can be configured to be filtered by zero, one or more filtersspecifiable order.

    6.1.1 Examples of Filtering Components• Authentication Filters

    • Logging and Auditing Filters

    • Image conversion Filters

    • Data compression Filters

    • Encryption Filters

    • Tokenizing Filters

    • Filters that trigger resource access events

    • XSL/T filters that transform XML content

    • Mime-type chain Filters

    6.2 Main ConceptsThe main concepts in this filtering model are described in this section.

    The application developer creates a filter by implementing the javax.servlet.Filter interfacthe Java Servlet API and must provide a public constructor taking no arguments. Theimplementation class is packaged in the Web Archive along with the rest of the static conand Servlets that make up the web application. Each Filter is declared using the syntax in the deployment descriptor. A Filter or collection of Filters can be configured toinvoked by defining a number of elements in the deployment descriptorThe syntax associates the filter or group of filters with a particular Servlet. This is donemapping a filter to a particular servlet by the servlet’s logical name, or mapping to a groupServlets and static content resources by mapping a filter to a url pattern.

    6.2.1 Filter Lifecycle

    After the time when the web application containing filters is deployed, and before anincoming request for a resource in the web application causes a the container to accessresource and serve it back, the container must look through the list of filter mappings to

    43 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    edthat

    ndr.

    list

    rfilter

    of

    d)

    t

    locate the list of filters that must be applied to the resource. How this list is built is describbelow. The container must ensure at some point in this time that, for each filter instanceis to be applied, it has instantiated a filter of the appropriate class, and calledsetFilterConfig(FilterConfig config) on each filter instance in the list. Thecontainer must ensure that only one instance of a filter per declaration in thedeployment descriptor is instantiated per Java Virtual Machine of the container. Thecontainer also ensures that thejavax.servlet.FilterConfig instance that is passedin to this call has been initialized with the filter name as declared in the deploymentdescriptor for that filter, with the reference to the ServletContext for this web application awith the set of initialization parameters declared for the filter in the deployment descripto

    When the container receives the incoming request, it takes the first filter instance in theand calls itsdoFilter() method, passing in theServletRequest andServletResponse , and a reference to theFilterChain object it will use.

    The doFilter() method of a Filter will typically be implemented following this or somesubset of this pattern

    1) It will examine the request headers

    2) It may wrap the request object passed into itsdoFilter() method with a customizedimplementation of ServletRequest or HttpServletRequest if it wishes to modify requestheaders or data.

    3) It may wrap the response object passed in to itsdoFilter() method with a customizedimplementation of ServletRequest or HttpServletRequest if it wishes to modify responseheaders or data.

    4) It can make an invocation of the next entity in the filter chain. If this filter is the last filtein the chain that ends with the target servlet or static resource, the next entity is the nextthat was configured in the deployment descriptor, if it is not, it is the resource at the endthe chain. It does this by calling thedoFilter() method on the chain object (passing inthe request and response it was called with, or the wrapped versions it may have create

    Alternatively, it can choose to block the request by not making the call to invoke the nexentity. In the latter case, the filter is responsible for filling out the response.

    5) It may examine response headers after it has invoked the next filter in the chain.

    6) Alternatively, the Filter may throw an exception to indicate an error in processing.

    Before the container can remove filter instances at the end of the lifetime of a webapplication, it must call thesetFilterConfig() method on the Filter passing in null toindicate that the Filter is being taken out of service.

    Chapter 6 Filtering 44

  • PROPOSED FINAL DRAFT

    entto the

    t,

    filter-thee>

    rn>

    6.2.2 Filter environment

    A set of initialization parameters can be associated with a filter using the init-params elemin the deployment descriptor. The names and values of these parameters are availableFilter at runtime via thegetInitParameter andgetInitParameterNamesmethods on the filter’sFilterConfig . Additionally, theFilterConfig affords accessto the ServletContext of the web application for the loading of resources, for loggingfunctionality or for storage of state in theServletContext’s attribute list.

    6.2.3 Configuration of Filters in a Web Application

    A Filter is defined in the deployment descriptor using the element. In this elementhe programmer declares the

    filter-name - this is used to map the filter to a servlet or URL

    filter-class - this is used by the container to identify the filter type

    init-params - the initialization parameters for a filter

    and optionally can specify icons, a textual description and a display name for toolmanipulation.

    Once a Filter has been declared in the deployment descriptor, the assembler uses the <mapping> element to define to which Servlets and static resources in the web applicationFilter is to be applied. Filters can be associated with a Servlet by using the

  • PROPOSED FINAL DRAFT

    the

    tles

    nts

    nts

    /*

    In this case, the Logging Filter is applied to all the Servlets and static content pages inweb application, because every request URI matches the ‘/*’ URL pattern.

    When processing a filter-mapping element using the url-pattern style, the container musdetermine whether the URL pattern matches the request URI using the path mapping rudefined in 12.1.

    The order in which the container builds the chain of filters to be applied for a particularrequest URI is

    1) The URL pattern matching filter-mappings in the same as the order that those elemeappear in the deployment descriptor, and then

    2) The servlet-name matching filter-mappings in the same as the order that those elemeappear in the deployment descriptor

    Chapter 6 Filtering 46

  • PROPOSED FINAL DRAFT

    47 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    tiventver

    er in

    sionthe

    me of

    CHAPTER 7

    Sessions

    The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. To build effecweb applications, it is imperative that a series of different requests from a particular cliecan be associated with each other. Many strategies for session tracking have evolved otime, but all are difficult or troublesome for the programmer to use directly.

    This specification defines a simpleHttpSession interface that allows a servlet containerto use any number of approaches to track a user’s session without involving the Developthe nuances of any one approach.

    7.1 Session Tracking MechanismsThere are several strategies to implement session tracking.

    7.1.1 URL Rewriting

    URL rewriting is the lowest common denominator of session tracking. In cases where aclient will not accept a cookie, URL rewriting may be used by the server to establish sestracking. URL rewriting involves adding data to the URL path that can be interpreted bycontainer on the next request to associate the request with a session.

    The session id must be encoded as a path parameter in the resulting URL string. The nathe parameter must bejsessionid . Here is an example of a URL containing encodedpath information:

    http://www.myserver.com/catalog/index.html;jsessionid=1234

    Sessions 48

  • PROPOSED FINAL DRAFT

    nd islient.

    g

    as a

    ata to

    gent

    until

    the

    o

    7.1.2 Cookies

    Session tracking through HTTP cookies is the most used session tracking mechanism arequired to be supported by all servlet containers. The container sends a cookie to the cThe client will then return the cookie on each subsequent request to the serverunambiguously associating the request with a session. The name of the session trackincookie must beJSESSIONID.

    7.1.3 SSL Sessions

    Secure Sockets Layer, the encryption technology which is used in the HTTPS protocol, hmechanism built into it allowing multiple requests from a client to be unambiguouslyidentified as being part of an accepted session. A servlet container can easily use this dserve as the mechanism for defining a session.

    7.1.4 Session Integrity

    Web containers must be able to support the integrity of the HTTP session when servicinHTTP requests from clients that do not support the use of cookies. To fulfil this requiremin this scenario, web containers commonly support the URL rewriting mechanism.

    7.2 Creating a SessionBecause HTTP is a request-response based protocol, a session is considered to be newa client “joins” it. A client joins a session when session tracking information has beensuccessfully returned to the server indicating that a session has been established. Untilclient joins a session, it cannot be assumed that the next request from the client will berecognized as part of the session.

    The session is considered to be “new” if either of the following is true:

    • The client does not yet know about the session

    • The client chooses not to join a session. This implies that the servlet container has nmechanism by which to associate a request with a previous request.

    49 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000

  • PROPOSED FINAL DRAFT

    as

    ject,

    sion.

    is no

    A Servlet Developer must design their application to handle a situation where a client hnot, can not, or will not join a session.

    7.3 Session ScopeHttpSession objects must be scoped at the application / servlet context level. Theunderlying mechanism, such as the cookie used to establish the session, can be sharedbetween contexts, but the object exposed, and more importantly the attributes in that obmust not be shared between contexts.

    7.4 Binding Attributes into a SessionA servlet can bind an object attribute into anHttpSession implementation by name. Anyobject bound into a session is available to any other servlet that belongs to the sameServletContext and that handles a request identified as being a part of the samesession.

    Some objects may require notification when they are placed into, or removed from, a sesThis information can be obtained by having the object implement theHttpSessionBindingListener interface. This interface defines the followingmethods that will signal an object being bound into, or being unbound from, a session.

    • valueBound• valueUnbound

    The valueBound method must be called before the object is made available via thegetAttribute method of theHttpSession interface. ThevalueUnbound methodmust be called after the object is no longer available via thegetAttribute method of theHttpSession interface.

    7.5 Session TimeoutsIn the HTTP protocol, there is no explicit termination signal when a client is no longeractive. This means that the only mechanism that can be used to indicate when a clientlonger active is a timeout period.

    Chapter 7 Sessions 50

  • PROPOSED FINAL DRAFT

    sion isservlet

    objectces

    ionable

    ch as

    The default timeout period for sessions is defined by the ser