Table of contents
Who Should Read THIS Specification 8
API REFERENCE 8
Other JavaTM Platform Specifications 8
Other important references 8
Providing Feedback 9
Acknowledgements 9
OVERVIEW 11
What is a servlet? 11
What is a servlet container? 11
AN EXAMPLE 11
Comparing servlets with other technology Technologies 12
RELATIONSHIP TO JAVA 2 Platform Enterprise Edition 12
Distributable Servlet Containers 12
Changes Since Version 2.1 12
TERMS USED 15
Basic Terms 15
Roles 16
Security Terms 17
The servlet interface 19
Request Handling Methods 19
Number of instances 20
Servlet Life CYCLE 20
Servlet CONTEXT 23
Scope of a servletContext 23
Initialization Parameters 23
Context Attributes 23
Resources 24
Multiple Hosts and Servlet Contexts 24
Reloading considances 24
Temporary Working Directories 25
The Request 27
Parameters 27
Attributes 27
HEADERS 28
Request path Elements 28
Path Translation Methods 29
Cookies 29
SSL Attributes 30
INTERNATIONALIZATION 30
The Response 31
BUFFERING 31
HEADERS 31
Convenience Methods 32
INTERNATIONALIZATION 32
Closure of Response Object 33
Sessions 35
Session Tracking Mechanisms 35
CREANG A SESSION 35
Session Scope 36
Binding Attributes Into a session 36
Session Timeouts 36
Last Accessed Times 36
Important Session Semantics 37
Dispatch Requests 39
Obtaining a requestdispatcher 39
USING A Request Dispatcher 40
INCLUDE 40
Forward 40
Error Handling 41
Web Applications 43
Relationship to servletContext 43
Elements of A Web Application 43
Distinction Between Repesentations 43
Directory Structure 43
Web Application Archive File 44
Web Application Configuration Descriptor 44
Replacing a Web Application 45
Error Handling 45
Web Application Environment 45Mapping Requests to Servlets 47
Use of url paths 47
Specification of mappings 47
SECURITY 49
Introduction 49
Declarative Security 49
Programmatic security 49
Roles 50
Authentication 50
Server TRACKING OF Authentication Information 52
Specifying Security Constraints 52
Application Programming Interface 53
Package Javax.Servlet 53
Package javax.servlet.http 57
Deployment Descriptor 63
Deployment Descriptor Elements 63
DTD 63
Examples 73
FUTURES 77
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
JavaTM Servlet Specification Version 2.2 11
1 Overview
1.1 What is a servlet?
A servlet is a web component, management by a contact, That generates Dynamic Content. Servlets Are
Small, Platform Independent Java Classes Compiled To An Architecture Neutral Bytecode That Can Be
Loaded Dynamically Into and Run By A Web Server. Servlets Interact with Web Clients Via a Request
Response Paradigm Implement by The Servlet Container. This Request-Response Model Is Based ON
The Behavior of the Hypertext Transfer Protocol (HTTP).
1.2 What is a servlet container?
The Servlet Container, in Conjunction With A Web Server or Application Server, Provides The Network
Services Over Which Requests and Responses Are Set, Decodes Mime Based Requests, and Formats
Mime Based Responses. A servlet Container Also Contains and Manages Servlets Through Their
Lifecycle.
A servlet container can Either Be Built Into A Host Web Server or Installed As an Add-on Component To
A Web Server Via That Server's Native Extension API. Servlet Containers Can Also Be Built INTO OR
Possibly Installed Into Web-enabled Application Servers.
All Servlet ContaCol for Requests and Responses, But May Alsosupport Addition REQUEST / RESPONSE BASED Protocols Such as https (http over ssl).
Minimum Required Version of The Http Specification That A Container Must IMPLEMENT IS HTTP / 1.0.
IT Is Strongly Suggested That Containers Implement The Http / 1.1 Specification As Well.
A Servlet Container May Place Security Restrictions on The Environment That A Servlet Executes in.
A Java 2 Platform Standard Edition 1.2 (J2SE) or Java 2 Platform Enterprise Edition 1.2 (J2EE)
Environment, THESE RESTRICTION SHOULD BE Placed Using The Permission Architecture Defined by Java 2
Platform. For example, high end application servers may limited ceertpaper action, such as the creeion of
A Thread Object, To Insure That Other Components of the Container Are Not Negative Impacted.
1.3 an esample
A Client Program, Such As A Web Browser, Accesses A Web Server and Makes An Http Request. This
Request is processed by the Web Server and is handed off to the servlet container. The servlet
Container Determines Which Servlet To Invoke Based On Its Internal Configuration and Calls It with
Objects representing the request and response. The servlet container can run in The Same Process As
The Host Web Server, in A Different Process on The Same Host, or on a Different 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 FORM Parameters
May Have Been Sent As Part of this Request, AND Other Relevant Data. The servlet can life perform
WhatVer Logic It Was ProGrammed with and can generation data to send back to 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 Response Is Properly
Flushed and returns control back to the host web server.
Overview
JavaTM Servlet Specification Version 2.2 12
1.4 Comparing Servlets with Other Technologies
In FunctionAlity, Servlets Lie Somewhere Between Common Gateway Interface (CGI) Programs and
ProPrietary Server Extensions Such As The Netscape Server API (NSAPI) OR Apache Modules.
Servlets Have The Following Advantages over Other Server Extension Mechanisms:
• They is generally much faster Than CGI Scripts Because A Different Process Model Is Used.
• They use a standard api this is supported by Many Web Servers.
• The Jave All The Advantages of The Java Programming Language, Including Ease of Development
And Platform Independence.
• They CAN Access The Large Set of Apis Available for the Java Platform.
1.5 Relationship to Java 2 Platform Enterprise Edition
The Servlet API Is A Required API of The Java 2 Platform Enterprise Edition, V1.21. The J2EE
Specification Describes Additional Requirements for Servlet Containers, And Servlets That Are Deployed
INTO THEM, THAT ARE EXECUTING IN A J2EE ENVIRONMENT.
1.6 Distributable Servlet Containers
New in this version of the specification is The Ability to Mark A Web Application As Distributable.
This Indication Allows Servlet Container Vendors To Deploy The Servlets in A Web Application Across
Multiple Java Virtual Machines Running on The Same Host OR on Different Hosts. An Application
Marked As Distributable Must Obey A Few Restrictions So That Containers That Support Distributable
Applications CAN IMPLEMENT FEATURES Such As Clustering and Failover.
All Web Applications That May NEED TO Run in a High Performance Environment, One That Allows for
SCALABILITY, SUCH AS A Compliant J2ee Implement, Should Be Written As
Distributable Web Applications. This Will Allow Applications To Take Maximum Advantage of Servers
That Provide THESE FEATURES. IF A NON Distributable Application IS Deployed Into Such a Server, Then IT
Cannot Take Full Advantage Of The Features That Are Given by Such Servers.
1.7 Changes SINCE VERSION 2.1
The Following Major Changes Have Been Made To The Specification Since Version 2.1:
• The Introduction of The Web Application Concept
• The Introduction of The Web Application Archive Files
• The Introduction of Response Buffering
• The Introduction of Distributable Servlets
• The Ability to Get a RequestDispatcher by Name
• The Ability To Get a RequestDispather Using A Relative Path
• Internationalization IMPROVEMENTS
• Many Clarification of Distributed Servlet Engine Semantics
The Following Changes Have Been Made To The API:
• Added the getServletName Method to the servletconfig interface to allow a servlet to
Obtain the name by Which it is knower to the system, if any.
1. Please see the Java 2 Platform Enterprise Edition Specification Available At
http://java.sun.com/j2ee/
Overview
JavaTM Servlet Specification Version 2.2 13
• Added the getInitParameter and getinitparameternames Method to the
ServletContext Interface So That Initialization Parameters Can Be Set At The Application Level
To be shared by all servlets That Are Part of this application.
• Added The getLocale Method to the servletRequest Interface to Aid in Determining What
Locale the client is in.
• Added The issecure method to the servletRequest Interface to Indicate WHether OR Notthe Request Was Transmitted Via A Secure Transport Such as https.
• Replaced The Construction Methods of UnavailableException As EXIXG CONSTRUCTOR
Signatures Caused Some Amount of Developer Confusion. these constructors have been replaced
Item.
• Added the getHeaders method to the httpservletRequest Interface to allow all the
Headers associated with a particular name to be retrieved from the request.
• Added the getcontextpath method to the httpservletRequest Interface So That the
Part of the request path associated with a web application can be objectined.
• Added the isuserinrole and getuserPrinciPle methods to the
HttpServletRequest Method to Allow Servlets To Use An Abstract Role Based Authentication.
• Added the addheader, addintheader, and adddateheader methods to the
HttpservletResponse Interface To ALLOW MULTIPLE Headers To Be created with the same
Header Name.
• Added The GetAttribute, GetAttribute, And
REMOVEATTRIBUTE METHODS to the httpsession interface to improve the name
Conventions of the API. The GetValue, GetValueenames, SetValue, And RemoveValue
Methods Are Deprecated as part of this change.
In Adduion, a large number of clarifications have name to spec.
Overview
JavaTM Servlet Specification Version 2.2 14
TERMS USED
JavaTM Servlet Specification Version 2.2 15
2 Terms Used
THESE TERMS Are Widely Used Throughout The Rest of this Specification.
2.1 Basic Terms
2.1.1 Uniform Resource Locators
A Uniform Resource Locators (URL) Is A Compact String Repectation Of Resources Available VIA
THE NETWORK. ONCE The Resource Represented by a URL HAS BEEN Accessed, Various Operations May Beperformed On That Resource.1 Urls Are A Form of a Uniform Resource Identifier (URI). Urls Are
Typically of the form:
For the purposes of this specification, we are primarily interested in http based urls which area
Of the form:
Http [s]: //
For example:
http://java.sun.com/products/serve/index.html
Https://javashop.sun.com/purchase
In http based urls, the '/' character is reserved for use to separate a hierarchical path structure
In The Url-path portion of the url. The Server is responsible for determining the meaning of the
Hierarchical structure. There is no Correspondence BetWeen a URL-Path and a Given File System Path.
2.1.2 Servlet Definition
A servlet definition is a unique name associated with a full qualified class name of a class
Implementing the servlet interface. a set of initialization parameters can be be associated with a
Servlet Definition.
2.1.3 servlet mapping
A servlet mapping is a servlet definition That Is Associated by a servlet Container with a URL PATH
Pattern. All Requests to That Path Pattern Are Handled by The Servlet Associated with The Servlet
DEFINITION.
2.1.4 Web Application
A Web Application IS A Collection of Servlets, JavaServer Pages2, HTML Documents, And Other Web
Resources Which Might Include Image Files, Compressed Archives, And Other Data. A Web Application
May Be packaged into an archive or exist in an open directory structure.
All Compatible Servlet Containers Must Accept A Web Application and Perform A Deployment of ITS
Contents Into Their Runtime. this May Mean That A Container Can Run The Application Directly from A1. See RFC 1738
2. See the JavaServer Pages Specification At
http://java.sun.com/products/jsp
TERMS USED
JavaTM Servlet Specification Version 2.2 16
Web Application Archive File or It MAY Mean That It Will Move THE Contents of A Web Application Into
The appropriate Locations for That Particular Container.
2.1.5 Web Application Archive
A Web Application Archive Is A Single File Which Contains All of The Components of A Web
Application. This Archive File is created by using standard jar Tools Which allow any or all of the
Web components to be signed.
Web Application Archive Files Are Identified by The .war Extension. A New Extension IS Used Instead
Of .jar Because That Extension Is Reserved for Files Which Contain A Set of Class Files and That Can Be
Placed in The ClassPath or Double Clicked Using A Gui To Launch An Application. As The Contents of A
Web Application Archive Are, A New Extension WAS in Order, WATAS IN ORDER.
2.2 Roles
The Following Roles Are Defined to Aid in Identifying The Actions And Responsibilities Taken By
Various Parties During The Development, Deployment, And Running of a servlet based application. in
Some Scenarios, A Single Party May Perform Several Roles; in Others, Each Role May Be Performed by
A Different Party.
2.2.1 Application Developer
The Application Developer Is The Producer of A Web Based Application. His Or Her Output Is A Set of
Servlet Classes, JSP Pages, HTML Pages, And Supporting Libraries and Files (SUCH As Images,
Compressed Archive Files, ETC.) for the Web Application. The Application Developer IS Typically An
Application Domain Expert. The developer is required to be aware of the servlet environment and itsconsequences when programming, incruding concurrency considances, and create the web
Application accountingly.
2.2.2 Application Assembler
The application assembler Takes The application done by the developer and ensures That IT IS A Deployable
Unit. The INPUT OF THE Application Assembler Is The Servlet Classes, JSP Pages, HTML Pages, And
Other Supporting Libraries and Files for the Web Application. The Output of the Application Assembler
IS A Web Application Archive OR A Web Application IN AN Open Directory Structure.
2.2.3 deployer
The Deployer Takes One or More Web Application Archive Files Or Other Directory Structures Provided
.
The Operational Environment Includes a Specific Servlet Container and Web Server. The Deployer
Must Resolve All the External Dependencies Decilad by The Developer. To Perform His Role, THE
Deployer Uses Tools Provided by the servlet container.
The Deployer IS An Expert in A Specific Operational Environment. For Example, The Deployer IS
Responsible for mapping the security roles defined by the application developer to the user groups
And Accounts That Exist in The Operational Environment Where The Web Application IS Deployed.
2.2.4 SYSTEM Administrator
The System Administrator Is Responsible for the Configuration and Administration of the Servlet
Container and Web Server. The Administrator is Also responsible for overseeing the Well-being of there
Deployed Web Applications At Run Time.
TERMS USED
JavaTM Servlet Specification Version 2.2 17
THIS SPECICITION DOES NOT Define The Contracts for System Management and Administration. Tools Runtime Monitoring and Management Tools Provided by the Container
Provider and Server Vendors to Accomplish these Tasks.
2.2.5 Servlet Container Provider
The Servlet Container Provider Is Responsible for Providing The Runtime Environment, Namely The
Servlet Container and Possibly The Web Server, in Which A Web Application Runs As Well as The Tools
Necessary to Deploy Web Applications.
The Expertise of The Container Provider is in http level programming. Since this Specification
Does Not Specify The Interface Between The Web Server and The Servlet Container, It Is Left to The THE
Container Provider to Split The Implementation of The Required FunctionAlity Between The Container
And The Server.
2.3 Security Terms
2.3.1 Principal
A Principal is an entity That Can Be Authenticated by an Authentication Protocol. A Principal IS
Identified by a principal name and authenticated by using authentication data. The content and
Format of the principal name and the authentication data depend on the Authentication Protocol.
2.3.2 Security Policy Domain
A Security Policy Domain Is a Scope Over Which Security Policies Are Defined and Enforced By A
Security Administrator of The Security Service. A Security Policy Domain Is Also Sometimes Referred
TO as a realm.
2.3.3 Security TECHNOLOGY DOMAIN
A Security Technology Domain Is The Scope Over Which The Same Security Mechanism, Such AS
Kerberos, IS Used to Enforce A Security Policy. Multiple Security Policy Domains Can EXIST WITHIN A
Single Technology Domain.
2.3.4 Role
A role is an abstract notion used by a development by thedeployer to a user, or group of users, in a security policy domain.
TERMS USED
JavaTM Servlet Specification Version 2.2 18
JavaTM Servlet Specification Version 2.2 19
3 The servlet interface
The Servlet Interface Is The Central Abstract Of The Servlet API. All servlets IMPLEMENT THIS
Interface Either Directly, or More Commonly, by Extending a class what implements the interface. The
Two classes in the API That Implement The Servlet Interface Are GenericServlet and
Httpservlet. For MOST PURPOSES, Developers Will Typically Extend Httpservlet To
Implement their servlets.
3.1 Request Handling Methods
The Basic Servlet Interface Defines a Service Method for Handling Client Requests. This
Method Is Called for Each Request That The Servlet Container Routes To an Instance of a Servlet.
Multiple Request Threads May Be Executing Within The Service Method at Any Time.
3.1.1 Http Specific Request HandlingMeets
The Httpservlet Abstract Subclass Adds Additional Methods Which Are Automatically Called By
The service method in the httpservlet class to aid in processing http based requests.
THESE METHES 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
Typically When Developing Http Based Servlets, a Servlet Developer Will Only Concern Himself
With the doget and dopost methods. The rest of these methods are considered to be advanced
Methods for use by programs Very Familiar with http programming.The doput and dodelete methods allow servlet development to support http / 1.1 clients which
Support these features. The Dohead Method in httpservlet is a specialized method this will
Execute the doget method, but only return the headers produced by the doget method to the THE
Client. The dooptions method Automatically determines Which http methods are Directly
Supported by the servlet and return. The information to the client. The dotrace maethod causes a
Response with a message containing all of the headers Sent in The TRACE REQUEST.
In Containers That Only Support HTTP / 1.0, ONLY THE Doget, Dohead and Dopost Methods Will B
Used as http / 1.0 does not define the put, delete, options, or trace methods.
3.1.2 Conditional Get Support
The httpservlet interface defines the getlastmodified method to support conditional get
Operations. a Conditional Get Operation Is One In Which THE Client Requests a Resource with the
HTTP GET Method and Adds A Header That Indicates That The Content Body Should Only Be Sent IT IT
HAS BEEN Modified Since A Specified Time.
Servlets That Implement The Doget Method and That Provide Content That Does Not Necessarily
Change from Request to Request SHOULD IMPLEMENT THITHOD TO AID IN Efficient Utilization Of
NetWork resources.
The servlet interface
JavaTM Servlet Specification Version 2.2 20
3.2 Number Of Instances
BY DEFAULT, There Must Be Only One Instance of a Servlet Class Per servlet Definition In A Container.
In The Case of a Servlet That Implements The SingleThreadmodel Interface, The Servlet Container
May Instantiate Multiple Instances of That Servlet SO That It Can Handle A Heavy Request Load While
STILL Serializing Requests to a Single Instance.in The Case Where a Servlet Was Deployed As Part of An Application That Marked In The Deployment
Descriptor As Distributable, There IS One Instance of a Servlet Class Per Servlet Definition Per VM IN A
Container. if the servlet imports the singlethreadmodel interface as well as part of a
Distributable Web Application, The Container May Instantiate Multiple Instances of That Servlet in
Each VM of the Container.
3.2.1 Note About SingleThreadModel
The Use of the SingleThreadmodel Interface Guarantees That One Thread At a Time Will Execute
THROUGH a Given Servlet Instance's Service Method. It is important to note that this Guarantee ONLY
Applies to servlet instance. Objects That Can Be Accessible to more Than Ooney Servlet Instance At A
Time, Such As Instances of Httpsession, May Be Available To Multiple Servlets, Including Those
That Implement SingleThreadModel, At Any Particular Time.
3.3 Servlet Life Cycle
A servlet is managed through a well defined life cycle tria defines how it is loaded, instantiated and the iNStantiated and
Initialized, Handles Requests from Clom Clom Clom Clom Clients, And How It Is Taken Out of Service. This Life Cycle IS
Expressed in the api by the init, service, and destroy methods of there
Javax.Servlet.Servlet Interface That All Servlets Must, Directly or Indirectly Through The
GenericServlet or httpservlet Abstract Classes, IMPLEMENT.
3.3.1 Loading and Instantiation
The Servlet Container Is Responsible for Loading and Instantiating a servlet. The instantiation and
Loading can occur when engine is started or it can be de delayed unsteil the container determines 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, The ServletContainer Loads a servlets Using Normal Java Class Loading facilities from a local file system, a remote
File System, Or Other Network Services.
After the Container Has Loaded The Servlet Class, IT Instantiates An Object Instance of That Class for
USE.
IT Is Important to Note That There Can Be More Than One Instance of a Given Servlet Class in There
Servlet Container. for Example, this Can Occur Where There Was More Than One Servlet Definition That
Utilized a specific servlet class with diffreent initialization parameters. this can also occur WHEN A
Servlet Implements The SingleThreadModel Interface and The Container Creates a pool of
Servlet Instances to Use.
3.3.2 Initialization
After the servletiated, The Container Must Initialize The Servlet Before IT
CAN Handle Requests from Clients. Initialization IS Provided So That a servlet can read Any Persistent
Configuration Data, Initialize Costly Resources (SUCH AS JDBCTM Based Connection), And Perform Any
Other One-Time Activities. The Container Initializes The Servlet by Calling The Init Method of To
Servlet Interface with a unique (Per servlet definition) Object Implementing The
The servlet interface
JavaTM Servlet Specification Version 2.2 21
ServletConfig Interface. This Configuration Object Allows The Servlet To Access Name-Value
Initialization Parameters from The Servlet Container's Configuration Information. The Configuration
Object Also Gives The Servlet Access To An Object IMPLEMENTING THE ServletContext Interface
Which Describes The Runtime Environment That The Servlet Is Running Withnin. See Section 4 Titled
"Servlet context" on page 23 for more information about the servletcontext interface.3.3.2.1 error conditions on Initialization
During Initialization, The Servlet Instance Can Signal That It Is Not To Be Placed Into Active Service By
Throwing an unavailableException or servletException. if a servlet instance throws
An Exception of this Type, IT Must Not Be Placed Into Active Service and The Instance Must Be
Immediately release by the servlet container. The destroy method is not called in this case
Initialization Was Not Considered to Be Successful.
After the instance of the failed servlet is released, a new instance may be instantiated and initialize
By The Container at Any Time. The Only Exception To this rule is if the unavailableException
Thrown by the failed servlet Which indeicates the minimum time of unavailability. in this case, the
Container Must Wait for the minimum Time of Unavailability to Pass Before CREANG AND INITIALIZING A
New servlet instance.
3.3.2.2 Tool considances
WHEN a Tool Loads and Introspects a Web Application, IT May May Load and Introspect Member Classes of
The Web Application. This Will Trigger Static Initialization Methods To Be Executed. Because of this
Behavior, A Developer Should Not Assume That a servlet is in an Active Container Runtime UnsS
Init Method of the Servlet Interface IS Called. for Example, this Means That a servlet shop NOT
Try to Establish Connections to Databases or Enterprise JavaBeansTM CompeNent Architecture
Containers When ITS Static (Class) Initialization Methods Are Invoked.
3.3.3 Request Handling
After the servlet is properly initialized, The servlet container may use it to handle requests. EACH
Request is represented by a request Object of Type ServletRequest and the servlet create aresponse to the request by useing the provided object of type servletResponse. Thase Objects
Are Passed as parameters to the service method of the servlet interface. in the case of an
HTTP Request, The Container Must Provide The Request and Response Objects as Implementations of RESPONS OF
HTTPSERVLETREQUEST AND HTTPSERVLETRESPONSE.
IT Is Important To Note That A Servlet Instance May Be CREATED AND Placed INTO Service By a servlet
Container But May Handle No Requests During ITS Lifetime.
3.3.3.1 Multithreading Issues
During The Course of Servicing Requests from Clom Clom Clom Clom Clients, a Servlet Container May Send Multiple Requests
From Multiple Clients Through The Service Method of The Servlet At Any One Time. This Means That
The Developer Must Take Care to make Sure That The Servlet Is Properly Programmed for Concurrency.
IF a developer Wants to Prevent this Default Behavior, He CAN Program The Servlet To Implement To
SingleThreadModel Interface. Implementing this Interface Will Guarantee That Only ONE
Request Thread at a Time Will Be Allowed in The Service Method. a servlet Container May Satisfy this
Guarantee by Serializing Requests on a servlet or by maintaining a pool of servlet instances. if The
Servlet Is Part of An Application That Has Been Marked As Distributable, The Container May Maintain A
Pool of Servlet Instances in Each VM That The Application IS Distributed Across.
IF a developer defines a Service Method (or Methods Such As Doget or Dopost Which Are
Dispatch to from the service method of the httpservlet abstract class) with the
The servlet interface
JavaTM Servlet Specification Version 2.2 22
Synchronized keyword, the servlet container will
Servlets That Implement The SingleThreadModel. It is strongly recommented That Developers
NOT SYNCHRONIZE The Service Method or any of the httpservlet service method Methods Such as doget,
Dopost, ETC.
3.3.3.2 Exceptions During Request Handling
A servlet may throw Either a servletexception or an unavailableException during
The service of a request. a servletexception signals That Some Error Occurred During the
Processing of the request and that the Container SHOULD Take Appropriate MeasureS to Clean Up
Request. An UnavailableException Signals That The Servlet IS Unable to Handle Requests Either
Temporarily or permanently.
IF a permanent unavailability is indeicated by the unavailableException, The servlet
Container Must Remove The Servlet from Service, Call ITS Destroy Method, And Release The Servlet
INSTANCE.
IF Temporary Unavailability Is Indicated by The UnavailableException, THEN THE CONTAINER
May Choose to Not Route Any Requests Through The Servlet During The Time Period of The Temporary
Unavailability. Any Requests Refused by The Container During this Period Must Be Returned with a
Service_unavailable (503) Response Status Along with a retry -After header indeficating
When the unavailability will terminate. The Container May Choose To ignore the distinction betWeen
a Permanent and Temporary Unavailability and Treat All UnavailableExceptions AS
Permanent, Thereby Removing a Servlet That Throws Any UnavailableException from Service.
3.3.3.3 Thread Safety
A Developer Should Note That Implementations of The Request and Response Objects Are Notguaranteed To Be Thread Safe. This Means That The the Request
Handling thread. References to the request and response Objects Should Not Be Given To Objects
Executing in Other Threads as The Behavior May Be Nondeterministic.
3.3.4 End of Service
The Servlet Container IS Not Required To Keep A Servlet Loaded for Any Period of Time. A servlet
Instance May Be Kept Active In a servlet Container for a period of only milliseconds, for the lifetime
Of The Servlet Container (Which Could Be Measured in Days, Months, Or Years), or Any Amount of Time
IN BETWEEN.
When the servlet container determines That a servlet shouth be removed from service (for example,
When a Container Wants to Conserve Memory Resources, or When ItSelf Is Being Shut Down, IT Must
Allow the servlet to release and save any penness state. to do this the
Servlet Container Calls The Destroy Method of The Servlet Interface.
Before The Servlet Container Can Call The Destroy Method, IT Must Allow Any Threads That Are
Currently Running In The Service Method of the Servlet To Either Complete, or Exceed a Server
Defined Time Limit, Before The Container CAN Proceed with calling the destroy method.
Once The Destroy Method Is Called On A Servlet Instance, The Container May Not Route Any More
Requests to That Particular Instance of the servlet. if the container Needs to enable the servlet again, IT
Must do so with a new instance of the servlet's class.
After the destroy method completries, The Servlet Container Must Release The Servlet Instance So
That it is eligible for Garbage Collection
Servlet ContextjavaTM Servlet Specification Version 2.2 23
4 servlet context
The ServletContext Defines a servlet's view of the Web Application forin Which the servlet is
Running. The servletContext Also Allows a servlet to access resources available to it. using
Such An Object, a servlet can log events, Obtain Url References To Resources, and Set and Store
Attributes That Other Servlets in The Context Can Use. The Container Provider is Responsible for
Providing An Implementation of The ServletContext Interface In The Servlet Container.
A servletcontext is rooted at a specific Path With Wtem. For Example a Context Could
BE located at
http://www.mycorp.com/catalog. All Requests That Start with the /
Catalog Request Path, Which Is Known As The Context Path, Will BE ROUTED THIS Servlet Context.
Only One Instance of a ServletContext May Be Available To The Servlets in A Web Application.
In Cases Where The Web Application INDICES THAT IT IS Distributable, There Must Only Be One Instance
Of The ServletContext Object in Use Per Application Per Java Virtual Machine.
4.1 Scope of a servletContext
There is one instance of the servletcontext interface associated with eachweb copLication
Deployed Into a Container. In Cases Where The Container IS Distributed over Many Virtual 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 Are Implicitly
Part of a "default" Web Application And Are Contained by a Default ServletContext. in A
Distributed Container, The Default ServletContext Is Non-Distributable and Must Only Exist On
One VM.
4.2 Initialization Parameters
A Set of Context Initialization Parameters Can Be Associated with a Web Application and Are Madeavailable By The Following Methods of The ServletContext Interface:
• GetInitParameter
• GetInitParameterNames
Initialization Parameters Can Be Used by An Application Developer to Convey Setup Information, Such
AS A Webmaster's E-mail address or the name of a system what holds critical data.
4.3 Context Attributes
A servlet can bind an Object Attribute INTO The Context by Name. Any Object Bound Into a Context IS
Available To Any Other Servlet That Is Part of The Same Web Application. The Following Methods of
ServletContext Interface Allow Access To this functionality:
• SetAttribute
• GetAttribute
• GetAttributeNames
• RemoveAttribute
Servlet Context
JavaTM Servlet Specification Version 2.2 24
4.3.1 Context Attributes in a Distributed Container
Context attributes exist locally to the vm in which they were create and placed. This prevents the
ServletContext from Being Used As a Distributed Shared Memory Store. IF Information Needs To
Be Shared Between Servlets Running In A Distributed Environment, That Information Should Be Placed
INTO A Session (See Section 7 Titled "Sessions" on page 35), a database or set in an Enterprise
Javabean.
4.4 Resources
The ServletContext Interface Allows Direct Access To The Static Document Hierarchy of Content
Documents, Such As HTML, GIF, AND JPEG Files, That Are Part of the Web Application Via THE
FOLLOWING METHODS of The ServletContext Interface:
• GetResource
• GetResourceAsStream
Both the getResource and getresourceASstream Methods Take A String Argument
Giving the path of the resource relative to the root of the context.
IT Is Important to Note That Sests from Whatver Repositorythe Server Uses. This Hierarchy of Documents May Exist In A File System, in A Web Application Archive
File, ON A Remote Server, OR Some Other Location. These Methods Are Not Used To Obtain Dynamic
Content. for Example, In a Container Supporting The JavaServer Pages Specification1, A Method Call
Of the form getresource ("/ index.jsp") Would Return The JSP Source Code and Not The
Processed Output. See Section 8 Titled "Dispatch Requests" on page 39 for more information
About Accessing Dynamic Content.
4.5 Multiple Hosts and Servlet Contexts
Many Web Servers Support The Ability for Multiple Logical Hosts To Share The Same IP Address ON A
Server. This Capability Is Sometimes Referred To As "Virtual Hosting". if a servlet container's host web
Server Has this Capability, Each Unique Logical Host Must Have ITS OWN Servlet Context Or Set of Servlet
Contexts. a servlet context can not be shared across virtual hosts.
4.6 Reloading Considances
Many Servlet Containers Support Servlet Reloading for Ease Of Offment. Reloading of Servlet
Classes Has Been AccompLished by Previous Generations of Servlet Containers by Creating A New Class
Loader to load the servlet which is distinct from class loaders used to load other servlets or the
Classes That The Use in The servlet context. this can have the undesirable side effect of causing
Object References for Point At a Different Class or Object Than Expected Which
Can Cause Unexpected Behavior.
Therefore, WHEN A Container, WHEN A CLAS RELOADER IMPLEMENTS A Class Reloading Scheme for Ease of
Developments, And Classes That the the application will loaded in it, limited
Developer.
1. The JavaServer Pages Specification Can Be Found AT
http://java.sun.com/products/jsp
Servlet Context
JavaTM Servlet Specification Version 2.2 25
4.7 Temporary Working Directories
IT is offen useful for application development exvelure to have a Temporary Working Area on The Local
FileSystem. All servlet Containers Must Provide a Private Temporary Directory Per Servlet Context and
Make It Available Via The Context Attribute of Javax.Servlet.Context.tempdir. The
Object associated with the attribute must be of type java.io.file.
Servlet Context
JavaTM Servlet Specification Version 2.2 26
The Request
JavaTM Servlet Specification Version 2.2 27
5 The Request
The Request Object Encapsulates All Information from The Client Request. In The Http Protocol, this
Information is transmitted from the client to the server by the client to the server by the http headers and the message body body
Of The Request.
5.1 Parameters
Request Parameters Are Strings Sent by The Client To a Servlet Container AS Part of a Request .when
The Request Is A HttpservletRequest, The Attributes Are Populated from The Uri Query String
And Possibly Posted form data. The parameters area stored by the servlet container as a set of namevalue
Pairs. Multiple Parameter Values Can EXIST for Any Given Parameter Name. The Following
Methods of The ServletRequest Interface Are Available To Access Parameters:
• GetParameter
• getParameterNames
• GetParameterValues
The getParametervalues method returns an array of string Objects containing all the
Passensita
GetParameterValues.
All Form Data from Both the query string and the post body area aggregated Into The Request
Parameter set. The Order of this aggregation is this query string data takes precedence over post
Body Parameter Data. for Example, IF a Request Is Made with a query string of a = hello and a post
Body of a = goodbye & a = world, the resulting parameter set would Be Ordered A = (Hello,
Goodbye, world).
Posted form data is only read from the input stream of the required and use to populate the request and use
Parameter set when All of the Following Conditions Are Met:
1. The Request is an HTTP or HTTPS REQUEST.
2. The http method is posket
3. The Content Type is Application / X-WWW-FORM-URLENCODED
4. The servlet calls any of the getParameter Family of Methods on The Request Object.
IF any of the getparameter Family of Methods Is Not Called, or Not All of the Above Conditions
Are Met, The Post Data Must Remain Available for the Servlet To Read Via The Request's Input Stream.
5.2 Attributes
Attributes Are Objects Associated with a request. Attributes may be set by the Container to Express
Information That Otherwise Could Not Be Expressed Via the Api, or May Be set by a servlet to
Communicate Information To Another Servlet (Via RequestDispatcher). Attributes Are Accessed
With The Following Methods of The ServletRequest Interface:
• GetAttribute
• GetAttributeNames
• SetAttribute
The Request
JavaTM Servlet Specification Version 2.2 28
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 suggested that all
Attributes Placed Into The Attribute Set Be named in Accordance with The Reverse Package Name
Convention suggested by the Java Programming Language Specification1 for package naming.
5.3 HEADERS
A servlet can access the headers of an http request through the folload methods of the
HTTPSERVLETREQUEST Interface:
• GetHeader
• GetHeaders
• GetHeadernames
The getHeader method allows access to the value of a header given the name of the header.
Multiple Headers, Such as The Cache-Control Header, Can Be Present in an Http Request. IF
There Are Multiple Headers with The Same Name in A Request, The GetHead Method Returns
First Header Contained In The Request. The GetHeaders Method ALLOW Access To All The Header
VALUES Associated with a particular header name return an enumeration of string Objects.
Headers May Contain Data That Is Better Expressed As An Int OR a Date Object. The Following
Convenience methods of the httpservletRequest Interface Provide Access to Header Data in A
One of these Formats:
• GetInTheader
• GetDateHeader
If The getIntheader method cannot translate the header value to an int, a
Numberformatexception is thrown. If the getdateheader method it
Header to a date Object, An IllegaLargumentException is thrown.
5.4 Request Path Elements
The Request Path That Leads to a servlet servicing a request is composed of Many Important Sections.
The Following Elements Are Obtained from The Request Uri Path and Exposed Via The Request Object: • Context Path: The PREFIX Associated with The ServletContext That Servlet Is A Part
OF. IF this context is the "default" context rooted at the base of the web server's url 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 shich actid this
Request. this path starts with a '/' character.
• PathInfo: The Part of the Request path That IS Not Part of The Context path or the servlet path.
The Following Methods Exist in The HttpservletRequest Interface To Access this Information:
• GetContextPath
• GetServletPath
• GetPathInfo
IT Is Important to Note That, Except for Url Encoding Differences Between The Request Uri and The
Path Parts, The Following Equation IS Always True:
1. The Java Programming Language Specification Is Available At
Http://java.sun.com/docs/books/jls
The Request
JavaTM Servlet Specification Version 2.2 29
Requesturi = ContextPath ServletPath PathInfo
To Give a Few Examples To Clarify The Above Points, Consider The Following:
The Following Behavior Is Observed:
5.5 Path Translation Methods
There Are Two Convenience Methods in The HttpservletRequest Interface Which Allow THE
Developer to Obtain The File System Path Equivalent To a Particular Path. There Methods Are:
• GetRealPath
• getPathTranslated
The GetRealPath Method Takes A String Argument And Returns A String Repesentation of A
File on the local file system to which That path Corresponds. The getpathtranslated method
Computes the real path of the pathinfo of this request.in Situations Where The Servlet ContaNot Determine a Valid File Path For Ssese Methods, Such
As WHEN THE Web Application IS Executed from an Archive, ON A Remote File System Not Accessible
Locally, or in A Database, Theese Methods Must Return NULL.
5.6 cookies
The httpservletRequest Interface Provides The getCookies method to Obtain an Array of
Cookies That Are Present in The Request. these cookies are Data Sent from the client to the server on
Every Request That The Client Makes. Typically, The Only Information That The Client Sends Back As Part
Table 1: Example Context Set Up
ContextPath / Catalog
Servlet Mapping Pattern: / Lawn
Servlet: LawnServlet
Servlet Mapping Pattern: / Garden
Servlet: GardenServlet
Servlet mapping pattern: * .jsp
Servlet: jspservlet
Table 2: Observed Path Element Behavior
Request Path Path Elements
/catalog/lawn/index.html contextpath: / catalog
ServletPath: / Lawn
PathInfo: /index.html
/ Catalog / Garden / Implements / ContextPath: / Catalog
ServletPath: / Garden
PathInfo: / imports /
/catalog/help/feedback.jsp ContextPath: / catalog
ServletPath: /help/feedback.jsp/feedback.jsp
PathInfo: NULL
The Request
JavaTM Servlet Specification Version 2.2 30
Of a cookie is the cookie name and the cookie value. Other cookie attributes That Can Be set by
The cookie is Sent To The Browser, Such as Comments, Are Not Typically Returned.
5.7 SSL Attributes
IF a Request Has Been Transmitted Over A Secure Protocol, Such As Https, this Information Must B
Exposed Via The ISsecure Method of The ServletRequest Interface.
In servlet containers That Are Running in A Java 2 Standard Edition, V 1.2 or Java 2 Enterprise
Edition, V 1.2 Environment, if there is an ssl certificate associated with the request, it must beexposed to the servlet program of type @
Java.security.cert.x509certificate and accessible Via a servletRequest
Attribute of javax.servlet.Request.x509certificate.
For a servlet container That IS Not Running In a java2 standard Edition 1.2 Environment, Vendors
May Provide Vendor Specific Request Attributes To Access Ssl Certificate Information.
5.8 INTERNATIONALIZATION
Clients May Optionally Indicate TO A Web Server What Language They Woulder The Response BE
Given information can becomunicated from the client sale the accept-language
Header Along With Other Mechanisms Described in The HTTP / 1.1 Specification. The Following
Methods Are Provided In The ServletRequest Interface To Determine The Preferred Locale of Tore
Sender:
• GetLocale
• GetLocales
The GetLocale Method Will Return The Preferred Locale That The Client Will Accept Content in. See
Section 14.4 of RFC 2616 (http / 1.1) for more information about how the accept-language
Header Must Interpreted to Determine The Preferred Language of The Client.
The Getlocales Method Will Return An Enumeration of Locale Objects INDICATION, IN
Decreasing Order Starting With The Preferred Locale, The Locales That Are Acceptable To The Client.
IF no preferred local, the location of the client, the locale returned by the getlocale method
Must Be The Default Locale for the servlet container and the getlocales method Must Contain AN
ENUMERATION OF A SINGLE LOCALE Element of The Default Locale.
The Response
JavaTM Servlet Specification Version 2.2 31
6 THE RESPONSE
THE RESE INFORMATION TO BE RETURNED from The Server To The Client. In Thehttp Protocol, This Information is Transmitted from The Server To The Client Either by http headers
Or the message body of the request.
6.1 Buffering
In Order to Improve Efficiency, a servlet container is allowed, but not required to by Default, TO
Buffer Output Going to The Client. The Following Methods Are Provided Via THE
ServletResponse Interface To Allow a servlet access to, and the setting of, buffering
Information:
• GetBuffersize
• SetBuffersize
• iScommitted
• Reset
• Flushbuffer
THESE Methods Are Provided On The ServletResponse Interface To Allow Buffering Operations To
Be Performed WHETHER The servlet is using a servletOutputStream or a writer.
The getBuffersize method returns the size of the underlying buffer being used. If no buffering
Is Being Used for this Response, This Method Must Return The int value of 0 (ZERO).
The Servlet Can Request a Preferred Buffer Size for the Response by Using The SetBuffersize
Method. The Actual Buffer Assigned to this request is not required to be the same size as request
By The Servlet, But Must Be at Least As Large As The Buffer Size Requested. This Allows the Container To
Reuse a set of fixed size buffers, providing a larger buffer Than Requested if appropriate. this method
Must be caled before any content is written using a servletoutputstream or write. if Any
Content Has Been Written, this Method Must Throw An IllegalStateException.
THE ISCOMMITTED METHOD RETURns A Boolean Value Indicating WHETER OR NOT Any Bytes from T
Response have yet been returned to the client. The flushbuffer method forces any 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 NOT
Considered to be committed. All Headers and the status code set by the servlet previous to the reset
Called Must Be Clead As Well.
If The Response Is Committed and The Reset Method Is Called, An IllegalStateException
Must Be Thrown. in this case, the response and it unechanged.
When Buffering Is in Uses Filled, The Container Must Immediatly Flush The Contents of The Buffer To
The client. If this is the first time for this request this data is send to the client, the response is
Considered to be committed at this point.
6.2 HEADERS
A servlet can set headers of an http response via the folload methods of the
HTTPSERVLETRESPONSE INTERFACE:
• SetHeader
The Response
JavaTM Servlet Specification Version 2.2 32
• AddHeader
The setheader method sets a header with a given name and value. If a prepvious header exists, IT
Is Replaced by The New Header. in The Case Where A Set of Header Values EXIST for the GIVEN 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. If there is
No Headers Already Associated with The Given Name, This Method Will Create a New Set.
Headers May Contain Data That Is Better Expressed As An Int OR a Date Object. The Following
Convenience methods of the httpservletresponse interface allow a servlet to set a header
Using the Correct Formatting for the appropriate data type:
• SetInTheader
• SetDateHeader
• AddintHeader
• AddDateHeader
In Order To Be Successful Transmitted Back to The Client, Headers Must Be Set Before The Response IS
Committed. Any Headers Set after the response is committed will be ignored by the servlet
Container.
6.3 Convenience Methods
The Following Convenience Methods Exist in The HttpServletResponse Interface:
• SendRedirect
• Senderror
The sendredirect method will set the appropriate headers and content body to redirect the
CLIENT TO A DIFFERENT URL. It is legal to call this method with a relative url path, howeever the
Underlying Container Must Translate The Relative Path To a Fully Qualified Url for Transmission Back
To The Client. If a Partial Url Is Given and, for Whatever Reason, Cannot Be Converted Into a Valid
URL, THIS Method Must Throw An IllegaAlargumentException.
The senderror method will set the appropriate headers and content body to return to the client.
An Optional String Argument Can Be PROVIDED TO The Senderror Method Which Can Be Used in
The Content Body of The Error.
The Side Effect of Committing The Response, IF IT HAD NOT Already Been
Committed, and Terminating it. no further output to the client shouth be worth by the servletAfter
THESE METHODS Are Called. if Data IS Written to The Response After these Methods Are Called, The Data IS
Ignored.
If Data Has Been Written to The Response Buffer, But Not Returned to The Client (I. The Response IS Not
Committed, The Data In The Response Buffer Must Be Cleared and Replaced with The Data Set by There
Methods. if the response is committed, Theese Methods Must throw AN
IllegalStateException.
6.4 INTERNATIONALIZATION
In response to a request by aclient to obtain a document of a particular language, or perhaps Due To
Preference setting by aclient, a servlet can set the language attributes of a response back to a client.this information is commit
Mechanisms Described in The HTTP / 1.1 Specification. The Language of a Response Can Be Set with
The setLocale Method of the ServletResponse Interface. This Method Must Correctly Set
The appropriate Http Headers to Accurately Communicate The Locale To The Client.
The Response
JavaTM Servlet Specification Version 2.2 33
For maximum benefit, the setlocale method before the set of the development before the
GetWriter Method of the ServletResponse Interface IS Called. this will ensure That
Returned PrintWriter IS Configured Appropriately for the Target Locale.
If The setContentType Method Is Called After The SetLocale Method and There IS A
Charset Component to the Given Content Type, The Charset Specified in The Content Type
Overrides the value set via the call to setlocale.
6.5 Closure of Response Object
A Number of Events Can Indicate That The Servlet Has Provided All of the Content To Satisfy The Request
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 The SetContentLength Method of The Response 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 Be Immediately
Flushed to the client.
The Response
JavaTM Servlet Specification Version 2.2 34
Sessions
JavaTM Servlet Specification Version 2.2 35
7 sessions
The Hypertext Transfer Protocol (http) is by Design A stateless protocol. To build effective webapplications, IT IS Imperest That A Series Of Different Requests from a Particular Client Can Be
Associated with each other. Many Strategies for Session TRACKING HAVOLVED OVER TIME, But All Are
Difficult or troublesome for the programmer to use directly.
THIS SPECification Defines A Simple HttpSession Interface That Allows a servlet Container TO USE
Any Number of Approaches To Track A User's Session WITHOUT INVOLVING THE Web
Of any one approach.
7.1 Session Tracking Mechanisms
7.1.1 URL REWRITING
URL REWRITING IS The Lowest Common Denominator of Session Tracking. In Cases Where a Client Will
NOT ACCEPT A cookie, URL REWRITING May BE Used by the Server to Establish Session Tracking. URL
ReWriting Involves Adding Data To The Url Path That Can Be Interpreted by the Container on The next
Request to Associate The Request with a session.
THE NAME OF THE NAME OF THE NAME OF THE
Parameter Must Be jsessionId. Here is an example of a url containing encoded path
Information:
http://www.myserver.com/catalog/index.html;jsessionID=1234
7.1.2 Cookies
SESSION TRACKING THROUGH HTTP COOKIES Is The Most Used Session Tracking Mechanism and IS
Required to be supported by all servlet containers. The Container Sends a cookie to the client. The
Client Will Then Return The cookie on each subsequent request to the server unambiguously @ Client WIEN SUBSEQUESLY
Associating The Request with a session. The name of the session tracking cookie must be
JSessionId.
7.1.3 SSL sessions
Secure Sockets Layer, The Encryption Technology Which is buy in The Https Protocol, HAS A
Mechanism Built ITO ITOWING MULTIPLE Requests from aclient to be unambiguously identified asbeing part of an affilt session. a servlet container can Easily Use THIS DATA to Serve As the
Mechanism for defining a session.
7.2 Creating a session
Because http is a request-response based protocol, a session is considered to be new unsseion
"JOINS" it. A Client Joins a session When Sensions TRACKING INFORMATION HAS BEEN SUCCESSFULLY RETURNED
To The Server Indicating That A Session Has Been Established. Until The Client Joins A Session, IT Cannot
Be Assumed That The Next Request from the client will be recognized as part of the session.
The session is considered to be "new" if each following is true:
• The Client Does Not Yet Know About The Session
Sessions
JavaTM Servlet Specification Version 2.2 36
• The client chooses not to join a session. This Implies That The Servlet Container Has No Mechanism
By Which To Associate A Request with a prepvious request.
A servlet development to handle a situation where aclient has not, ca
Not, or Will Not Join A SESSION.
7.3 session scope
HttpSession Objects Must Be Scoped At the Application / Servlet Context Level. The Underlying
Mechanism, Such as the cookie buy to establish the session, Can Be Shared Between Contexts, But
The Object Exposed, And More Importantly The Attributes in That Object, Must Not Be Shared Between
CONTEXTS.
7.4 Binding Attributes Into a Session
A servlet can bind an Object Attribute INTO an HTTPSESSION IMPLEMENTATION BY Name. Any Object
Bound Into a sessions is available to any other servlet That Belongs to the Same ServletContext
And That Handles A Request Identified As Being a Part of The Same Session.SOME Objects May Require Notification WHEN THEY Are Placed Into, Or Removed from, A Session. THIS
Information can be obtained by haVing the object implementation the Object IMPLEMENT THE
HttpSessionBindingListener Interface. This interface defines the following methods That
Will Signal An Object Being Bound INTO, OR BEING UNBOUND, A session.
• ValueBound
• Valueunbound
The valuebound method must be called before the object is master available via the
GetaTtribute Method of the httpsession interface. The valueunbound method must be
Called after the Object is no longer available via the getattribute method of the
Httpsession interface.
7.5 Session Timeouts
In The Http Protocol, The Http Protocol, There IS No Explicit Termination Signal WHEN A Client Is No longer Active. This
Means That The Only Mechanism That Can Be Used To Indicate When a Client Is No Longer Active Is A
Timeout Period.
The default timeout period for sessions is defined by the servlet container and can be obtained via
The getMaxinactiveInterval method of the httpsession interface. This Timeout Can Be
Changed by the developer Using the setMaxinactiveInterval of the httpsession
Interface. The Timeout Periods Used by Thase Methods Is Defined in Seconds. if The Timeout Period
For a session is set to -1, the session will never expression.
7.6 Last Accessed Times
The getlastaccessedTime Method of the httpsession interface allows a servlet to
Determine the last time the session WAS Accessed Before The Current Request. The Session IS
Considered to Be Accessed WHEN A Request That Is Part of The Session Is Handled by The Servlet
CONTEXT.
Sessions
JavaTM Servlet Specification Version 2.2 37
7.7 Important Session Semantics7.7.1 Threading Issues
Multiple Servlets Executing Request Threads May Have Active Access To A Single Session Object At The
Same Time. The Developer Has The Responsibility To Synchronize Access To Resources Stored in Tha
Session as approprise.
7.7.2 Distributed Environments
Withn Application That Is Marked As Distributable, All Requests That Are Part of A Session Can ONLY
Be Handled ON A Single VM At Any One Time. in Addition All Objects Placed Into Instances of The
HttpSession Class Using The SetAttribute or Putvalue Methods Must Implement THE
Serializable Interface. The Servlet Container May Throw AN
IllegalarGumentexception if a non serializable object is placed Into the session.
THESE RESTRICTIONS Mean That The Developer Is Enssured That There No Additional Concurrency
Issues Beyond Those Encountered In A Non-Distributed Container. In Adduion, The Container Provider
Can Ensure Scalability by Having The Ability To Move A Session Object, And ITS Contents, from any
Active Node of The Distributed System To a Different Node of The System.
7.7.3 Client Semantics
Due to the fact this cookies or ssl certificates area type type controlled by the Web Browser Process
And Are Not Associated with Any Particular Window of A The Browser, Requests from All Windows of A
Client Application To a servlet Container Might Be Part of The Same Session. For maximum portability,
The Developer SHOULD Always Assume That All Windows of a Client Are Particles in The Same
SESSION.
Sessions
JavaTM Servlet Specification Version 2.2 38
Dispatch Requests
JavaTM Servlet Specification Version 2.2 39
8 Dispatch Requests
When Building a Web Application, IT IS OFTEN USEful To Forward Processing of a Request to AnotherServlet, or To include the output of another servlet in the response. The requestdispatcher
Interface Provides a Mechanism to Accomplish this.
8.1 Obtaining a RequestDispatcher
An Object Implementing The RequestDispather Interface May BE Obtained from THE
ServletContext Via the Following Methods:
• GetRequestDispatcher
• GetNamedDispatcher
The GetRequestDispatcher Method Takes A String Argument Describing a Path Wtem
Scope of the servletcontext. this path must be relative to the root of the
ServletContext. This path is buy to look up a servlet, WRAP IT WITH A
RequestDispatcher Object, And Return It. If no servlet can be resolved based on the given path,
A RequestDispatcher Is Provided That Simply Returns The Content for That Path.
The getnameddispatcher method it gets a string argument indecent the name of a servlet
KNown to the servletcontext. if a servlet is knower to the servletcontext by the given
Name, IT IS Wrapped with a requestdispatcher object and return. if no servlet is associated
With the given name, The Method Must Return NULL.
TO Allow RequestDispatcher Objects To Be Obtained Using Relative Paths, Paths Which Are Not
Relative to the root of the servletcontext but instead area relative to the path of the current
Request, The Following Method Is Provided in The ServletRequest Interface:
• GetRequestDispatcher
The Behavior of this Method Is Similar To The Method of The Same Name in The servletContext,
HOWEVER IT DOES NOT Require a Complete Path Withnin The Context To Be Given As Part of The Argument To
Operate. The servlet container can use the information in the request object to transform the party ibject to transform the givenrelative path to a completion path. for example, in a context rooted at '/', a request to
/ garden/tools.html, a Request Dispatcher Obtained VIA
ServletRequest.getRequestDispatcher ("Header.html") Will Behave EXACTLY LIKE
a call to servletContext.getRequestDispatcher ("/ garden / header.html").
8.1.1 Query Strings in Request Dispatcher Paths
In The ServletContext and ServletRequest Methods Which Allow The Creation of A
RequestDispatcher Using Path Information, Optional Query String Information May Be
Attached to the path. for esample, a developmentdispatcher by us
FOLLOWING CODE:
String path = "/raisons.jsp?orderno=5";
RequestDispatcher rd = context.getRequestDispatcher (path);
Rd.includ (Request, Response);
The Contents of the Query String Areaded To The Parameter Set That The include Servlet Has Access
To. The parameters are Ordered So That Any Parameters Specified in The Query String Used To Create
Dispatch Requests
JavaTM Servlet Specification Version 2.2 40
The RequestDispatcher Take Precedence. The Parameters Associated with a
RequestDispatcher is Only Scope for the duration of the include or forward call.
8.2 Using A Request Dispatcher
TO USE A Request Dispatcher, a developer Needs to call Either the include or forward method of
The RequestDispatcher Interface Using The Request and Response Arguments That WERE
Passed in via the service method of the servlet interface.
The Container Provider Must Ensure That The dispatch to a target servlets occurs in The Same Thread of
The Same Vm as The Original Request.
8.3 Include
THE INTERFACE MAY BE CALED AT Any Time. The THETARGET Servlet Has Access To All Aspects of The Request Object, But Can Only Write Information To The
ServletOutputStream or Writer of The Response Object As Well As the Ability To Commit A
Response by Either Writing Content Past the end of the response buffer or expedition calling the
Flush method of the servletresponse interface. The include servlet cannot set headers or in the INCLUDET CANNOT
.
8.3.1 Included Request Parameters
WHEN a servlet is being use from with11, it is soli TO, IT IS SOMES Necessary for That Servlet To
KNOW The path by Which it is invoked and not the original request paths. The folload request
Attributes Are Set:
Javax.Servlet.include.Request_uri
Javax.Servlet.include.Context_path
Javax.Servlet.include.Servlet_path
Javax.Servlet.include.path_info
Javax.servlet.include.query_string
THESE Attributes Are Accessible from the include servlet via the getttribute method on the getattribute method on
Request Object.
If The include servlet Was Obtained by Using A Nameddispatcher, The Attributes Are Not Set.
8.4 Forward
THE Forward Method of the RequestDispatcher Interface May Only Be Called by the Calling
Servletted to the client. if Output exists in the response buffer That HAS
NOT BEEN COMMITTED, IT MUST Be Reset (Clearing the Buffer) Before The Target Servlet's Service
Method Is Called. if The Response Has Been Committed, An IllegalStateException Must Be
Thrown.
THE PATH Elements of The Request Object Exposed to The Target Servlet Must Reflect The Path Used To
Obtaining to this is if the requireddispatcherwas Obtained via the getnameddispatcher method. in this case, the path elements of there
Request Object Reflect Those of the Original Request.
Before The Forward Method of The RequestDispatcher Interface Returns, The Response Must
Be committed and close by the servlet container.
Dispatch Requests
JavaTM Servlet Specification Version 2.2 41
8.5 ERROR HANDLING
Only Runtime Exceptions and Checked Exceptions of Type ServletException OR
IOEXCEPTION SHOULD Be propagated to the calling servlet if thrown by the target of a request
Dispatcher. All Other Exceptions Should Be Wrapped As a servletexception and the root cause
Original Exception.
Dispatch Requests
JavaTM Servlet Specification Version 2.2 42
Web Applications
JavaTM Servlet Specification Version 2.2 43
9 Web Applications
A Web Application IS A Collection of Servlets, HTML Pages, Classes, And Other Resources That Can Be
Bundled and Run ON Multiple Containers from Multiple Vendors. A Web Application IS Rooted AT A
Specific Path Withnin A Web Server. For Example, a catalog application could be located at http: //
Www.mycorp.com/catalog. All Requests That Start with this prefix will be routed to the
ServletContext Which Represents The catalog application.
A servlet Container Can Also Establish Rules for Automatic Generation of Web Applications. For
Example a ~ user / maping could be used to map to a web application based on / home / user /
Public_html /.
By Default An Instance of A Web Application Must Only Be Run ONE VM At Any One Time. This
Behavior Can Be Overridden if The Application Is Marked As "Distributable" Via Its The Deployment
Descriptor. When An Application IS Marked As Distributable, The Developer Must Obey A Morerestrics Set of Rules Than Is Expected of a Normal Web Application. Thase Specific Rules Are Called
Out throughout this specification.
9.1 Relationship to servletContext
The Servlet Container Must Enforce A One To One Correspondence Between A Web Application and A
ServletContext. A servletcontext Object Can Be Viewed AS A Servlet's View ONTO ITS
APPLICATION.
9.2 Elements of A Web Application
A Web Application May Consist of the Following Items:
• servlets
• JavaServer Pages1
• Utility Classes
• Static Documents (HTML, Images, Sounds, ETC.)
• Client Side Applets, Beans, And Classes
• Descriptive Meta Information Which Ties All of the Above Elements Together.
9.3 Distinction Between Repesentations
This Specification Defines a hierarchical structure Which can EXIST IN Open File System, AN Archive
File, or some other form for deployment purposes. it is recommented, but not required, That servlet
Containers Support this structure as a runtime representation.
9.4 Directory Structure
A Structured Hierarchy Of Directories. The root of this hierarchy serves as
A Document Root for Serving Files That Are Part of this Context. for example, for a web copLication
Located At / Catalog In A Web Server, The Index.html File Located At the Base of THE Web
Application hierarchy can be served to satisfy a request to /catalog/index.html.
1. See The JavaServer Pages Specification Available from
http://java.sun.com/products/jsp.
Web Applications
JavaTM Servlet Specification Version 2.2 44
A Special Directory Exists Withnin The Application Hierarchy Named "Web-inf". This Directory
Contains all things related to the app1 aren't in the document root of the application. It isimportant to note That the the application.
No file contained in the Web-INF Directory May Be Served Directly to a client.
The Contents of the Web-INF Directory Are:
• /Web-inf/web.xml Deployment Descriptor
• / Web-INF / CLASS / * DIRECTORY for Servlet and Utility Classes. The Classes in this Directory
Are used by the application class logader to load classes from.
• /Web-inf/lib/*.jar Area for Java Archive Files Which Contain Servlets, Beans, And Other
Utility Classes Useful to the Web Application. All Such Archive Files Are Used by the Web
Application Class Loader To Load Classes from.
9.4.1 Sample Web Application Directory Structure
Illustrate Here Is A Listing of All The Files in A Sample Web Application:
/index.html
/ HuWTO.JSP
/ Feedback.jsp
/IMages/banner.gif
/IMages/jumping.gif
/Web-inf/web.xml
/Web-inf/lib/jspbean.jar
/Web-inf/classes/com/mycorp/servlets/myservlet.class
/Web-inf/classes/com/mycorp/util/myutils.class
9.5 Web Application Archive File
Web Applications Can Be Packaged and Signed, Using The Standard Java Archive Tools, Into A Web
Archive format (war) File. For example, an application for issue tracking could be distributed in an
Archive with the filename Issuetrack.war.
When PackageDo Such A Form, A Meta-Inf Directory Will Be Present Which Contains
Information useful to the Java Archive Tools. if this Directory is present, The Servlet Container MUST
Not Allow It Be Served As Content To A Web Client's Request.
9.6 Web Application Configuration Descriptor
The Following Types of Configuration and Deployment Information Exist in The Web ApplicationDeployment Descriptor:
• ServletContext Init Parameters
• Session Configuration
• Servlet / JSP definitions
• Servlet / JSP Mappings
• MIME TYPE MAPPINGS
• Welcome File List
• Error Pages
• Security
All of these Types of Information Are Conveyed In The Deployment Descriptor (See Section 13 Titled
"Deployment Descriptor" on Page 63).
Web Applications
JavaTM Servlet Specification Version 2.2 45
9.7 Replacing a Web Application
Applications Evolve and Must Occasionally Be Replaced. In a long Running Server IT IDEAL TO BE
Able to Load a new Web Application and Shut Down The Old One Withnout Restarting The Container.
When An Application IS Replaced, a Container Should Provide a Robust Approach To Preserve Session
Data with.
9.8 ERROR HANDLING
A Web Application May Specify That When Errors Occur, Other Resources In The Application Area.
THESE Resources Are Specified in The Deployment Descriptor (See Section 13 Titled "Deployment
Descriptor "on page 63). If The location of the error handler is a servlet or a jsp, The Following
Request Attributes CAN Be Set:
• javax.servlet.rror.status_code
• javax.servlet.error.exception_type
• javax.servlet.error.Message
THESE Attributes Allow The Servlet To Generate Specialized Content Depending On The Status Code,
Exception Type and Message of The Error.
9.9 Web Application Environment
Java 2 Platform Enterprise Edition, V 1.2 Defines a Naming Environment That Allows Applications To
Easily Access Resources and External Information without the expend knowledge of how the external country
Information is named or organization.
AS Servlets Are An Integral Component Type Of J2EE, Provision Has Been Made In The Web ApplicationDeployment Descriptor for Specifying Information Allowing a Servlet To Obtain References To
Resources and Enterprise Beans. The Deployment Elements That Contain this Information Are:
• Env-entry
• EJB-REF
• Resource-Ref
The Env-Entry Element Contains Information To Set Up Basic Environment Entry Names Relative To
The Java: Comp / Env Context, The Expected Java Type of The Environment Entry Value (The Type of
Object Returned from the JNDI LOOKUP METHOD, And An Optional Environment Entry Value. The
EJB-Ref Element Contains The Information Needed to Allow a Servlet To Locate The Home Interfaces
OF A Enterprise Bean. The Resource-Ref Element Contains The Information NEEDED TO SET UP A
Resource faArtory.
The Requirements of The J2ee Environment with Regards To Setting Up The Environment Are Described
In Chapter 5 of the Java 2 Platform Enterprise Edition v 1.2 Specification1. servlet Containers That
Are Not Part of A J2EE Compliant Implementation Are Encouraged, But Not Required, To Implement THE
Application Environment Functionality Described in the J2EE Specification.
1. The J2ee Specification IS Available At
http://java.sun.com/j2ee
Web Applications
JavaTM Servlet Specification Version 2.2 46
Mapping Requests to servlets
JavaTM Servlet Specification Version 2.2 47
10 mapping requests to servlets
Previous Versions of this Specification Have Allowed Servlet Containers a Great Deal of Flexibility in
Mapping Client Requests to servlets Only Defining a set a suggested mapping techniques. this
Specification Now Requires a set of mapping techniques to be used for Web Applications Which Are
Deployed Via the Web Application Deployment Mechanism. Just As It IsHiGhly Recommended ThatServlet Containers Use The Deployment Representation, IT ISHIGHLY
Recommended That the use tres for all purposes and not just AS
Part of deploying a web application.
10.1 Use of url paths
Servlet Containers Must User URL Paths To Map Requests To Servlets. The Container Uses The
Requesturi from The Request, Minus the Context Path, As The Path To Map To a Servlet. The URL
Path Mapping Rules Are As Follows (Where The First Match Wins and No Further Rules Are Attempted):
1. The Servlet Container Will Try to match the exact path of the request to a servlet.
2. THE Container Will THE TO Recursively Match The Longest Path Prefix Mapping. This Process
Occurs by Stepping Down The Path Tree A Directory At A Time, Using The '/' Character As a Path
Separator, and determining if the it is a match with a servlet.
3. if the last node of the url-path contains an extension (.jsp for example), The servlet container
Will Try to match a servlet what handles requests for the extension. an extension is defined as the
Part of the path after the last '.' Character.
4. IF Neither Of The Previous Two Rules Result In A Servlet Match, The Container Will Attempt To Serve
Content Appriate for the Resource Requested. If A "Default" servlet is defined for the application,
IT Will Be buy in this case.
10.2 Specification of mappings
In The Web Application Deployment Descriptor, The Following Syntax IS Used To Define Mappings:
• a string beginning with a '/' character and ending with a '/ *' Postfix IS Used As a path
Mapping.
• A string beginning with a '*.' Prefix is buy. • All Other strings all used as exact matches ONLY
• a string containing only the '/' character indeicates That Servlet Specified by the mapping
Becomes The "default" servlet of the application.
10.2.1 Implicit Mappings
If The Container Has An Internal JSP Container, The * .jsp Extension Is Implicitly Mapped To It So
That JSP Pages May Be Executed on Demand. If The Web Application Defines A * .jsp Mapping, ITS
Mapping Takes Precedence over this implicit mapping.
A servlet container is allowed to make other umplicit mapings as long as evicit mapings take
Precedence. for example, an implicit mapping of * .shtml could be mapped by a container TO A
Server Side Include Functionality.
Mapping Requests to servlets
JavaTM Servlet Specification Version 2.2 48
10.2.2 Example Mapping Set
Consider the folowing set of mappings:
The Following Behavior Would Result:
Note That in the case of /catalog/index.html and /catalog/racecar.bop, The servlet
Mapped to "/ catalog" is not buy as it is not an exact match and the rule doesn't include the '*'
CHARACTER.
Table 3: Example Set of Maps
Path Pattern servlet
/ FOO / BAR / * Servlet1
/ baz / * servlet2
/ catalog servlet3
* .BOP servlet4
Table 4: incoming paths Applied to Example Maps
incoming Path Servlet Handling Request
/foo/bar/index.html servlet1
/FOO/BAR/index.bop servlet1
/ baz servlet2
/BAZ/index.html servlet2
/ catalog servlet3
/catalog/index.html "Default" servlet
/catalog/racecar.bop servlet4
/index.bop servlet4
Security
JavaTM Servlet Specification Version 2.2 49
11 Security
Web Applications Are Created by A Development, Who Then Gives, Sells, or Otherwise
Application to the Deployer for Installation Into a runtime environment. it is useful for theDeveloper to Communicate Attributes About How The Security Should Be Set Up for a Deployed
APPLICATION.
AS with the Web Application Directory Layout and Deployment Descriptor, The elements of this
Section is Only Required As a Deployment Representation, Not a Runtime Reperesentation. However, IT
IS Recommended That Containers Implement Thase Elements As Part of Their Runtime Representation.
11.1 Introduction
A Web Application Contains Many Resources That Can Be Accessed by Many Users. SENSITIVE
Information of TRAVERSES UNPROTECTED OPEN NETWORKS, Such as the Internet. in Such AN
Environment, There Is A Substantial Number Web Applications That Have Some Level of Security
Requirements. Most Servlet Containers Have The Specific Mechanisms and Infrastructure To Meet
SHESE REQUIREMENTS. Although The Quality Assurances and Implementation Details May Vary, All of
Thase Mechanisms Share Some of the Following Characteristics:
• Authentication: The Mechanism by Which Communicating Entities Prove To One Another That
They area acting on behalf of specific identities.
• Access Control for Resources: The Mechanism by Which Interactions with resources Are Limited
To collections of users or programs for the purpose of enforcing availability, integrity, or
Confidentiality.
• Data Integrity: The Mechanism Used to Prove That Information Could Not Have Been Modified by
A third party while in transit.
• Confidentiality Or Data Privacy: The Mechanism Used to Ensure That The Information Is Only
Made Available to Users Who Are Authorized to Access It and is not comprised during
Transmission.
11.2 Declarative Security
Declarative security refers
Deployment Descriptor is The Primary VEHICLE for Declarative Security In Web Applications.
The Deployer Maps The Application's Logical Security Requirements to a representation of the
Security Policy That Is Specific To The Runtime Environment. AT Runtime, The Servlet Container Uses The Servlet Container
Security Policy That Was Derived from the deployment descriptor and configured by the deployer to - THE DEPLOYER TO
Enforce Authentication.
11.3 Programmatic Security
Programmatic security is buy by security aware application foring
Sufficient to Express The Security Model of the Application. Programmatic Security Consists of the
FOLLOWING METHODS of The HttpServletRequest Interface:
• GetRemoteuser
• iSuserinRole
Security
JavaTM Servlet Specification Version 2.2 50
• GetUserPrincipal
The GetRemoteuser Method Returns The User Name That The Client Authenticated with. Thae
iSuserinRole Queries the underlying security mechanism of the container to determine if A
Particular User is in a Given Security Role. The GetUserPrinciPle Method Returns A
Java.security.pricipal object.
THESE APIW Servlets to make Business Logic Decisions Based on the logical role of the remote
User. The Current User..................
IF GetRemoteuser Returns Null (Which Means That No User Has Been Authenticated, THE
iSuserinrole Method Will Always Return False and The GetUserPrincipal Will Always
Return null.
11.4 ROLES
A Role IS AN Abstract Logical Grouping of Users That Is Defined by the Application Developer Orssembler. When the Application IS Deployed, Thase Roles Are Mapped by a Deployer To Security
Identities, Such As Principals or Groups, in the runtime environment.
A servlet container enforces declarative or Programmatic Security for the Principal Associated with the PROGRATIN
An Incoming Request Based on The Security Attributes of That Calling Principal. For Example,
1. WHEN a Deployer Has Mapped A Security Role to a User Group in The Operational Environment. The Operational Environment. The Operational Environment. The Operational Environment.
User group to which the calling principal belongs is retrieved from its security attributes. if the
Principal's User Group Matches The User Group in The Operational Environment That The Security
Role Has Been Mapped to, The Principal is in the security role.
2. WHEN a Deployer Has Mapped A Security Role To a Principal Name in a security policy domain, the
Principal Name of The Calling Principal is Retrieved from ITS Security Attributes. if The Principal IS
THE SAME As The Principal To Which The Security Role Was Mapped, The Calling Principal is in the
Security role.
11.5 Authentication
A Web Client CAN Authenticate a User To a Web Server Using One of the Following Mechanisms:
• http Basic Authentication
• http Digest Authentication
• https client authentication
• FORM BASED Authentication
11.5.1 HTTP Basic Authentication
HTTP Basic Authentication Is The Authentication Mechanism Defined in The HTTP / 1.1 Specification.
This Mechanism Is Based ON A UserName and Password. A Web Server Requests A Web Client To
Authenticate The User. As Part of The Request, The Web Server Passs The String Called The Realm of The STRING
Request in which the user is to be authenticated. it is important to note what the realm save of thebasic authentication mechanism does NOT HAVE TO REFLECT ANY PARTICTICA
(Which Confusingly, Can Also Be Referred To As a realm). The Web Client Obtains the UserName and The
Password from the user an transmits Them to the Web server. The Web Server the Authenticates The Web Server THE
User in the specified realm.
Basic Authentication IS Not a Secure Authentication Protocol as the user password is transmitted
WITH A Simple Base64 Encoding and The Target Server IS Not Authenticated. However, Additional
Protection, Such As Applying a Secure Transport Mechanism (Https) Or Using Security At The
NetWork Level (Such as The IPsec Protocol or VPN Strategies) CAN AlleViate Some of these Concerns.
Security
JavaTM Servlet Specification Version 2.2 51
11.5.2 HTTP Digest Authentication
Like http Basic Authentication, Http Digest Authentication Authenticates a User Based ON A
Username and a password. however the authentication is performance by Transmitting The Password in
An Encrypted Form What Simple Base64 Encoding Used by Basic
Authentication. This Authentication Method Is Not As Secure As Any Private Key Scheme Such AS
HTTPS Client Authentication. As Digest Authentication IS Not Currently In Wide, Servlet
Containers Are Not Required, But Are Encouraged, To Support IT.
11.5.3 Form Based Authentication
The Look and Feel of The "Login Screen" Cannot Be Controlled with An Http Browser's Builtin
Authentication Mechanisms. Therefore this specification defines a form based authentication
Mechanism Which Allows A Developer to Control The Look and Feel of The Login Screens.
The Web Application Deployment Descriptor Contains Entries for a login form and error page to be
Used with this mechanism. The login form must contain field for the user to specify usrname and
Password. Thase Fields Must Be named 'j_username' and 'j_password', respectively.
WHEN a User Attempts to Access A Protected Web Resource, The Container Checks If The User Has Been
Authenticated. if So, And Dependent On The User's Authority To Access The Resource, The Requested Web
Resource is activated and returned. if the user is not auticated, all of the following steps occr:
1. The login form associated with the security constraint is returned to the client. The URL PATH
Which Triggered The Authentication is Stored by The Container.
2. The Client Fills Out The Form, INCLUDING The Username and Password Fields.
3. The form is posted back to the server.
4. The Container Processes The Form To Authenticate The User. If Authentication Fails, The Error Page IS
Returned.
5. The Authenticated Principal IS CHECKED TO SEE IT IT IS in An Authorized Role for Accessing The ORIGINAL
Web Request.
6. The client is redirected to the original resource using the original store.
IF the user is not success, the error page is returned to the client. It is
Recommended That The error Page Contains Information That Allows the user to determine That
Authorization failed.
Like Basic Authentication, this Is Not a Secure Authentication Protocol as The user password is
Tregetted as plain text and the target server is not authenticated. However, Additional Protection,
Such as Applying a Secure Transport Mechanism (https) Or Using Security At The Network Level
(Ipsec or vpn) Can AlleViate Some of these Concerns.11.5.3.1 Login Form Notes
FORM BASED LOGIN AND URL BASED SESSION TRACKING CAN Be PROBLEMATIC TO IMPLEMENT. IT IS STRONGLY
Recommended That Form Based Login Only Be Used by SESSION IS Being Maintained by Cookies
Or by ssl session information.
In Order for the Authentication To Proceed Appropriately, The Action of The Login Form Must Always Be
"J_security_check". This Restriction is Made So That The Login Form Will Always Work No
Matter What The Resource Is That Requests It and Avoids Requiring That The Server to Process
Outbound form to correct the an action field.
Here is an html sample showing how the form shouth be code INTO The HTML PAGE:
Security
JavaTM Servlet Specification Version 2.2 52