Jakarta Servlet SpecificationJakarta Servlet Team httpsprojectseclipseorgprojectsee4jservlet
50 September 07 2020 Final
Table of ContentsCopyright 3
Eclipse Foundation Specification License 3
Disclaimers 3
Jakarta Servlet Specification Version 50 5
Preface 5
Additional Sources 5
Who Should Read This Specification 5
API Reference 6
Other Jakarta Platform Specifications 6
Other Important References 6
Providing Feedback 7
1 Overview 9
11 What is a Servlet 9
12 What is a Servlet Container 9
13 An Example 9
14 Comparing Servlets with Other Technologies 10
15 Relationship to Jakarta EE Platform 10
2 The Servlet Interface 11
21 Request Handling Methods 11
211 HTTP Specific Request Handling Methods 11
212 Additional Methods 11
213 Conditional GET Support 12
22 Number of Instances 12
221 Note About The Single Thread Model 12
23 Servlet Life Cycle 13
231 Loading and Instantiation 13
232 Initialization 13
2321 Error Conditions on Initialization 13
2322 Tool Considerations 13
233 Request Handling 14
2331 Multithreading Issues 14
2332 Exceptions During Request Handling 14
2333 Asynchronous processing 15
2334 Thread Safety 24
2335 Upgrade Processing 25
234 End of Service 25
3 The Request 27
31 HTTP Protocol Parameters 27
311 When Parameters Are Available 27
32 File Upload 28
33 Attributes 28
34 Headers 29
35 Request Path Elements 29
36 Path Translation Methods 31
37 Non-Blocking IO 31
38 HTTP2 Server Push 32
39 Cookies 33
310 SSL Attributes 33
311 Internationalization 34
312 Request Data Encoding 34
313 Lifetime of the Request Object 35
4 Servlet Context 37
41 Introduction to the ServletContext Interface 37
42 Scope of a ServletContext Interface 37
43 Initialization Parameters 37
44 Configuration Methods 37
441 Programmatically Adding and Configuring Servlets 38
4411 addServlet(String servletName String className) 38
4412 addServlet(String servletName Servlet servlet) 38
4413 addServlet(String servletName Class lt extends Servletgt servletClass) 38
4414 addJspFile(String servletName String jspfile) 38
4415 ltT extends Servletgt T createServlet(ClassltTgt clazz) 38
4416 ServletRegistration getServletRegistration(String servletName) 38
4417 MapltString extends ServletRegistrationgt getServletRegistrations() 38
442 Programmatically Adding and Configuring Filters 39
4421 addFilter(String filterName String className) 39
4422 addFilter(String filterName Filter filter) 39
4423 addFilter(String filterName Class lt extends Filtergt filterClass) 39
4424 ltT extends Filtergt T createFilter(ClassltTgt clazz) 39
4425 FilterRegistration getFilterRegistration(String filterName) 39
4426 MapltString extends FilterRegistrationgt getFilterRegistrations() 39
443 Programmatically Adding and Configuring Listeners 40
4431 void addListener(String className) 40
4432 ltT extends EventListenergt void addListener(T t) 40
4433 void addListener(Class lt extends EventListenergt listenerClass) 41
4434 ltT extends EventListenergt void createListener(ClassltTgt clazz) 41
4435 Annotation processing requirements for programmatically added Servlets Filters
and Listeners 42
444 Programmatically Configuring Session Time Out 42
445 Programmatically Configuring Character Encoding 42
45 Context Attributes 43
451 Context Attributes in a Distributed Container 43
46 Resources 43
47 Multiple Hosts and Servlet Contexts 44
48 Reloading Considerations 44
481 Temporary Working Directories 44
5 The Response 47
51 Buffering 47
52 Headers 48
53 HTTP Trailer 49
54 Non-Blocking IO 49
55 Convenience Methods 50
56 Internationalization 51
57 Closure of Response Object 52
58 Lifetime of the Response Object 52
6 Filtering 53
61 What is a Filter 53
611 Examples of Filtering Components 53
62 Main Concepts 54
621 Filter Lifecycle 54
622 Wrapping Requests and Responses 55
623 Filter Environment 56
624 Configuration of Filters in a Web Application 56
625 Filters and the RequestDispatcher 58
7 Sessions 61
71 Session Tracking Mechanisms 61
711 Cookies 61
712 SSL Sessions 61
713 URL Rewriting 61
714 Session Integrity 62
72 Creating a Session 62
73 Session Scope 62
74 Binding Attributes into a Session 63
75 Session Timeouts 63
76 Last Accessed Times 64
77 Important Session Semantics 64
771 Threading Issues 64
772 Distributed Environments 64
773 Client Semantics 65
8 Annotations and Pluggability 67
81 Annotations and Pluggability 67
811 WebServlet 69
812 WebFilter 70
813 WebInitParam 71
814 WebListener 71
815 MultipartConfig 72
816 Other Annotations Conventions 72
82 Pluggability 72
821 Modularity of webxml 72
822 Ordering of webxml and web-fragmentxml 73
823 Assembling the Descriptor from webxml web-fragmentxml and Annotations 79
824 Shared Libraries Runtimes Pluggability 89
83 JSP Container Pluggability 91
84 Processing Annotations and Fragments 92
9 Dispatching Requests 93
91 Obtaining a RequestDispatcher 93
911 Query Strings in Request Dispatcher Paths 93
92 Using a Request Dispatcher 94
93 The Include Method 94
931 Included Request Parameters 94
94 The Forward Method 95
941 Query String 95
942 Forwarded Request Parameters 95
95 Error Handling 96
96 Obtaining an AsyncContext 96
97 The Dispatch Method 96
971 Query String 97
972 Dispatched Request Parameters 97
10 Web Applications 99
101 Web Applications Within Web Servers 99
102 Relationship to ServletContext 99
103 Elements of a Web Application 99
104 Deployment Hierarchies 99
105 Directory Structure 100
1051 Example of Application Directory Structure 101
106 Web Application Archive File 101
107 Web Application Deployment Descriptor 101
1071 Dependencies On Extensions 102
1072 Web Application Class Loader 102
108 Replacing a Web Application 103
109 Error Handling 103
1091 Request Attributes 103
1092 Error Pages 104
1093 Error Filters 105
1010 Welcome Files 105
1011 Web Application Environment 106
1012 Web Application Deployment 107
1013 Inclusion of a webxml Deployment Descriptor 107
11 Application Lifecycle Events 109
111 Introduction 109
112 Event Listeners 109
1121 Event Types and Listener Interfaces 109
1122 An Example of Listener Use 110
113 Listener Class Configuration 110
1131 Provision of Listener Classes 110
1132 Deployment Declarations 111
1133 Listener Registration 111
1134 Notifications At Shutdown 111
114 Deployment Descriptor Example 111
115 Listener Instances and Threading 112
116 Listener Exceptions 112
117 Distributed Containers 113
118 Session Events 113
12 Mapping Requests to Servlets 115
121 Use of URL Paths 115
122 Specification of Mappings 115
1221 Implicit Mappings 116
1222 Example Mapping Set 116
123 Runtime Discovery of Mappings 117
1231 Runtime Discovery of Servlet Mappings 117
13 Security 119
131 Introduction 119
132 Declarative Security 119
133 Programmatic Security 120
134 Programmatic Security Policy Configuration 121
1341 ServletSecurity Annotation 121
13411 Examples 124
13412 Mapping ServletSecurity to security-constraint 126
13413 Mapping HttpConstraint and HttpMethodConstraint to XML 127
1342 setServletSecurity of ServletRegistrationDynamic 129
135 Roles 130
136 Authentication 130
1361 HTTP Basic Authentication 130
1362 HTTP Digest Authentication 131
1363 Form Based Authentication 131
13631 Login Form Notes 132
1364 HTTPS Client Authentication 133
1365 Additional Container Authentication Mechanisms 133
137 Server Tracking of Authentication Information 133
138 Specifying Security Constraints 133
1381 Combining Constraints 134
1382 Example 135
1383 Processing Requests 137
1384 Uncovered HTTP Protocol Methods 137
13841 Rules for Security Constraint Configuration 139
13842 Handling Uncovered HTTP Methods 139
139 Default Policies 140
1310 Login and Logout 140
14 Deployment Descriptor 143
141 Deployment Descriptor Elements 143
142 Rules for Processing the Deployment Descriptor 143
143 Deployment Descriptor 144
144 Examples 144
1441 A Basic Example 145
1442 An Example of Security 146
15 Requirements related to other Specifications 149
151 Sessions 149
152 Web Applications 149
1521 Web Application Class Loader 149
1522 Web Application Environment 149
1523 JNDI Name for Web Module Context Root URL 150
153 Security 151
1531 Propagation of Security Identity in Jakarta Enterprise Bean Calls 151
1532 Container Authorization Requirements 151
1533 Container Authentication Requirements 152
154 Deployment 152
1541 Deployment Descriptor Elements 152
1542 Packaging and Deployment of JAX-WS Components 152
1543 Rules for Processing the Deployment Descriptor 153
155 Annotations and Resource Injection 154
1551 Handling of metadata-complete 154
1552 DeclareRoles 155
1553 EJB Annotation 156
1554 EJBs Annotation 156
1555 Resource Annotation 157
1556 PersistenceContext Annotation 158
1557 PersistenceContexts Annotation 158
1558 PersistenceUnit Annotation 158
1559 PersistenceUnits Annotation 158
15510 PostConstruct Annotation 159
15511 PreDestroy Annotation 159
15512 Resources Annotation 160
15513 RunAs Annotation 160
15514 WebServiceRef Annotation 161
15515 WebServiceRefs Annotation 162
15516 Contexts and Dependency Injection for Jakarta EE Platform Requirements 162
Appendix A Change Log 163
A1 Compatibility with Jakarta Servlet Specification Version 40 163
A2 Changes Since Jakarta Servlet 40 163
Glossary 165
Specification Jakarta Servlet Specification
Version 50
Status Final
Release September 07 2020
Preface
Final Jakarta Servlet Specification 1
Preface
2 Jakarta Servlet Specification Final
CopyrightCopyright (c) 2019 2020 Eclipse Foundation
Eclipse Foundation Specification LicenseBy using andor copying this document or the Eclipse Foundation document from which this statementis linked you (the licensee) agree that you have read understood and will comply with the followingterms and conditions
Permission to copy and distribute the contents of this document or the Eclipse Foundation documentfrom which this statement is linked in any medium for any purpose and without fee or royalty ishereby granted provided that you include the following on ALL copies of the document or portionsthereof that you use
bull link or URL to the original Eclipse Foundation document
bull All existing copyright notices or if one does not exist a notice (hypertext is preferred but a textualrepresentation is permitted) of the form Copyright copy [$date-of-document] Eclipse Foundation Incltlturl to this licensegtgt
Inclusion of the full text of this NOTICE must be provided We request that authorship attribution beprovided in any software documents or other items or products that you create pursuant to theimplementation of the contents of this document or any portion thereof
No right to create modifications or derivatives of Eclipse Foundation documents is granted pursuant tothis license except anyone may prepare and distribute derivative works and portions of this documentin software that implements the specification in supporting materials accompanying such softwareand in documentation of such software PROVIDED that all such works include the notice belowHOWEVER the publication of derivative works of this document for use as a technical specification isexpressly prohibited
The notice is
Copyright copy 2018 2020 Eclipse Foundation This software or document includes material copied fromor derived from Jakarta reg Servlet httpsjakartaeespecificationsservlet50
Disclaimers
THIS DOCUMENT IS PROVIDED AS IS AND THE COPYRIGHT HOLDERS AND THE ECLIPSEFOUNDATION MAKE NO REPRESENTATIONS OR WARRANTIES EXPRESS OR IMPLIED INCLUDINGBUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSENON-INFRINGEMENT OR TITLE THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANYPURPOSE NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRDPARTY PATENTS COPYRIGHTS TRADEMARKS OR OTHER RIGHTS
Eclipse Foundation Specification License
Final Jakarta Servlet Specification 3
THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION WILL NOT BE LIABLE FOR ANY DIRECTINDIRECT SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT ORTHE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF
The name and trademarks of the copyright holders or the Eclipse Foundation may NOT be used inadvertising or publicity pertaining to this document or its contents without specific written priorpermission Title to copyright in this document will at all times remain with copyright holders
Eclipse Foundation Specification License
4 Jakarta Servlet Specification Final
Jakarta Servlet Specification Version 50Copyright (c) 2020 Contributors to the Eclipse Foundation
Eclipse is a registered trademark of the Eclipse Foundation Jakarta is a trademark of the EclipseFoundation Oracle and Java are registered trademarks of Oracle andor its affiliates Other names maybe trademarks of their respective owners
The Jakarta Servlet Team - September 07 2020
Comments to servlet-deveclipseorg [mailtoservlet-deveclipseorg]
PrefaceThis document is the Jakarta Servlet Specification version 50 The standard for the Jakarta Servlet APIis described herein
Additional SourcesThe specification is intended to be a complete and clear explanation of the Jakarta Servlet API but ifquestions remain the following sources may be consulted
bull A reference implementation (RI) has been made available which provides a behavioral benchmarkfor this specification Where the specification leaves implementation of a particular feature open tointerpretation implementors may use the reference implementation as a model of how to carry outthe intention of the specification
bull A compatibility test suite (CTS) has been provided for assessing whether implementations meet thecompatibility requirements of the Jakarta Servlet API standard The test results have normativevalue for resolving questions about whether an implementation is standard
bull If further clarification is required the working group for the Jakarta Servlet API under the JakartaEE Working Group should be consulted and is the final arbiter of such issues
Comments and feedback are welcome and will be used to improve future versions
Who Should Read This SpecificationThe intended audience for this specification includes the following groups
bull Web server and application server vendors that want to provide servlet engines that conform tothis standard
bull Authoring tool developers that want to support web applications that conform to this specification
bull Experienced servlet authors who want to understand the underlying mechanisms of servlettechnology
Preface
Final Jakarta Servlet Specification 5
We emphasize that this specification is not a userrsquos guide for servlet developers and is not intended tobe used as such
API ReferenceThe full specifications of classes interfaces and method signatures that define the Jakarta Servlet APIas well as their accompanying Javadoctrade documentation is available online at httpsjakartaeespecificationsservlet
Other Jakarta Platform SpecificationsThe following Jakarta API specifications are referenced throughout this specification
bull Jakarta EE Platform version 9
bull Jakarta Server Pagestrade (JSP) version 30
bull Java Naming and Directory Interfacetrade (JNDI)
bull Jakarta Context and Dependency Injection for the Jakarta EE Platform
bull Jakarta Managed Beans specification
These specifications may be found at the Jakarta EE Platform web site httpsjakartaee
specifications
Other Important ReferencesThe following Internet specifications provide information relevant to the development andimplementation of the Jakarta Servlet API and standard servlet engines
bull RFC 1630 Uniform Resource Identifiers (URI)
bull RFC 1738 Uniform Resource Locators (URL)
bull RFC 3986 Uniform Resource Identifiers (URI) Generic Syntax
bull RFC 1945 Hypertext Transfer Protocol (HTTP10)
bull RFC 2045 MIME Part One Format of Internet Message Bodies
bull RFC 2046 MIME Part Two Media Types
bull RFC 2047 MIME Part Three Message Header Extensions for non-ASCII text
bull RFC 2048 MIME Part Four Registration Procedures
bull RFC 2049 MIME Part Five Conformance Criteria and Examples
bull RFC 6265 HTTP State Management Mechanism
bull RFC 7258 Pervasive Monitoring Is an Attack
bull RFC 7540 Hypertext Transfer Protocol Version 2 (HTTP2)
API Reference
6 Jakarta Servlet Specification Final
bull RFC 7541 HPACK Header Compression for HTTP2 (HPACK)
bull RFC 7230 Hypertext Transfer Protocol (HTTP11) Message Syntax and Routing
bull RFC 7231 Hypertext Transfer Protocol (HTTP11) Semantics and Content
bull RFC 7232 Hypertext Transfer Protocol (HTTP11) Conditional Requests
bull RFC 7233 Hypertext Transfer Protocol (HTTP11) Range Requests
bull RFC 7234 Hypertext Transfer Protocol (HTTP11) Caching
bull RFC 7235 Hypertext Transfer Protocol (HTTP11) Authentication
bull RFC 7301 Transport Layer Security (TLS) Application-Layer Protocol Negotiation Extension (ALPN)
bull RFC 7168 The Hyper Text Coffee Pot Control Protocol for Tea Ef (HTCPCP-TEA)[1]
bull RFC 2617 HTTP Authentication Basic and Digest Authentication
bull RFC 2119 Key words for use in RFCs to Indicate Requirement Levels
Online versions of these RFCs are at httpwwwietforgrfc
The World Wide Web Consortium (httpwwww3org) is a definitive source of HTTP relatedinformation affecting this specification and its implementations
The eXtensible Markup Language (XML) is used for the specification of the Deployment Descriptorsdescribed in Chapter 13 of this specification
The key words MUST MUST NOT REQUIRED SHALL SHALL NOT SHOULD SHOULD NOTRECOMMENDED NOT RECOMMENDED MAY and OPTIONAL in this document are to beinterpreted as described in RFC2119
Providing FeedbackWe welcome any and all feedback about this specification Please e-mail your comments to servlet-deveclipseorg
[1] This reference is mostly tongue-in-cheek although most of the concepts described in the HTCPCP -TEA RFC arerelevant to all well-designed web servers
Providing Feedback
Final Jakarta Servlet Specification 7
Providing Feedback
8 Jakarta Servlet Specification Final
Chapter 1 Overview
11 What is a ServletA servlet is a Jakarta technology-based web component managed by a container that generatesdynamic content Like other Jakarta technology-based components servlets are platform-independentJava classes that are compiled to platform-neutral byte code that can be loaded dynamically into andrun by a Jakarta technology-enabled web server Containers sometimes called servlet engines are webserver extensions that provide servlet functionality Servlets interact with web clients via arequestresponse paradigm implemented by the servlet container
12 What is a Servlet ContainerThe servlet container is a part of a web server or application server that provides the network servicesover which requests and responses are sent decodes MIME-based requests and formats MIME-basedresponses A servlet container also contains and manages servlets through their lifecycle
A servlet container can be built into a host web server or installed as an add-on component to a webserver via that serverrsquos native extension API Servlet containers can also be built into or possiblyinstalled into web-enabled application servers
All servlet containers must support HTTP as a protocol for requests and responses but additionalrequestresponse-based protocols such as HTTPS (HTTP over SSL) may be supported The requiredversions of the HTTP specification that a container must implement are HTTP11 and HTTP2 Whensupporting HTTP2 servlet containers must support the ldquoh2rdquo and ldquoh2crdquo protocol identifiers (asspecified in section 31 of the HTTP2 RFC) This implies all servlet containers must support ALPNBecause the container may have a caching mechanism described in RFC 7234 (HTTP11 Caching) itmay modify requests from the clients before delivering them to the servlet may modify responsesproduced by servlets before sending them to the clients or may respond to requests without deliveringthem to the servlet under the compliance with RFC 7234
A servlet container may place security restrictions on the environment in which a servlet executesThese restrictions may be placed using the permission architecture defined by the Java platform Forexample some application servers may limit the creation of a Thread object to insure that othercomponents of the container are not negatively impacted
Java SE 8 is the minimum version of the underlying Java platform with which servlet containers mustbe built
13 An ExampleThe following is a typical sequence of events
1 A client (eg a web browser) accesses a web server and makes an HTTP request
11 What is a Servlet
Final Jakarta Servlet Specification 9
2 The request is received by the web server and handed off to the servlet container The servletcontainer can be running in the same process as the host web server in a different process on thesame host or on a different host from the web server for which it processes requests
3 The servlet container determines which servlet to invoke based on the configuration of its servletsand calls it with objects representing the request and response
4 The servlet uses the request object to find out who the remote user is what HTTP POST parametersmay have been sent as part of this request and other relevant data The servlet performs whateverlogic it was programmed with and generates data to send back to the client It sends this data backto the client via the response object
5 Once the servlet has finished processing the request the servlet container ensures that theresponse is properly flushed and returns control back to the host web server
14 Comparing Servlets with Other TechnologiesIn functionality servlets provide a higher level abstraction than Common Gateway Interface (CGI)programs but a lower level of abstraction than that provided by web frameworks such as JakartaServer Faces
Servlets have the following advantages over other server extension mechanisms
bull They are generally much faster than CGI scripts because a different process model is used
bull They use a standard API that is supported by many web servers
bull They have all the advantages of the Java programming language including ease of developmentand platform independence
bull They can access the large set of APIs available for the Java platform
15 Relationship to Jakarta EE PlatformThe Jakarta Servlet API v50 is a required API of the Jakarta EE Platform 9[2] Servlet containers andservlets deployed into them must meet additional requirements described in the Jakarta EEspecification for executing in a Jakarta EE environment
[2] Please see the Jakarta EE Platform specification available at httpsjakartaeespecificationsplatform9
14 Comparing Servlets with Other Technologies
10 Jakarta Servlet Specification Final
Chapter 2 The Servlet InterfaceThe Servlet interface is the central abstraction of the Jakarta Servlet API All servlets implement thisinterface either directly or more commonly by extending a class that implements the interface Thetwo classes in the Jakarta Servlet API that implement the Servlet interface are GenericServlet andHttpServlet For most purposes Developers will extend HttpServlet to implement their servlets
21 Request Handling MethodsThe basic Servlet interface defines a service method for handling client requests This method is calledfor each request that the servlet container routes to an instance of a servlet
The handling of concurrent requests to a web application generally requires that the web developerdesign servlets that can deal with multiple threads executing within the service method at a particulartime
Generally the web container handles concurrent requests to the same servlet by concurrent executionof the service method on different threads
211 HTTP Specific Request Handling Methods
The HttpServlet abstract subclass adds additional methods beyond the basic Servlet interface that areautomatically called by the service method in the HttpServlet class to aid in processing HTTP-basedrequests These methods are
bull doGet for handling HTTP GET requests
bull doPost for handling HTTP POST requests
bull doPut for handling HTTP PUT requests
bull doDelete for handling HTTP DELETE requests
bull doHead for handling HTTP HEAD requests
bull doOptions for handling HTTP OPTIONS requests
bull doTrace for handling HTTP TRACE requests
Typically when developing HTTP-based servlets an Application Developer is concerned with the doGetand doPost methods The other methods are considered to be methods for use by programmers veryfamiliar with HTTP programming
212 Additional Methods
The doPut and doDelete methods allow Servlet Developers to support HTTP11 clients that employ thesefeatures The doHead method in HttpServlet is a specialized form of the doGet method that returns onlythe headers produced by the doGet method The doOptions method responds with which HTTP methods
21 Request Handling Methods
Final Jakarta Servlet Specification 11
are supported by the servlet The doTrace method generates a response containing all instances of theheaders sent in the TRACE request
The CONNECT method is not supported because it applies to proxies and the Jakarta Servlet API istargeted at endpoints
213 Conditional GET Support
The HttpServlet class defines the getLastModified method to support conditional GET operations Aconditional GET operation requests a resource be sent only if it has been modified since a specifiedtime In appropriate situations implementation of this method may aid efficient utilization of networkresources
22 Number of InstancesThe servlet declaration which is either via the annotation as described in Chapter 8 Annotations andPluggability or part of the deployment descriptor of the web application containing the servlet asdescribed in Chapter 14 Deployment Descriptor controls how the servlet container provides instancesof the servlet
For a servlet not hosted in a distributed environment (the default) the servlet container must use onlyone instance per servlet declaration However for a servlet implementing the SingleThreadModelinterface the servlet container may instantiate multiple instances to handle a heavy request load andserialize requests to a particular instance
In the case where a servlet was deployed as part of an application marked in the deploymentdescriptor as distributable a container may have only one instance per servlet declaration per JavaVirtual Machine (JVMtrade) However if the servlet in a distributable application implements theSingleThreadModel interface the container may instantiate multiple instances of that servlet in eachJVM of the container
221 Note About The Single Thread Model
The use of the SingleThreadModel interface guarantees that only one thread at a time will execute in agiven servlet instancersquos service method It is important to note that this guarantee only applies to eachservlet instance since the container may choose to pool such objects Objects that are accessible tomore than one servlet instance at a time such as instances of HttpSession may be available at anyparticular time to multiple servlets including those that implement SingleThreadModel
It is recommended that a developer take other means to resolve those issues instead of implementingthis interface such as avoiding the usage of an instance variable or synchronizing the block of the codeaccessing those resources The SingleThreadModel Interface has been deprecated since version 24 ofthis specification
22 Number of Instances
12 Jakarta Servlet Specification Final
23 Servlet Life CycleA servlet is managed through a well defined life cycle that defines how it is loaded and instantiated isinitialized handles requests from clients and is taken out of service This life cycle is expressed in theAPI by the init service and destroy methods of the jakartaservletServlet interface that all servletsmust implement directly or indirectly through the GenericServlet or HttpServlet abstract classes
231 Loading and Instantiation
The servlet container is responsible for loading and instantiating servlets The loading andinstantiation can occur when the container is started or delayed until the container determines theservlet is needed to service a request
When the servlet engine is started needed servlet classes must be located by the servlet container Theservlet container loads the servlet class using normal Java class loading facilities The loading may befrom a local file system a remote file system or other network services
After loading the Servlet class the container instantiates it for use
232 Initialization
After the servlet object is instantiated the container must initialize the servlet before it can handlerequests from clients Initialization is provided so that a servlet can read persistent configuration datainitialize costly resources (such as JDBCtrade API-based connections) and perform other one-timeactivities The container initializes the servlet instance by calling the init method of the Servletinterface with a unique (per servlet declaration) object implementing the ServletConfig interface Thisconfiguration object allows the servlet to access name-value initialization parameters from the webapplicationrsquos configuration information The configuration object also gives the servlet access to anobject (implementing the ServletContext interface) that describes the servletrsquos runtime environmentSee Chapter 4 Servlet Context for more information about the ServletContext interface
2321 Error Conditions on Initialization
During initialization the servlet instance can throw an UnavailableException or a ServletException Inthis case the servlet must not be placed into active service and must be released by the servletcontainer The destroy method is not called as it is considered unsuccessful initialization
A new instance may be instantiated and initialized by the container after a failed initialization Theexception to this rule is when an UnavailableException indicates a minimum time of unavailability andthe container must wait for the period to pass before creating and initializing a new servlet instance
2322 Tool Considerations
The triggering of static initialization methods when a tool loads and introspects a web application is tobe distinguished from the calling of the init method Developers should not assume a servlet is in anactive container runtime until the init method of the Servlet interface is called For example a servlet
23 Servlet Life Cycle
Final Jakarta Servlet Specification 13
should not try to establish connections to databases or Jakarta Enterprise Beans containers when onlystatic (class) initialization methods have been invoked
233 Request Handling
After a servlet is properly initialized the servlet container may use it to handle client requestsRequests are represented by request objects of type ServletRequest The servlet fills out responses torequests by calling methods of a provided object of type ServletResponse These objects are passed asparameters to the service method of the Servlet interface
In the case of an HTTP request the objects provided by the container are of types HttpServletRequestand HttpServletResponse
Note that a servlet instance placed into service by a servlet container may handle no requests duringits lifetime
2331 Multithreading Issues
A servlet container may send concurrent requests through the service method of the servlet To handlethe requests the Application Developer must make adequate provisions for concurrent processingwith multiple threads in the service method
An alternative for the Application Developer was to implement the SingleThreadModel interface but thisis now deprecated The SingleThreadModel interface requires the container to guarantee that there isonly one request thread at a time in the service method A servlet container may satisfy thisrequirement by serializing requests on a servlet or by maintaining a pool of servlet instances If theservlet is part of a web application that has been marked as distributable the container may maintaina pool of servlet instances in each JVM that the application is distributed across
For servlets not implementing the SingleThreadModel interface if the service method (or methods suchas doGet or doPost to which the service method of the HttpServlet abstract class is dispatched) has beendefined with the synchronized keyword the servlet container cannot use the instance pool approachbut must serialize requests through it It is strongly recommended that Developers not synchronize theservice method (or methods dispatched to it) in these circumstances because of detrimental effects onperformance
2332 Exceptions During Request Handling
A servlet may throw either a ServletException or an UnavailableException during the service of arequest A ServletException signals that some error occurred during the processing of the request andthat the container should take appropriate measures to clean up the request
An UnavailableException signals that the servlet is unable to handle requests either temporarily orpermanently
If a permanent unavailability is indicated by the UnavailableException the servlet container mustremove the servlet from service call its destroy method and release the servlet instance Any requests
23 Servlet Life Cycle
14 Jakarta Servlet Specification Final
refused by the container by that cause must be returned with a SC_NOT_FOUND (404) response
If temporary unavailability is indicated by the UnavailableException the container may choose to notroute any requests through the servlet during the time period of the temporary unavailability Anyrequests refused by the container during this period must be returned with a SC_SERVICE_UNAVAILABLE(503) response status along with a Retry-After header indicating when the unavailability willterminate
The container may choose to ignore the distinction between a permanent and temporaryunavailability and treat all UnavailableExceptions as permanent thereby removing a servlet thatthrows any UnavailableException from service
2333 Asynchronous processing
Sometimes a filter andor servlet is unable to complete the processing of a request without waiting fora resource or event before generating a response For example a servlet may need to wait for anavailable JDBC connection for a response from a remote web service for a JMS message or for anapplication event before proceeding to generate a response Waiting within the servlet is an inefficientoperation as it is a blocking operation that consumes a thread and other limited resources Frequentlya slow resource such as a database may have many threads blocked waiting for access and can causethread starvation and poor quality of service for an entire web container
The asynchronous processing of requests is introduced to allow the thread to return to the containerand perform other tasks When asynchronous processing begins on the request another thread orcallback may either generate the response and call complete or dispatch the request so that it may runin the context of the container using the AsyncContextdispatch method A typical sequence of eventsfor asynchronous processing is
1 The request is received and passed via normal filters for authentication etc to the servlet
2 The servlet processes the request parameters andor content to determine the nature of therequest
3 The servlet issues requests for resources or data for example sends a remote web service requestor joins a queue waiting for a JDBC connection
4 The servlet returns without generating a response
5 After some time the requested resource becomes available the thread handling that eventcontinues processing either in the same thread or by dispatching to a resource in the containerusing the AsyncContext
Jakarta EE features such as Section 1522 ldquoWeb Application Environmentrdquo and Section 1531ldquoPropagation of Security Identity in Jakarta Enterprise Bean Callsrdquo are available only to threadsexecuting the initial request or when the request is dispatched to the container via theAsyncContextdispatch method Jakarta EE features may be available to other threads operating directlyon the response object via the AsyncContextstart(Runnable) method
The WebServlet and WebFilter annotations described in Chapter 8 have an attribute asyncSupported
23 Servlet Life Cycle
Final Jakarta Servlet Specification 15
that is a boolean with a default value of false When asyncSupported is set to true the application canstart asynchronous processing in a separate thread by calling startAsync (see below) passing it areference to the request and response objects and then exit from the container on the original threadThis means that the response will traverse (in reverse order) the same filters (or filter chain) that weretraversed on the way in The response isnrsquot committed till complete (see below) is called on theAsyncContext The application is responsible for handling concurrent access to the request andresponse objects if the async task is executing before the container-initiated dispatch that calledstartAsync has returned to the container
Dispatching from a servlet that has asyncSupported=true to one where asyncSupported is set to false isallowed In this case the response will be committed when the service method of the servlet that doesnot support async is exited and it is the containerrsquos responsibility to call complete on the AsyncContextso that any interested AsyncListener instances will be notified The AsyncListeneronComplete
notification should also be used by filters as a mechanism to clear up resources that they have beenholding on to for the async task to complete
Dispatching from a synchronous servlet to an asynchronous servlet would be illegal However thedecision of throwing an IllegalStateException is deferred to the point when the application callsstartAsync This would allow a servlet to either function as a synchronous or an asynchronous servlet
The async task that the application is waiting for could write directly to the response on a differentthread than the one that was used for the initial request This thread knows nothing about any filtersIf a filter wanted to manipulate the response in the new thread it would have to wrap the responsewhen it was processing the initial request on the way in and passed the wrapped response to thenext filter in the chain and eventually to the servlet So if the response was wrapped (possibly multipletimes once per filter) and the application processes the request and writes directly to the response itis really writing to the response wrapper(s) ie any output added to the response will still beprocessed by the response wrapper(s) When an application reads from a request in a separate threadand adds output to the response it really reads from the request wrapper(s) and writes to theresponse wrapper(s) so any input andor output manipulation intended by the wrapper(s) willcontinue to occur
Alternately if the application chooses to do so it can use the AsyncContext to dispatch the request fromthe new thread to a resource in the container This would enable using content generationtechnologies like Jakarta Server Pages within the scope of the container
In addition to the annotation attributes the following methods classes are provided
ServletRequest
public AsyncContext startAsync(ServletRequest req ServletResponse res)
This method puts the request into asynchronous mode and initializes its AsyncContext with the givenrequest and response objects and the time out returned by getAsyncTimeout The ServletRequest andServletResponse parameters MUST be either the same objects as were passed to the calling servletrsquosservice or the filterrsquos doFilter method or be subclasses of ServletRequestWrapper orServletResponseWrapper classes that wrap them A call to this method ensures that the response isnrsquot
23 Servlet Life Cycle
16 Jakarta Servlet Specification Final
committed when the application exits out of the service method It is committed whenAsyncContextcomplete is called on the returned AsyncContext or the AsyncContext times out and thereare no listeners associated to handle the time out The timer for async time outs will not start untilthe request and its associated response have returned from the container The AsyncContext couldbe used to write to the response from the async thread It can also be used to just notify that theresponse is not closed and committed
It is illegal to call startAsync if the request is within the scope of a servlet or filter that does notsupport asynchronous operations or if the response has been committed and closed or is calledagain during the same dispatch The AsyncContext returned from a call to startAsync can then beused for further asynchronous processing Calling the AsyncContexthasOriginalRequestResponse()on the returned AsyncContext will return false unless the passed ServletRequest andServletResponse arguments are the original ones and do not carry application provided wrappersAny filters invoked in the outbound direction after this request was put into asynchronous modeMAY use this as an indication that some of the request and or response wrappers that they addedduring their inbound invocation MAY need to stay in place for the duration of the asynchronousoperation and their associated resources MAY not be released A ServletRequestWrapper appliedduring the inbound invocation of a filter MAY be released by the outbound invocation of the filteronly if the given ServletRequest which is used to initialize the AsyncContext and will be returned by acall to AsyncContextgetRequest() does not contain the said ServletRequestWrapper The same holdstrue for ServletResponseWrapper instances
public AsyncContext startAsync()
This method is provided as a convenience that uses the original request and response objects for theasync processing Please note users of this method SHOULD flush the response if they are wrappedbefore calling this method if you wish to ensure that any data written to the wrapped response isnrsquotlost
public AsyncContext getAsyncContext()
Returns the AsyncContext that was created or re initialized by the invocation of startAsync It isillegal to call getAsyncContext if the request has not been put in asynchronous mode
public boolean isAsyncSupported()
Returns true if the request supports async processing and false otherwise Async support will bedisabled as soon as the request has passed a filter or servlet that does not support async processing(either via the designated annotation or declaratively)
public boolean isAsyncStarted()
Returns true if async processing has started on this request and false otherwise If this request hasbeen dispatched using one of the AsyncContextdispatch methods since it was put in asynchronousmode or a call to AsynContextcomplete is made this method returns false
public DispatcherType getDispatcherType()
Returns the dispatcher type of a request The dispatcher type of a request is used by the container toselect the filters that need to be applied to the request Only filters with the matching dispatcher
23 Servlet Life Cycle
Final Jakarta Servlet Specification 17
type and url patterns will be applied Allowing a filter that has been configured for multipledispatcher types to query a request for its dispatcher type allows the filter to process the requestdifferently depending on its dispatcher type The initial dispatcher type of a request is defined asDispatcherTypeREQUEST The dispatcher type of a request dispatched viaRequestDispatcherforward(ServletRequest ServletResponse) orRequestDispatcherinclude(ServletRequest ServletResponse) is given as DispatcherTypeFORWARD orDispatcherTypeINCLUDE respectively while a dispatcher type of an asynchronous request dispatchedvia one of the AsyncContextdispatch methods is given as DispatcherTypeASYNC Finally thedispatcher type of a request dispatched to an error page by the containerrsquos error handlingmechanism is given as DispatcherTypeERROR
AsyncContext
This class represents the execution context for the asynchronous operation that was started on theServletRequest An AsyncContext is created and initialized by a call to ServletRequeststartAsync asdescribed above The following methods are in the AsyncContext
public ServletRequest getRequest()
Returns the request that was used to initialize the AsyncContext by calling one of the startAsyncmethods Calling getRequest when complete or any of the dispatch methods has been previouslycalled in the asynchronous cycle will result in an IllegalStateException
public ServletResponse getResponse()
Returns the response that was used to initialize the AsyncContext by calling one of the startAsyncmethods Calling getResponse when complete or any of the dispatch methods has been previouslycalled in the asynchronous cycle will result in an IllegalStateException
public void setTimeout(long timeoutMilliseconds)
Sets the time out for the asynchronous processing in milliseconds A call to this method overridesthe time out set by the container If the time out is not specified via the call to setTimeout 30000 isused as the default A value of 0 or less indicates that the asynchronous operation will never timeout The time out applies to the AsyncContext once the container-initiated dispatch during whichone of the ServletRequeststartAsync methods was called has returned to the container It is illegalto call this method after the container-initiated dispatch on which the asynchronous cycle wasstarted has returned to the container and will result in an IllegalStateException
public long getTimeout()
Gets the time out in milliseconds associated with the AsyncContext This method returns thecontainerrsquos default time out or the time out value set via the most recent invocation of setTimeoutmethod
public void addListener(AsyncListener listener ServletRequest req ServletResponse res)
Registers the given listener for notifications of onTimeout onError onComplete or onStartAsync Thefirst three are associated with the most recent asynchronous cycle started by calling one of theServletRequeststartAsync methods The onStartAsync is associated to a new asynchronous cycle viaone of the ServletRequeststartAsync methods Async listeners will be notified in the order in which
23 Servlet Life Cycle
18 Jakarta Servlet Specification Final
they were added to the request The request and response objects passed in to the method are theexact same ones that are available from the AsyncEventgetSuppliedRequest() andAsyncEventgetSuppliedResponse() when the AsyncListener is notified These objects should not beread from or written to because additional wrapping may have occurred since the givenAsyncListener was registered but may be used in order to release any resources associated withthem It is illegal to call this method after the container-initiated dispatch on which theasynchronous cycle was started has returned to the container and before a new asynchronous cyclewas started and will result in an IllegalStateException
public ltT extends AsyncListenergt createListener(ClassltTgt clazz)
Instantiates the given AsyncListener class The returned AsyncListener instance may be furthercustomized before it is registered with the AsyncContext via a call to one of the addListener methodsspecified below The given AsyncListener class MUST define a zero argument constructor which isused to instantiate it This method supports any annotations applicable to the AsyncListener
public void addListener(AsyncListener)
Registers the given listener for notifications of onTimeout onError onComplete or onStartAsync Thefirst three are associated with the most recent asynchronous cycle started by calling one of theServletRequeststartAsync methods The onStartAsync is associated to a new asynchronous cycle viaone of the ServletRequeststartAsync methods If startAsync(req res) or startAsync() is called onthe request the exact same request and response objects are available from the AsyncEvent whenthe AsyncListener is notified The request and response may or may not be wrapped Async listenerswill be notified in the order in which they were added to the request It is illegal to call this methodafter the container-initiated dispatch on which the asynchronous cycle was started has returned tothe container and before a new asynchronous cycle was started and will result in anIllegalStateException
public void dispatch(String path)
Dispatches the request and response that were used to initialize the AsyncContext to the resourcewith the given path The given path is interpreted as relative to the ServletContext that initializedthe AsyncContext All path related query methods of the request MUST reflect the dispatch targetwhile the original request URI context path path info and query string may be obtained from therequest attributes as defined in Section 972 ldquoDispatched Request Parametersrdquo These attributesMUST always reflect the original path elements even after multiple dispatches
public void dispatch()
Provided as a convenience to dispatch the request and response used to initialize the AsyncContextas follows If the AsyncContext was initialized via the startAsync(ServletRequest ServletResponse)and the request passed is an instance of HttpServletRequest then the dispatch is to the URI returnedby HttpServletRequestgetRequestURI() Otherwise the dispatch is to the URI of the request when itwas last dispatched by the container The examples CODE EXAMPLE 2-1 CODE EXAMPLE 2-2 andCODE EXAMPLE 2-3 shown below demonstrate what the target URI of dispatch would be in thedifferent cases
23 Servlet Life Cycle
Final Jakarta Servlet Specification 19
CODE EXAMPLE 2-1
REQUEST to urlAAsyncContext ac = requeststartAsync()acdispatch() ASYNC dispatch to urlA
CODE EXAMPLE 2-2
REQUEST to urlA
FORWARD to urlB
requestgetRequestDispatcher(urlB)forward(request response)
Start async operation from within the target of the FORWARD
AsyncContext ac = requeststartAsync()
acdispatch() ASYNC dispatch to urlA
CODE EXAMPLE 2-3
REQUEST to urlA
FORWARD to urlB
requestgetRequestDispatcher(urlB)forward(request response)
Start async operation from within the target of the FORWARD
AsyncContext ac = requeststartAsync(request response)
acdispatch() ASYNC dispatch to urlB
public void dispatch(ServletContext context String path)
Dispatches the request and response used to initialize the AsyncContext to the resource with thegiven path in the given ServletContext
For all the 3 variations of the dispatch methods defined above calls to the methods returnsimmediately after passing the request and response objects to a container managed thread onwhich the dispatch operation will be performed The dispatcher type of the request is set to ASYNCUnlike RequestDispatcherforward(ServletRequest ServletResponse) dispatches the response bufferand headers will not be reset and it is legal to dispatch even if the response has already beencommitted Control over the request and response is delegated to the dispatch target and the
23 Servlet Life Cycle
20 Jakarta Servlet Specification Final
response will be closed when the dispatch target has completed execution unlessServletRequeststartAsync() or ServletRequeststartAsync(ServletRequest ServletResponse) iscalled If any of the dispatch methods are called before the container-initiated dispatch that calledstartAsync has returned to the container the following conditions must hold during that timebetween the invocation of dispatch and the return of control to the container
i any dispatch invocations invoked during that time will not take effect until after the container-initiated dispatch has returned to the container
ii any AsyncListeneronComplete(AsyncEvent) AsyncListeneronTimeout(AsyncEvent) andAsyncListeneronError(AsyncEvent) invocations will also be delayed until after the container-initiated dispatch has returned to the container
iii any calls to requestisAsyncStarted() must return true until after the container-initiateddispatch has returned to the container
There can be at most one asynchronous dispatch operation per asynchronous cycle which is startedby a call to one of the ServletRequeststartAsync methods Any attempt to perform additionalasynchronous dispatch operations within the same asynchronous cycle is illegal and will result inan IllegalStateException If startAsync is subsequently called on the dispatched request then any ofthe dispatch methods may be called with the same restriction as above
Any errors or exceptions that may occur during the execution of the dispatch methods MUST becaught and handled by the container as follows
i invoke the AsyncListeneronError(AsyncEvent) method for all instances of the AsyncListenerregistered with the ServletRequest for which the AsyncContext was created and make theThrowable available via the AsyncEventgetThrowable()
ii If none of the listeners called AsyncContextcomplete or any of the AsyncContextdispatchmethods then perform an error dispatch with a status code equal toHttpServletResponseSC_INTERNAL_SERVER_ERROR and make the Throwable available as the value ofthe RequestDispatcherERROR_EXCEPTION request attribute
iii If no matching error page is found or the error page does not call AsyncContextcomplete() orany of the AsyncContextdispatch methods then the container MUST call AsyncContextcomplete
public boolean hasOriginalRequestAndResponse()
This method checks if the AsyncContext was initialized with the original request and responseobjects by calling ServletRequeststartAsync() or if it was initialized by callingServletRequeststartAsync(ServletRequest ServletResponse) and neither the ServletRequest nor theServletResponse argument carried any application provided wrappers in which case it returns trueIf the AsyncContext was initialized with wrapped request andor response objects usingServletRequeststartAsync(ServletRequest ServletResponse) it returns false This information maybe used by filters invoked in the outbound direction after a request was put into asynchronousmode to determine whether any request andor response wrappers that they added during theirinbound invocation need to be preserved for the duration of the asynchronous operation or may bereleased
23 Servlet Life Cycle
Final Jakarta Servlet Specification 21
public void start(Runnable r)
This method causes the container to dispatch a thread possibly from a managed thread pool to runthe specified Runnable The container may propagate appropriate contextual information to theRunnable
public void complete()
If requeststartAsync is called then this method MUST be called to complete the async processingand commit and close the response The complete method can be invoked by the container if therequest is dispatched to a servlet that does not support async processing or the target servlet calledby AsyncContextdispatch does not do a subsequent call to startAsync In this case it is thecontainerrsquos responsibility to call complete() as soon as that servletrsquos service method is exited AnIllegalStateException MUST be thrown if startAsync was not called It is legal to call this methodanytime after a call to ServletRequeststartAsync() or ServletRequeststartAsync(ServletRequestServletResponse) and before a call to one of the dispatch methods If this method is called before thecontainer-initiated dispatch that called startAsync has returned to the container the followingconditions must hold during that time between the invocation of complete and the return of controlto the container
i the behavior specified for complete will not take effect until after the container-initiated dispatchhas returned to the container
ii any AsyncListeneronComplete(AsyncEvent) invocations will also be delayed until after thecontainer-initiated dispatch has returned to the container
iii any calls to requestisAsyncStarted() must return true until after the container-initiateddispatch has returned to the container
ServletRequestWrapper
public boolean isWrapperFor(ServletRequest req)
Checks recursively if this wrapper wraps the given ServletRequest and returns true if it does else itreturns false
ServletResponseWrapper
public boolean isWrapperFor(ServletResponse res)
Checks recursively if this wrapper wraps the given ServletResponse and returns true if it does else itreturns false
AsyncListener
public void onComplete(AsyncEvent event)
Is used to notify the listener of completion of the asynchronous operation started on theServletRequest
public void onTimeout(AsyncEvent event)
Is used to notify the listener of a time out of the asynchronous operation started on theServletRequest
23 Servlet Life Cycle
22 Jakarta Servlet Specification Final
public void onError(AsyncEvent event)
Is used to notify the listener that the asynchronous operation has failed to complete
public void onStartAsync(AsyncEvent event)
Is used to notify the listener that a new asynchronous cycle is being initiated via a call to one of theServletRequeststartAsync methods The AsyncContext corresponding to the asynchronous operationthat is being reinitialized may be obtained by calling AsyncEventgetAsyncContext on the given event
In the event that an asynchronous operation times out the container must run through the followingsteps
bull Invoke the AsyncListeneronTimeout method on all the AsyncListener instances registered with theServletRequest on which the asynchronous operation was initiated
bull If none of the listeners called AsyncContextcomplete() or any of the AsyncContextdispatch methodsperform an error dispatch with a status code equal toHttpServletResponseSC_INTERNAL_SERVER_ERROR
bull If no matching error page was found or the error page did not call AsyncContextcomplete() or anyof the AsyncContextdispatch methods the container MUST call AsyncContextcomplete()
bull If an exception is thrown while invoking methods in an AsyncListener it is logged and will notaffect the invocation of any other AsyncListeners
bull Async processing in JSP would not be supported by default as it is used for content generation andasync processing would have to be done before the content generation It is up to the containerhow to handle this case Once all the async activities are done a dispatch to the JSP page using theAsyncContextdispatch can be used for generating content
bull Figure 2-1 shown below is a diagram depicting the state transitions for various asynchronousoperations
Figure 2-1 State transition diagram for asynchronous operations
23 Servlet Life Cycle
Final Jakarta Servlet Specification 23
2334 Thread Safety
Other than the startAsync and complete methods implementations of the request and response objectsare not guaranteed to be thread safe This means that they should either only be used within the scopeof the request handling thread or the application must ensure that access to the request and responseobjects are thread safe
If a thread created by the application uses the container-managed objects such as the request orresponse object those objects must be accessed only within the objectrsquos life cycle as defined in sectionsSection 313 ldquoLifetime of the Request Objectrdquo and Section 58 ldquoLifetime of the Response Objectrdquo
23 Servlet Life Cycle
24 Jakarta Servlet Specification Final
respectively Be aware that other than the startAsync and complete methods the request and responseobjects are not thread safe If those objects were accessed in the multiple threads the access should besynchronized or be done through a wrapper to add the thread safety for instance synchronizing thecall of the methods to access the request attribute or using a local output stream for the responseobject within a thread
2335 Upgrade Processing
In HTTP11 the Upgrade header allows the client to specify the additional communication protocolsthat it supports and would like to use If the server finds it appropriate to switch protocols then newprotocols will be used in subsequent communication
The servlet container provides an HTTP upgrade mechanism However the servlet container itself doesnot have knowledge about the upgraded protocol The protocol processing is encapsulated in theHttpUpgradeHandler Data reading or writing between the servlet container and the HttpUpgradeHandleris in byte streams
When an upgrade request is received the servlet can invoke the HttpServletRequestupgrade methodwhich starts the upgrade process This method instantiates the given HttpUpgradeHandler class Thereturned HttpUpgradeHandler instance may be further customized The application prepares and sendsan appropriate response to the client After exiting the service method of the servlet the servletcontainer completes the processing of all filters and marks the connection to be handled by theHttpUpgradeHandler It then calls the HttpUpgradeHandlers init method passing a WebConnection to allowthe protocol handler access to the data streams
The servlet filters only process the initial HTTP request and response They are not involved insubsequent communications In other words they are not invoked once the request has beenupgraded
The HttpUpgradeHandler may use non-blocking IO to consume and produce messages
The Application Developer has the responsibility for thread safe access to the ServletInputStream andServletOutputStream while processing HTTP upgrade
When the upgrade processing is done HttpUpgradeHandlerdestroy will be invoked
234 End of Service
The servlet container is not required to keep a servlet loaded for any particular period of time Aservlet instance may be kept active in a servlet container for a period of milliseconds for the lifetimeof the servlet container (which could be a number of days months or years) or any amount of time inbetween
When the servlet container determines that a servlet should be removed from service it calls thedestroy method of the Servlet interface to allow the servlet to release any resources it is using and saveany persistent state For example the container may do this when it wants to conserve memoryresources or when it is being shut down
23 Servlet Life Cycle
Final Jakarta Servlet Specification 25
Before the servlet container calls the destroy method it must allow any threads that are currentlyrunning in the service method of the servlet to complete execution or exceed a server-defined timelimit
Once the destroy method is called on a servlet instance the container may not route other requests tothat instance of the servlet If the container needs to enable the servlet again it must do so with a newinstance of the servletrsquos class
After the destroy method completes the servlet container must release the servlet instance so that it iseligible for garbage collection
23 Servlet Life Cycle
26 Jakarta Servlet Specification Final
Chapter 3 The RequestThe request object encapsulates all information from the client request In the HTTP protocol thisinformation is transmitted from the client to the server in the HTTP headers and the message body ofthe request
31 HTTP Protocol ParametersRequest parameters for the servlet are the strings sent by the client to a servlet container as part of itsrequest When the request is an HttpServletRequest object and the conditions set out in Section 311ldquoWhen Parameters Are Availablerdquo are met the container populates the parameters from the URI querystring and POST-ed data
The parameters are stored as a set of name-value pairs Multiple parameter values can exist for anygiven parameter name The following methods of the ServletRequest interface are available to accessparameters
bull getParameter
bull getParameterNames
bull getParameterValues
bull getParameterMap
The getParameterValues method returns an array of String objects containing all the parameter valuesassociated with a parameter name The value returned from the getParameter method must be the firstvalue in the array of String objects returned by getParameterValues The getParameterMap methodreturns a javautilMap of the parameter of the request which contains names as keys and parametervalues as map values
Data from the query string and the post body are aggregated into the request parameter set Querystring data is presented before post body data For example if a request is made with a query string ofa=hello and a post body of a=goodbyeampa=world the resulting parameter set would be ordered a=(hellogoodbye world)
Path parameters that are part of a GET request (as defined by HTTP11) are not exposed by these APIsThey must be parsed from the String values returned by the getRequestURI method or the getPathInfomethod
311 When Parameters Are Available
The following are the conditions that must be met before form data will be populated to the parameterset
1 The request is an HTTP or HTTPS request
2 The HTTP method is POST
31 HTTP Protocol Parameters
Final Jakarta Servlet Specification 27
3 The content type is applicationx-www-form-urlencoded
4 The servlet has made an initial call of any of the getParameter family of methods on the requestobject
If the conditions are not met and the form data is not included in the parameter set the form datamust still be available to the servlet via the request objectrsquos input stream If the conditions are metform data will no longer be available for reading directly from the request objectrsquos input stream
32 File UploadServlet container allows files to be uploaded when data is sent as multipartform-data
The servlet container provides multipartform-data processing if any one of the following conditions ismet
bull The servlet handling the request is annotated with the MultipartConfig as defined in Section 815ldquoMultipartConfigrdquo
bull Deployment descriptors contain a multipart-config element for the servlet handling the request
How data in a request of type multipartform-data is made available depends on whether the servletcontainer provides multipartform-data processing
bull If the servlet container provides multipartform-data processing the data is made availablethrough the following methods in HttpServletRequest
public CollectionltPartgt getParts()
public Part getPart(String name)
Each part provides access to the headers content type related with it and the content via thePartgetInputStream method
For parts with form-data as the Content-Disposition but without a filename the string value of thepart will also be available through the getParameter and getParameterValues methods onHttpServletRequest using the name of the part
bull If the servlet container does not provide the multi-partform-data processing the data will beavailable through HttpServletReuqestgetInputStream
33 AttributesAttributes are objects associated with a request Attributes may be set by the container to expressinformation that otherwise could not be expressed via the API or may be set by a servlet tocommunicate information to another servlet (via the RequestDispatcher) Attributes are accessed withthe following methods of the ServletRequest interface
32 File Upload
28 Jakarta Servlet Specification Final
bull getAttribute
bull getAttributeNames
bull setAttribute
Only one attribute value may be associated with an attribute name
Attribute names beginning with the prefix of jakarta are reserved for definition by this specificationIt is suggested that all attributes placed in the attribute set be named in accordance with the reversedomain name convention suggested by the Java Programming Language Specification [3] for packagenaming
34 HeadersA servlet can access the headers of an HTTP request through the following methods of theHttpServletRequest interface
bull getHeader
bull getHeaders
bull getHeaderNames
The getHeader method returns a header value given the name of the header There can be multipleheaders with the same name eg Cache-Control headers in an HTTP request If there are multipleheaders with the same name the getHeader method returns the value of first header in the request ThegetHeaders method allows access to all the header values associated with a particular header namereturning an Enumeration of String objects
Headers may contain String representations of int or Date data The following convenience methods ofthe HttpServletRequest interface provide access to header data in a one of these formats
bull getIntHeader
bull getDateHeader
If the getIntHeader method cannot translate the header value to an int a NumberFormatException isthrown If the getDateHeader method cannot translate the header to a Date object anIllegalArgumentException is thrown
35 Request Path ElementsThe request path that leads to a servlet servicing a request is composed of many important sectionsThe following elements are obtained from the request URI path and exposed via the request object
bull Context Path The path prefix associated with the ServletContext that this servlet is a part of If thiscontext is the ldquodefaultrdquo context rooted at the base of the web serverrsquos URL name space this pathwill be an empty string Otherwise if the context is not rooted at the root of the serverrsquos name
34 Headers
Final Jakarta Servlet Specification 29
space the path starts with a character but does not end with a character
bull Servlet Path The path section that directly corresponds to the mapping which activated thisrequest This path starts with a character except in the case where the request is matched withthe or pattern in which case it is an empty string
bull PathInfo The part of the request path that is not part of the Context Path or the Servlet Path It iseither null if there is no extra path or is a string with a leading
The following methods exist in the HttpServletRequest interface to access this information
bull getContextPath
bull getServletPath
bull getPathInfo
It is important to note that except for URL encoding differences between the request URI and the pathparts the following equation is always true
requestURI = contextPath + servletPath + pathInfo
To give a few examples to clarify the above points consider the following
Table 3-1 Example Context Configuration
Context Path catalog
Servlet Mapping Pattern lawnServlet LawnServlet
Servlet Mapping Pattern gardenServlet GardenServlet
Servlet Mapping Pattern jspServlet JSPServlet
The following behavior is observed
Table 3-2 Observed Path Element Behavior
Request Path Path Elements
cataloglawnindexhtml ContextPath catalogServletPath lawnPathInfo indexhtml
cataloggardenimplements ContextPath catalogServletPath gardenPathInfo implements
35 Request Path Elements
30 Jakarta Servlet Specification Final
Request Path Path Elements
cataloghelpfeedbackjsp ContextPath catalogServletPath helpfeedbackjspPathInfo null
36 Path Translation MethodsThere are two convenience methods in the API which allow the Application Developer to obtain the filesystem path equivalent to a particular path These methods are
bull ServletContextgetRealPath
bull HttpServletRequestgetPathTranslated
The getRealPath method takes a String argument and returns a String representation of a file on thelocal file system to which a path corresponds The getPathTranslated method computes the real path ofthe pathInfo of the request
In situations where the servlet container cannot determine a valid file path for these methods such aswhen the web application is executed from an archive on a remote file system not accessible locallyor in a database these methods must return null Resources inside the META-INFresources directory ofJAR file must be considered only if the container has unpacked them from their containing JAR filewhen a call to getRealPath() is made and in this case MUST return the unpacked location
37 Non-Blocking IONon-blocking request processing in the web container helps improve the ever increasing demand forimproved web container scalability increase the number of connections that can simultaneously behandled by the web container Non-blocking IO in the servlet container allows developers to read dataas it becomes available or write data when possible to do so Non-blocking IO only works with asyncrequest processing in servlets and filters (as defined in Section 2333 ldquoAsynchronous processingrdquo)and upgrade processing (as defined in Section 2335 ldquoUpgrade Processingrdquo) Otherwise anIllegalStateException must be thrown when ServletInputStreamsetReadListener orServletOutputStreamsetWriteListener is invoked
The ReadListener provides the following callback methods for non-blocking IO
ReadListener
onDataAvailable()
The onDataAvailable method is invoked on the ReadListener when data is available to read from theincoming request stream The container will invoke the method the first time when data is availableto read The container will subsequently invoke the onDataAvailable method if and only if theisReady method on ServletInputStream described below has been called and returned a value offalse and data has subsequently become available to read
36 Path Translation Methods
Final Jakarta Servlet Specification 31
onAllDataRead()
The onAllDataRead method is invoked when all the data for the ServletRequest for which the listenerwas registered has been read
onError(Throwable t)
The onError method is invoked if there is any error or exception that occurs while processing therequest
The servlet container must access methods in ReadListener in a thread safe manner
In addition to the ReadListener defined above the following methods have been added toServletInputStream class
ServletInputStream
boolean isFinished()
The isFinished method returns true when all the data for the request associated with theServletInputStream has been read Otherwise it returns false
boolean isReady()
The isReady method returns true if data can be read without blocking If no data can be readwithout blocking it returns false If isReady returns false it is illegal to call the read method and anIllegalStateException MUST be thrown
void setReadListener(ReadListener listener)
Sets the ReadListener defined above to be invoked to read data in a non-blocking fashion Once alistener is associated with the ServletInputStream the container invokes the methods on theReadListener when data is available to read all the data has been read or if there was an errorprocessing the request Registering a ReadListener will start non-blocking IO It is illegal to switch tothe traditional blocking IO at that point and an IllegalStateException MUST be thrown Asubsequent call to setReadListener in the scope of the current request is illegal and anIllegalStateException MUST be thrown
38 HTTP2 Server PushServer push is the most visible of the improvements in HTTP2 to appear in the servlet API All of thenew features in HTTP2 including server push are aimed at improving the perceived performance ofthe web browsing experience Server push derives its contribution to improved perceived browserperformance from the simple fact that servers are in a much better position than clients to know whatadditional assets (such as images stylesheets and scripts) go along with initial requests For example itis possible for servers to know that whenever a browser requests indexhtml it will shortly thereafterrequest headergif footergif and stylecss Since servers know this they can preemptively startsending the bytes of these assets along side the bytes of the indexhtml
To use server push obtain a reference to a PushBuilder from an HttpServletRequest mutate the builderas desired then call push() Please see the javadoc for method
38 HTTP2 Server Push
32 Jakarta Servlet Specification Final
jakartaservlethttpHttpServletRequestnewPushBuilder() and class jakartaservlethttpPushBuilderfor the normative specification The remainder of this section calls out implementation requirementswith respect to the section titled ldquoServer Pushrdquo in the HTTP2 specification version referenced in OtherImportant References
Unless explicitly excluded Servlet 50 containers must support server push as specified in the HTTP2specification section ldquoServer Pushrdquo Containers must enable server push if the client is capable ofspeaking HTTP2 unless the client has explicitly disabled server push by sending aSETTINGS_ENABLE_PUSH setting value of 0 (zero) for the current connection In that case for thatconnection only server push must not be enabled
In addition to allowing clients to disable server push with the SETTINGS_ENABLE_PUSH setting servletcontainers must honor a clientrsquos request to not receive a pushed response on a finer grained basis byheeding the CANCEL or REFUSED_STREAM code that references the pushed streamrsquos stream identifier Onecommon use of this interaction is when a browser already has the resource in its cache
39 CookiesThe HttpServletRequest interface provides the getCookies method to obtain an array of cookies that arepresent in the request These cookies are data sent from the client to the server on every request thatthe client makes Typically the only information that the client sends back as part of a cookie is thecookie name and the cookie value Other cookie attributes that can be set when the cookie is sent to thebrowser such as comments are not typically returned The specification also allows for the cookies tobe HttpOnly cookies HttpOnly cookies indicate to the client that they should not be exposed to client-side scripting code (itrsquos not filtered out unless the client knows to look for this attribute) The use ofHttpOnly cookies helps mitigate certain kinds of cross-site scripting attacks
310 SSL AttributesIf a request has been transmitted over a secure protocol such as HTTPS this information must beexposed via the isSecure method of the ServletRequest interface The web container must expose thefollowing attributes to the servlet programmer
Table 3-3 Protocol Attributes
Attribute Attribute Name Java Type
cipher suite jakartaservletrequestcipher_suite String
bit size of the algorithm jakartaservletrequestkey_size Integer
SSL session id jakartaservletrequestssl_session_id String
If there is an SSL certificate associated with the request it must be exposed by the servlet container tothe servlet programmer as an array of objects of type javasecuritycertX509Certificate andaccessible via a ServletRequest attribute of jakartaservletrequestX509Certificate
39 Cookies
Final Jakarta Servlet Specification 33
The order of this array is defined as being in ascending order of trust The first certificate in the chainis the one set by the client the next is the one used to authenticate the first and so on
311 InternationalizationClients may optionally indicate to a web server what language they would prefer the response be givenin This information can be communicated from the client using the Accept-Language header along withother mechanisms described in the HTTP11 specification The following methods are provided in theServletRequest interface to determine the preferred locale of the sender
bull getLocale
bull getLocales
The getLocale method will return the preferred locale for which the client wants to accept content Seesection 144 of RFC 7231 (HTTP11) for more information about how the Accept-Language header mustbe interpreted to determine the preferred language of the client
The getLocales method will return an Enumeration of Locale objects indicating in decreasing orderstarting with the preferred locale the locales that are acceptable to the client
If no preferred locale is specified by the client the locale returned by the getLocale method must be thedefault locale for the servlet container and the getLocales method must contain an enumeration of asingle Locale element of the default locale
312 Request Data EncodingCurrently many browsers do not send a char encoding qualifier with the Content-Type header leavingopen the determination of the character encoding for reading HTTP requests In the absence of a charencoding qualifier if the Content-Type is applicationx-www-form-urlencoded the default encoding thecontainer uses to create the request reader and parse POST data must be US-ASCII Any nn encodedvalues must be decoded to ISO-8859-1 For any other Content-Type if none has been specified by theclient request web application or container vendor specific configuration (for all web applications inthe container) the default encoding of a request the container uses to create the request reader andparse POST data must be ISO-8859-1 However in order to indicate to the developer the absence of achar encoding qualifier the container must return null from the getCharacterEncoding() method
If the client hasnrsquot set character encoding and the request data is encoded with a different encodingthan the default as described above breakage can occur To remedy this situationsetRequestCharacterEncoding(String enc) is available on ServletContext the ltrequest-character-
encodinggt element is available in the webxml and setCharacterEncoding(String enc) is available on theServletRequest interface Developers can override the character encoding supplied by the container bycalling this method It must be called prior to parsing any post data or reading any input from therequest Calling this method once data has been read will not affect the encoding
311 Internationalization
34 Jakarta Servlet Specification Final
313 Lifetime of the Request ObjectEach request object is valid only within the scope of a servletrsquos service method or within the scope of afilterrsquos doFilter method unless the asynchronous processing is enabled for the component and thestartAsync method is invoked on the request object In the case where asynchronous processingoccurs the request object remains valid until complete is invoked on the AsyncContext Containerscommonly recycle request objects in order to avoid the performance overhead of request objectcreation The developer must be aware that maintaining references to request objects for whichstartAsync has not been called outside the scope described above is not recommended as it may haveindeterminate results
In case of upgrade the above is still true
[3] The Java Programming Language Specification is available at httpdocsoraclecomjavasespecs
313 Lifetime of the Request Object
Final Jakarta Servlet Specification 35
313 Lifetime of the Request Object
36 Jakarta Servlet Specification Final
Chapter 4 Servlet Context
41 Introduction to the ServletContext InterfaceThe ServletContext interface defines a servletrsquos view of the web application within which the servlet isrunning The Container Provider is responsible for providing an implementation of the ServletContextinterface in the servlet container Using the ServletContext object a servlet can log events obtain URLreferences to resources and set and store attributes that other servlets in the context can access
A ServletContext is rooted at a known path within a web server For example a servlet context couldbe located at httpexamplecomcatalog All requests that begin with the catalog request path knownas the context path are routed to the web application associated with the ServletContext
42 Scope of a ServletContext InterfaceThere is one instance object of the ServletContext interface associated with each web applicationdeployed into a container In cases where the container is distributed over many virtual machines aweb application will have an instance of the ServletContext for each JVM
43 Initialization ParametersThe following methods of the ServletContext interface allow the servlet access to context initializationparameters associated with a web application as specified by the Application Developer in thedeployment descriptor
bull getInitParameter
bull getInitParameterNames
Initialization parameters are used by an Application Developer to convey setup information Typicalexamples are a webmasterrsquos e-mail address or the name of a system that holds critical data
44 Configuration MethodsThe following methods are provided on the ServletContext interface to enable programmatic definitionof servlets filters and the url pattern(s) that they map to These methods can only be called during theinitialization of the application either from the contexInitialized method of a ServletContextListenerimplementation or from the onStartup method of a ServletContainerInitializer implementation Inaddition to adding servlets and filters one can also look up an instance of a Registration objectcorresponding to a servlet or filter or a map of all the Registration objects for the servlets or filters If aServletContext is passed to the ServletContextListenerrsquos contextInitialized method where theServletContextListener was neither declared in webxml or web-fragmentxml nor annotated withWebListener then an UnsupportedOperationException MUST be thrown for all the methods defined inServletContext for programmatic configuration of servlets filters and listeners
41 Introduction to the ServletContext Interface
Final Jakarta Servlet Specification 37
441 Programmatically Adding and Configuring Servlets
The ability to programmatically add a servlet to a context is useful for framework developers Forexample a framework could declare a controller servlet using this method The return value of thismethod is a ServletRegistration or a ServletRegistrationDynamic object which further allows thesetup of the other parameters of the servlet like init-param url-mappings etc There are threeoverloaded versions of the method as described below
4411 addServlet(String servletName String className)
This method allows the application to declare a servlet programmatically It adds a servlet with thegiven name and class name to the servlet context
4412 addServlet(String servletName Servlet servlet)
This method allows the application to declare a servlet programmatically It adds a servlet with thegiven name and servlet instance to the servlet context
4413 addServlet(String servletName Class lt extends Servletgt servletClass)
This method allows the application to declare a servlet programmatically It adds a servlet with thegiven name and an instance of the servlet class to the servlet context
4414 addJspFile(String servletName String jspfile)
This method allows the application to declare a jsp programmatically It adds the jsp with the givenname and an instance of the servlet class corresponding to the jsp file to the servlet context
4415 ltT extends Servletgt T createServlet(ClassltTgt clazz)
This method instantiates the given Servlet class The method must support all the annotationsapplicable to servlets except WebServlet The returned Servlet instance may be further customizedbefore it is registered with the ServletContext via a call to addServlet(String Servlet) as definedabove The given Servlet class must define a zero argument constructor which is used to instantiate it
4416 ServletRegistration getServletRegistration(String servletName)
This method returns the ServletRegistration corresponding to the servlet with the given name or null ifno ServletRegistration exists under that name An UnsupportedOperationException is thrown if theServletContext was passed to the contextInitialized method of a ServletContextListener that wasneither declared in the webxml or web-fragmentxml nor annotated withjakartaservletannotationWebListener
4417 MapltString extends ServletRegistrationgt getServletRegistrations()
This method returns a map of ServletRegistration objects keyed by name corresponding to all servletsregistered with the ServletContext If there are no servlets registered with the ServletContext an empty
44 Configuration Methods
38 Jakarta Servlet Specification Final
map is returned The returned Map includes the ServletRegistration objects corresponding to alldeclared and annotated servlets as well as the ServletRegistration objects corresponding to allservlets that have been added via one of the addServlet and addJspFile methods Any changes to thereturned Map MUST not affect the ServletContext An UnsupportedOperationException is thrown if theServletContext was passed to the contextInitialized method of a ServletContextListener that wasneither declared in the webxml or web-fragmentxml nor annotated withjakartaservletannotationWebListener
442 Programmatically Adding and Configuring Filters
4421 addFilter(String filterName String className)
This method allows the application to declare a filter programmatically It adds a filter with the givenname and class name to the web application
4422 addFilter(String filterName Filter filter)
This method allows the application to declare a filter programmatically It adds a filter with the givenname and filter instance to the web application
4423 addFilter(String filterName Class lt extends Filtergt filterClass)
This method allows the application to declare a filter programmatically It adds a filter with the givenname and an instance of the filter class to the web application
4424 ltT extends Filtergt T createFilter(ClassltTgt clazz)
This method instantiates the given Filter class The method must support all the annotationsapplicable to filters The returned Filter instance may be further customized before it is registeredwith the ServletContext via a call to addFilter(String Filter) as defined above The given Filter classmust define a zero argument constructor which is used to instantiate it
4425 FilterRegistration getFilterRegistration(String filterName)
This method returns the FilterRegistration corresponding to the filter with the given name or null ifno FilterRegistration exists under that name An UnsupportedOperationException is thrown if theServletContext was passed to the contextInitialized method of a ServletContextListener that wasneither declared in the webxml or web-fragmentxml nor annotated withjakartaservletannotationWebListener
4426 MapltString extends FilterRegistrationgt getFilterRegistrations()
This method returns a map of FilterRegistration objects keyed by name corresponding to all filtersregistered with the ServletContext If there are no filters registered with the ServletContext an emptyMap is returned The returned Map includes the FilterRegistration objects corresponding to all declaredand annotated filters as well as the FilterRegistration objects corresponding to all filters that havebeen added via one of the addFilter methods Any changes to the returned Map MUST not affect the
44 Configuration Methods
Final Jakarta Servlet Specification 39
ServletContext An UnsupportedOperationException is thrown if the ServletContext was passed to thecontextInitialized method of a ServletContextListener that was neither declared in the webxml or web-fragmentxml nor annotated with jakartaservletannotationWebListener
443 Programmatically Adding and Configuring Listeners
4431 void addListener(String className)
Add the listener with the given class name to the ServletContext The class with the given name will beloaded using the classloader associated with the application represented by the ServletContext andMUST implement one or more of the following interfaces
bull jakartaservletServletContextAttributeListener
bull jakartaservletServletRequestListener
bull jakartaservletServletRequestAttributeListener
bull jakartaservlethttpHttpSessionListener
bull jakartaservlethttpHttpSessionAttributeListener
bull jakartaservlethttpHttpSessionIdListener
If the ServletContext was passed to the ServletContainerInitializerrsquos onStartup method then the classwith the given name MAY also implement jakartaservletServletContextListener in addition to theinterfaces listed above As part of this method call the container MUST load the class with the specifiedclass name to ensure that it implements one of the required interfaces If the class with the given nameimplements a listener interface whose invocation order corresponds to the declaration order that is ifit implements jakartaservletServletRequestListener jakartaservletServletContextListener orjakartaservlethttpHttpSessionListener then the new listener will be added to the end of theordered list of listeners of that interface
4432 ltT extends EventListenergt void addListener(T t)
Add the given listener to the ServletContext The given listener MUST be an instance of one or more ofthe following interfaces
bull jakartaservletServletContextAttributeListener
bull jakartaservletServletRequestListener
bull jakartaservletServletRequestAttributeListener
bull jakartaservlethttpHttpSessionListener
bull jakartaservlethttpHttpSessionAttributeListener
bull jakartaservlethttpHttpSessionIdListener
If the ServletContext was passed to the ServletContainerInitializerrsquos onStartup method then the givenlistener MAY also be an instance of jakartaservletServletContextListener in addition to the
44 Configuration Methods
40 Jakarta Servlet Specification Final
interfaces listed above If the given listener is an instance of a listener interface whose invocationorder corresponds to the declaration order that is if it implementsjakartaservletServletRequestListener jakartaservletServletContextListener orjakartaservlethttpHttpSessionListener then the new listener will be added to the end of theordered list of listeners of that interface
4433 void addListener(Class lt extends EventListenergt listenerClass)
Add the listener of the given class type to the ServletContext The given listener class MUST implementone or more of the following interfaces
bull jakartaservletServletContextAttributeListener
bull jakartaservletServletRequestListener
bull jakartaservletServletRequestAttributeListener
bull jakartaservlethttpHttpSessionListener
bull jakartaservlethttpHttpSessionAttributeListener
bull jakartaservlethttpHttpSessionIdListener
If the ServletContext was passed to the ServletContainerInitializerrsquos onStartup method then the givenlistener class MAY also implement jakartaservletServletContextListener in addition to the interfaceslisted above If the given listener class implements a listener interface whose invocation ordercorresponds to the declaration order that is if it implements jakartaservletServletRequestListenerjakartaservletServletContextListener or jakartaservlethttpHttpSessionListener then the newlistener will be added to the end of the ordered list of listeners of that interface
4434 ltT extends EventListenergt void createListener(ClassltTgt clazz)
This method instantiates the given EventListener class The specified EventListener class MUSTimplement at least one of the following interfaces
bull jakartaservletServletContextAttributeListener
bull jakartaservletServletRequestListener
bull jakartaservletServletRequestAttributeListener
bull jakartaservlethttpHttpSessionListener
bull jakartaservlethttpHttpSessionAttributeListener
bull jakartaservlethttpHttpSessionIdListener
This method MUST support all annotations applicable to the above listener interfaces as defined by thisspecification The returned EventListener instance may be further customized before it is registeredwith the ServletContext via a call to addListener(T t) The given EventListener class MUST define a zeroargument constructor which is used to instantiate it
44 Configuration Methods
Final Jakarta Servlet Specification 41
4435 Annotation processing requirements for programmatically added Servlets Filters andListeners
When using the programmatic API to add a servlet or create a servlet apart from the addServlet thattakes an instance the following annotations must be introspected in the class in question and themetadata defined in it MUST be used unless it is overridden by calls to the API in theServletRegistrationDynamic ServletRegistration
ServletSecurity RunAs DeclareRoles MultipartConfig
For filters and listeners no annotations need to be introspected
Resource injection on all components (servlets filters and listeners) added programmatically orcreated programmatically other than the ones added via the methods that takes an instance will onlybe supported when the component is a CDI Managed Bean For details please refer to Section 15516ldquoContexts and Dependency Injection for Jakarta EE Platform Requirementsrdquo
444 Programmatically Configuring Session Time Out
The following methods of the ServletContext interface allow the web application to access andconfigure the default session timeout interval for all sessions created in the given web application Thespecified timeout in setSessionTimeout is in minutes If the timeout is 0 or less the container ensuresthe default behavior of sessions is never to time out
bull getSessionTimeout()
bull setSessionTimeout(int timeout)
445 Programmatically Configuring Character Encoding
The following methods of the ServletContext interface allow the web application to access andconfigure request and response character encoding
bull getRequestCharacterEncoding()
bull setRequestCharacterEncoding(String encoding)
bull getResponseCharacterEncoding()
bull setResponseCharacterEncoding(String encoding)
If no request character encoding is specified in deployment descriptor or container specificconfiguration (for all web applications in the container) getRequestCharacterEncoding() returns null Ifno response character encoding is specified in deployment descriptor or container specificconfiguration (for all web applications in the container) getResponseCharacterEncoding() returns null
44 Configuration Methods
42 Jakarta Servlet Specification Final
45 Context AttributesA servlet can bind an object attribute into the context by name Any attribute bound into a context isavailable to any other servlet that is part of the same web application The following methods ofServletContext interface allow access to this functionality
bull setAttribute
bull getAttribute
bull getAttributeNames
bull removeAttribute
451 Context Attributes in a Distributed Container
Context attributes are local to the JVM in which they were created This prevents ServletContextattributes from being a shared memory store in a distributed container When information needs to beshared between servlets running in a distributed environment the information should be placed into asession (See Chapter 7 Sessions) stored in a database or set in an Jakarta Enterprise Beanscomponent
46 ResourcesThe ServletContext interface provides direct access only to the hierarchy of static content documentsthat are part of the web application including HTML GIF and JPEG files via the following methods ofthe ServletContext interface
bull getResource
bull getResourceAsStream
The getResource and getResourceAsStream methods take a String with a leading as an argument thatgives the path of the resource relative to the root of the context or relative to the META-INFresourcesdirectory of a JAR file inside the web applicationrsquos WEB-INFlib directory If there is a WEB-INF entryinside the META-INFresources entry of a JAR file in WEB-INFlib then it and all child entries areavailable only as static resources No classes or jars will be placed on the context classpath from such aWEB-INF entry and no servlet specific descriptors will be processed These methods will first search theroot of the web application context for the requested resource before looking at any of the JAR files inthe WEB-INFlib directory The order in which the JAR files in the WEB-INFlib directory are scanned isundefined This hierarchy of documents may exist in the serverrsquos file system in a web applicationarchive file on a remote server or at some other location
These methods are not used to obtain dynamic content For example in a container supporting theJakarta Server Pages specification [4] a method call of the form getResource(indexjsp) would returnthe JSP source code and not the processed output See Chapter 9 Dispatching Requests for moreinformation about accessing dynamic content
45 Context Attributes
Final Jakarta Servlet Specification 43
The full listing of the resources in the web application can be accessed using thegetResourcePaths(String path) method The full details on the semantics of this method may be foundin the API documentation in this specification
47 Multiple Hosts and Servlet ContextsWeb servers may support multiple logical hosts sharing one IP address on a server This capability issometimes referred to as virtual hosting In this case each logical host must have its own servletcontext or set of servlet contexts Servlet contexts can not be shared across virtual hosts
The getVirtualServerName method of ServletContext interface allows access to the configuration nameof the logical host on which the ServletContext is deployed Servlet containers may support multiplelogical hosts This method must return the same name for all the servlet contexts deployed on a logicalhost and the name returned by this method must be distinct stable per logical host and suitable foruse in associating server configuration information with the logical host
48 Reloading ConsiderationsAlthough a Container Provider implementation of a class reloading scheme for ease of development isnot required any such implementation must ensure that all servlets and classes that they may use [5]are loaded in the scope of a single class loader This requirement is needed to guarantee that theapplication will behave as expected by the Application Developer As a development aid the fullsemantics of notification to session binding listeners should be supported by containers for use in themonitoring of session termination upon class reloading
Previous generations of containers created new class loaders to load a servlet distinct from classloaders used to load other servlets or classes used in the servlet context This could cause objectreferences within a servlet context to point at unexpected classes or objects and cause unexpectedbehavior The requirement is needed to prevent problems caused by demand generation of new classloaders
481 Temporary Working Directories
A temporary storage directory is required for each servlet context Servlet containers must provide aprivate temporary directory for each servlet context and make it available via thejakartaservletcontexttempdir context attribute The objects associated with the attribute must be oftype javaioFile
The requirement recognizes a common convenience provided in many servlet engineimplementations The container is not required to maintain the contents of the temporary directorywhen the servlet container restarts but is required to ensure that the contents of the temporarydirectory of one servlet context is not visible to the servlet contexts of other web applications runningon the servlet container
[4] The Jakarta Server Pages specification can be found at httpsjakartaeespecificationspages
47 Multiple Hosts and Servlet Contexts
44 Jakarta Servlet Specification Final
[5] An exception is system classes that the servlet may use in a different class loader
48 Reloading Considerations
Final Jakarta Servlet Specification 45
48 Reloading Considerations
46 Jakarta Servlet Specification Final
Chapter 5 The ResponseThe response object encapsulates all 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 orthe message body of the response
51 BufferingA servlet container is allowed but not required to buffer output going to the client for efficiencypurposes Typically servers that do buffering make it the default but allow servlets to specify bufferingparameters
The following methods in the ServletResponse interface allow a servlet to access and set bufferinginformation
bull getBufferSize
bull setBufferSize
bull isCommitted
bull reset
bull resetBuffer
bull flushBuffer
These methods are provided on the ServletResponse interface to allow buffering operations to beperformed 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 beingused this method must return the int value of 0 (zero)
The servlet can request a preferred buffer size by using the setBufferSize method The buffer assignedis not required to be the size requested by the servlet but must be at least as large as the sizerequested This allows the container to reuse a set of fixed size buffers providing a larger buffer thanrequested if appropriate The method must be called before any content is written using aServletOutputStream or Writer If any content has been written or the response object has beencommitted this method must throw an IllegalStateException
The isCommitted method returns a boolean value indicating whether any response bytes have beenreturned to the client The flushBuffer method forces content in the buffer to be written to the client
The reset method clears data in the buffer when the response is not committed Headers status codesand the state of calling getWriter or getOutputStream set by the servlet prior to the reset call must becleared as well The resetBuffer method clears content in the buffer if the response is not committedwithout clearing the headers and status code
If the response is committed and the reset or resetBuffer method is called an IllegalStateException
51 Buffering
Final Jakarta Servlet Specification 47
must be thrown The response and its associated buffer will be unchanged
When using a buffer the container must immediately flush the contents of a filled buffer to the clientIf this is the first data that is sent to the client the response is considered to be committed
52 HeadersA servlet can set headers of an HTTP response via the following methods of the HttpServletResponseinterface
bull setHeader
bull addHeader
The setHeader method sets a header with a given name and value A previous header is replaced by thenew header Where a set of header values exist for the name the values are cleared and replaced withthe new value
The addHeader method adds a header value to the set with a given name If there are no headersalready associated with the name a new set is created
Headers may contain data that represents an int or a Date object The following convenience methodsof the HttpServletResponse interface allow a servlet to set a header using the correct formatting for theappropriate data type
bull setIntHeader
bull setDateHeader
bull addIntHeader
bull addDateHeader
To be successfully transmitted back to the client headers (other than those in a trailer) must be setbefore the response is committed Headers (other than those in a trailer) set after the response iscommitted will be ignored by the servlet container If an HTTP trailer as specified in RFC 7230 is to besent in the response the fields must be provided using the setTrailerFields() method onHttpServletResponse This method must have been called before the last chunk in the chunked responsehas been written
Servlet programmers are responsible for ensuring that the Content-Type header is appropriately set inthe response object for the content the servlet is generating The HTTP11 specification does notrequire that this header be set in an HTTP response Servlet containers must not set a default contenttype when the servlet programmer does not set the type
It is recommended that containers use the X-Powered-By HTTP header to publish its implementationinformation The field value should consist of one or more implementation types such as Servlet50Optionally the supplementary information of the container and the underlying Java platform can beadded after the implementation type within parentheses The container should be configurable to
52 Headers
48 Jakarta Servlet Specification Final
suppress this header
Herersquos the examples of this header
X-Powered-By Servlet50
X-Powered-By Servlet50 JSP30 (GlassFish Server 60 JavaOracle Corporation18)
53 HTTP TrailerAn HTTP trailer is a collection of HTTP headers that comes after the response body It is specified inRFC 7230 It is useful in the context of chunked transfer encoding and also in the implementation ofadditional communication protocols Servlet containers provide support for trailers
If trailer headers are ready for reading isTrailerFieldsReady() will return true Then a servlet canread trailer headers of the HTTP request via the getTrailerFields() method of the HttpServletRequestinterface
A servlet can write trailer headers to the response by providing a Supplier to the setTrailerFieldsmethod of the HttpServletResponse interface The Supplier of the trailer headers can be obtained byaccessing the getTrailerFields() method of the HttpServletResponse interface
Please see the javadoc for these two methods for the normative specification
54 Non-Blocking IONon-blocking IO only works with async request processing in servlets and filters (as defined in Section2333 ldquoAsynchronous processingrdquo) and upgrade processing (as defined in Section 2335 ldquoUpgradeProcessingrdquo) Otherwise an IllegalStateException must be thrown whenServletInputStreamsetReadListener or ServletOutputStreamsetWriteListener is invoked To supportnon-blocking writes in the web container in addition to the changes made in the ServletRequest asdescribed in Section 37 ldquoNon-Blocking IOrdquo the following changes have been made to handle responserelated classes interfaces
The WriteListener provides the following callback methods which the container invokes appropriately
WriteListener
void onWritePossible()
When a WriteListener is registered with the ServletOutputStream this method will be invoked by thecontainer the first time when it is possible to write data The container will subsequently invoke theonWritePossible method if and only if the isReady method on ServletOutputStream described belowreturns a value of false and a write operation has subsequently become possible
53 HTTP Trailer
Final Jakarta Servlet Specification 49
void onError(Throwable t)
Invoked when an error occurs processing the response
Along with the WriteListener the following methods have been added to ServletOutputStream class toallow the developer to check with the runtime whether or not it is possible to write the data to be sentto the client
ServletOutputStream
boolean isReady()
This method returns true if a write to the ServletOutputStream will succeed otherwise it will returnfalse If this method returns true a write operation can be performed on the ServletOutputStream Ifno further data can be written to the ServletOutputStream then this method will return false till theunderlying data is flushed at which point the container will invoke the onWritePossible method ofthe WriteListener A subsequent call to this method will return true
void setWriteListener(WriteListener listener)
Associates the WriteListener with this ServletOutputStream for the container to invoke the callbackmethods on the WriteListener when it is possible to write data Registering a WriteListener will startnon-blocking IO It is illegal to switch to the traditional blocking IO at that point The use of IOrelated method calls after this illegal switch to traditional blocking IO produces unspecifiedbehavior
The servlet container must access methods in WriteListener in a thread safe manner
55 Convenience MethodsThe following convenience methods exist in the HttpServletResponse interface
bull sendRedirect
bull sendError
The sendRedirect method will set the appropriate headers and content body to redirect the client to adifferent URL It is legal to call this method with a relative URL path however the underlying containermust translate the relative path to a fully qualified URL for transmission back to the client If a partialURL is given and for whatever reason cannot be converted into a valid URL then this method mustthrow an IllegalArgumentException
The sendError method will set the appropriate headers and content body for an error message toreturn to the client An optional String argument can be provided to the sendError method which canbe used in the content body of the error
These methods will have the side effect of committing the response if it has not already beencommitted and terminating it No further output to the client should be made by the servlet after thesemethods are called If data is written to the response after these methods are called the data isignored
55 Convenience Methods
50 Jakarta Servlet Specification Final
If data has been written to the response buffer but not returned to the client (ie the response is notcommitted) the data in the response buffer must be cleared and replaced with the data set by thesemethods If the response is committed these methods must throw an IllegalStateException
56 InternationalizationServlets should set the locale and the character encoding of a response The locale is set using theServletResponsesetLocale method The method can be called repeatedly but calls made after theresponse is committed have no effect If the servlet does not set the locale before the page iscommitted the containerrsquos default locale is used to determine the responsersquos locale but nospecification is made for the communication with a client such as Content-Language header in the caseof HTTP
ltlocale-encoding-mapping-listgt ltlocale-encoding-mappinggt ltlocalegtjaltlocalegt ltencodinggtShift_JISltencodinggt ltlocale-encoding-mappinggtltlocale-encoding-mapping-listgt
The ltresponse-character-encodinggt element can be used to explicitly set the default encoding for allresponses in a given web application
ltresponse-character-encodinggtUTF-8ltresponse-character-encodinggt
If neither element exists or does not provide a mapping setLocale uses a container dependentmapping The setCharacterEncoding setContentType and setLocale methods can be called repeatedly tochange the character encoding Calls made after the servlet responsersquos getWriter method has beencalled or after the response is committed have no effect on the character encoding Calls tosetContentType set the character encoding only if the given content type string provides a value for thecharset attribute Calls to setLocale set the character encoding only if neither setCharacterEncoding norsetContentType has set the character encoding before
If the servlet does not specify a character encoding before the getWriter method of the ServletResponseinterface is called or the response is committed the default ISO-8859-1 is used
Containers must communicate the locale and the character encoding used for the servlet responsersquoswriter to the client if the protocol in use provides a way for doing so In the case of HTTP the locale iscommunicated via the Content-Language header the character encoding as part of the Content-Typeheader for text media types Note that the character encoding cannot be communicated via HTTPheaders if the servlet does not specify a content type however it is still used to encode text written viathe servlet responsersquos writer
56 Internationalization
Final Jakarta Servlet Specification 51
57 Closure of Response ObjectWhen a response is closed the container must immediately flush all remaining content in the responsebuffer to the client The following events indicate that the servlet has satisfied the request and that theresponse object is to be closed
bull The termination of the service method of the servlet
bull The amount of content specified in the setContentLength or setContentLengthLong method of theresponse has been greater than zero and has been written to the response
bull The sendError method is called
bull The sendRedirect method is called
bull The complete method on AsyncContext is called
58 Lifetime of the Response ObjectEach response object is valid only within the scope of a servletrsquos service method or within the scope ofa filterrsquos doFilter method unless the associated request object has asynchronous processing enabledfor the component If asynchronous processing on the associated request is started then the responseobject remains valid until complete method on AsyncContext is called Containers commonly recycleresponse objects in order to avoid the performance overhead of response object creation Thedeveloper must be aware that maintaining references to response objects for which startAsync on thecorresponding request has not been called outside the scope described above may lead to non-deterministic behavior
57 Closure of Response Object
52 Jakarta Servlet Specification Final
Chapter 6 FilteringFilters are Java components that allow on the fly transformations of payload and header informationin both the request into a resource and the response from a resource
The Jakarta Servlet API provides a lightweight framework for filtering active and static content Itdescribes how filters are configured in a web application and conventions and semantics for theirimplementation
API documentation for servlet filters is provided online The configuration syntax for filters is given bythe deployment descriptor schema described in Chapter 14 Deployment Descriptor The reader shoulduse these sources as references when reading this chapter
61 What is a FilterA filter is a reusable piece of code that can transform the content of HTTP requests responses andheader information Filters do not generally create a response or respond to a request as servlets dorather they modify or adapt the requests for a resource and modify or adapt responses from aresource
Filters can act on dynamic or static content For the purposes of this chapter dynamic and staticcontent are referred to as web resources
Among the types of functionality available to the developer needing to use filters are the following
bull The accessing of a resource before a request to it is invoked
bull The processing of the request for a resource before it is invoked
bull The modification of request headers and data by wrapping the request in customized versions ofthe request object
bull The modification of response headers and response data by providing customized versions of theresponse object
bull The interception of an invocation of a resource after its call
bull Actions on a servlet on groups of servlets or static content by zero one or more filters in aspecifiable order
611 Examples of Filtering Components
bull Authentication filters
bull Logging and auditing filters
bull Image conversion filters
bull Data compression filters
61 What is a Filter
Final Jakarta Servlet Specification 53
bull Encryption filters
bull Tokenizing filters
bull Filters that trigger resource access events
bull XSLT filters that transform XML content
bull MIME-type chain filters
bull Caching filters
62 Main ConceptsThe main concepts of this filtering model are described in this section
The application developer creates a filter by implementing the jakartaservletFilter interface andproviding a public constructor taking no arguments The class is packaged in the web archive alongwith the static content and servlets that make up the web application A filter is declared using theltfiltergt element in the deployment descriptor A filter or collection of filters can be configured forinvocation by defining ltfilter-mappinggt elements in the deployment descriptor This is done bymapping filters to a particular servlet by the servletrsquos logical name or mapping to a group of servletsand static content resources by mapping a filter to a URL pattern
621 Filter Lifecycle
After deployment of the web application and before a request causes the container to access a webresource the container must locate the list of filters that must be applied to the web resource asdescribed below The container must ensure that it has instantiated a filter of the appropriate class foreach filter in the list and called its init(FilterConfig config) method The filter may throw anexception to indicate that it cannot function properly If the exception is of type UnavailableExceptionthe container may examine the isPermanent attribute of the exception and may choose to retry thefilter at some later time
Only one instance per ltfiltergt declaration in the deployment descriptor is instantiated per JVM of thecontainer The container provides the filter config as declared in the filterrsquos deployment descriptor thereference to the ServletContext for the web application and the set of initialization parameters
When the container receives an incoming request it takes the first filter instance in the list and calls itsdoFilter method passing in the ServletRequest and ServletResponse and a reference to the FilterChainobject it will use
The doFilter method of a filter will typically be implemented following this or some subset of thefollowing pattern
1 The method examines the requestrsquos headers
2 The method may wrap the request object with a customized implementation of ServletRequest orHttpServletRequest in order to modify request headers or data
62 Main Concepts
54 Jakarta Servlet Specification Final
3 The method may wrap the response object passed in to its doFilter method with a customizedimplementation of ServletResponse or HttpServletResponse to modify response headers or data
4 The filter may invoke the next entity in the filter chain The next entity may be another filter or ifthe filter making the invocation is the last filter configured in the deployment descriptor for thischain the next entity is the target web resource The invocation of the next entity is effected bycalling the doFilter method on the FilterChain object and passing in the request and response withwhich it was called or passing in wrapped versions it may have created
The filter chainrsquos implementation of the doFilter method provided by the container must locatethe next entity in the filter chain and invoke its doFilter method passing in the appropriaterequest and response objects
Alternatively the filter chain can block the request by not making the call to invoke the next entityleaving the filter responsible for filling out the response object
The service method is required to run in the same thread as all filters that apply to the servlet
5 After invocation of the next filter in the chain the filter may examine response headers
6 Alternatively the filter may have thrown an exception to indicate an error in processing If thefilter throws an UnavailableException during its doFilter processing the container must notattempt continued processing down the filter chain It may choose to retry the whole chain at alater time if the exception is not marked permanent
7 When the last filter in the chain has been invoked the next entity accessed is the target servlet orresource at the end of the chain
8 Before a filter instance can be removed from service by the container the container must first callthe destroy method on the filter to enable the filter to release any resources and perform othercleanup operations
622 Wrapping Requests and Responses
Central to the notion of filtering is the concept of wrapping a request or response in order that it canoverride behavior to perform a filtering task In this model the developer not only has the ability tooverride existing methods on the request and response objects but to provide new API suited to aparticular filtering task to a filter or target web resource down the chain For example the developermay wish to extend the response object with higher level output objects than the output stream or thewriter such as API that allows DOM objects to be written back to the client
In order to support this style of filter the container must support the following requirement When afilter invokes the doFilter method on the containerrsquos filter chain implementation the container mustensure that the request and response object that it passes to the next entity in the filter chain or to thetarget web resource if the filter was the last in the chain is the same object that was passed into thedoFilter method by the calling filter
The same requirement of wrapper object identity applies to the calls from a servlet or a filter to
62 Main Concepts
Final Jakarta Servlet Specification 55
RequestDispatcherforward or RequestDispatcherinclude when the caller wraps the request orresponse objects In this case the request and response objects seen by the called servlet must be thesame wrapper objects that were passed in by the calling servlet or filter
623 Filter Environment
A set of initialization parameters can be associated with a filter using the ltinit-paramgt element in thedeployment descriptor The names and values of these parameters are available to the filter at runtimevia the getInitParameter and getInitParameterNames methods on the filterrsquos FilterConfig objectAdditionally the FilterConfig affords access to the ServletContext of the web application for theloading of resources for logging functionality and for storage of state in the ServletContextrsquos attributelist A filter and the target servlet or resource at the end of the filter chain must execute in the sameinvocation thread
624 Configuration of Filters in a Web Application
A filter is defined either via the WebFilter annotation as defined in Section 812 ldquoWebFilterrdquo of thespecification or in the deployment descriptor using the ltfiltergt element In this element theprogrammer declares the following
bull filter-name used to map the filter to a servlet or URL
bull filter-class used by the container to identify the filter type
bull init-param initialization parameters for a filter
Optionally the programmer can specify icons a textual description and a display name for toolmanipulation The container must instantiate exactly one instance of the Java class defining the filterper filter declaration in the deployment descriptor Hence two instances of the same filter class will beinstantiated by the container if the developer makes two filter declarations for the same filter class
Here is an example of a filter declaration
ltfiltergt ltfilter-namegtImage Filterltfilter-namegt ltfilter-classgtcomexampleImageServletltfilter-classgtltfiltergt
Once a filter has been declared in the deployment descriptor the assembler uses the ltfilter-mappinggtelement to define servlets and static resources in the web application to which the filter is to beapplied Filters can be associated with a servlet using the ltservlet-namegt element For example thefollowing code example maps the Image Filter filter to the ImageServlet servlet
62 Main Concepts
56 Jakarta Servlet Specification Final
ltfilter-mappinggt ltfilter-namegtImage Filterltfilter-namegt ltservlet-namegtImageServletltservlet-namegtltfilter-mappinggt
Filters can be associated with groups of servlets and static content using the lturl-patterngt style of filtermapping
ltfilter-mappinggt ltfilter-namegtLogging Filterltfilter-namegt lturl-patterngtlturl-patterngtltfilter-mappinggt
Here the Logging Filter is applied to all the servlets and static content pages in the web applicationbecause every request URI matches the URL pattern
When processing a ltfilter-mappinggt element using the lturl-patterngt style the container mustdetermine whether the lturl-patterngt matches the request URI using the path mapping rules defined inChapter 12 Mapping Requests to Servlets
The order the container uses in building the chain of filters to be applied for a particular request URI isas follows
1 First the lturl-patterngt matching filter mappings in the same order that these elements appear inthe deployment descriptor
2 Next the ltservlet-namegt matching filter mappings in the same order that these elements appear inthe deployment descriptor
If a filter mapping contains both ltservlet-namegt and lturl-patterngt the container must expand thefilter mapping into multiple filter mappings (one for each ltservlet-namegt and lturl-patterngt)preserving the order of the ltservlet-namegt and lturl-patterngt elements For example the followingfilter mapping
ltfilter-mappinggt ltfilter-namegtMultiple Mappings Filterltfilter-namegt lturl-patterngtfoolturl-patterngt ltservlet-namegtServlet1ltservlet-namegt ltservlet-namegtServlet2ltservlet-namegt lturl-patterngtbarlturl-patterngtltfilter-mappinggt
is equivalent to
62 Main Concepts
Final Jakarta Servlet Specification 57
ltfilter-mappinggt ltfilter-namegtMultipe Mappings Filterltfilter-namegt lturl-patterngtfoolturl-patterngtltfilter-mappinggt
ltfilter-mappinggt ltfilter-namegtMultipe Mappings Filterltfilter-namegt ltservlet-namegtServlet1ltservlet-namegtltfilter-mappinggt
ltfilter-mappinggt ltfilter-namegtMultipe Mappings Filterltfilter-namegt ltservlet-namegtServlet2ltservlet-namegtltfilter-mappinggt
ltfilter-mappinggt ltfilter-namegtMultipe Mappings Filterltfilter-namegt lturl-patterngtbarlturl-patterngtltfilter-mappinggt
The requirement about the order of the filter chain means that the container when receiving anincoming request processes the request as follows
bull Identifies the target web resource according to the rules of Section 122 ldquoSpecification ofMappingsrdquo
bull If there are filters matched by servlet name and the web resource has a ltservlet-namegt thecontainer builds the chain of filters matching in the order declared in the deployment descriptorThe last filter in this chain corresponds to the last ltservlet-namegt matching filter and is the filterthat invokes the target web resource
bull If there are filters using lturl-patterngt matching and the lturl-patterngt matches the request URIaccording to the rules of Section 122 ldquoSpecification of Mappingsrdquo the container builds the chain oflturl-patterngt matched filters in the same order as declared in the deployment descriptor The lastfilter in this chain is the last lturl-patterngt matching filter in the deployment descriptor for thisrequest URI The last filter in this chain is the filter that invokes the first filter in the ltservlet-namegtmatching chain or invokes the target web resource if there are none
It is expected that high performance web containers will cache filter chains so that they do not need tocompute them on a per-request basis
625 Filters and the RequestDispatcher
The servlet specification provides the ability to configure filters to be invoked under requestdispatcher forward() and include() calls
By using the ltdispatchergt element in the deployment descriptor the developer can indicate for a filter-
62 Main Concepts
58 Jakarta Servlet Specification Final
mapping whether the filter should be applied to requests when
1 The request comes directly from the client
This is indicated by a ltdispatchergt element with value REQUEST or by the absence of anyltdispatchergt elements
2 The request is being processed under a request dispatcher representing the web componentmatching the lturl-patterngt or ltservlet-namegt using a forward() call
This is indicated by a ltdispatchergt element with value FORWARD
3 The request is being processed under a request dispatcher representing the web componentmatching the lturl-patterngt or ltservlet-namegt using an include() call
This is indicated by a ltdispatchergt element with value INCLUDE
4 The request is being processed with the error page mechanism specified in Section 95 ldquoErrorHandlingrdquo to an error resource matching the lturl-patterngt
This is indicated by a ltdispatchergt element with the value ERROR
5 The request is being processed with the async context dispatch mechanism specified in Section2333 ldquoAsynchronous processingrdquo to a web component using a dispatch call
This is indicated by a ltdispatchergt element with the value ASYNC
6 Or any combination of 1 2 3 4 or 5 above
For example
ltfilter-mappinggt ltfilter-namegtLogging Filterltfilter-namegt lturl-patterngtproductslturl-patterngtltfilter-mappinggt
would result in the Logging Filter being invoked by client requests starting productshellip but notunderneath a request dispatcher call where the request dispatcher has path commencing productshellipThe following code
ltfilter-mappinggt ltfilter-namegtLogging Filterltfilter-namegt ltservlet-namegtProductServletltservlet-namegt ltdispatchergtINCLUDEltdispatchergtltfilter-mappinggt
62 Main Concepts
Final Jakarta Servlet Specification 59
would result in the Logging Filter not being invoked by client requests to the ProductServlet norunderneath a request dispatcher forward() call to the ProductServlet but would be invokedunderneath a request dispatcher include() call where the request dispatcher has a name commencingProductServlet The following code
ltfilter-mappinggt ltfilter-namegtLogging Filterltfilter-namegt lturl-patterngtproductslturl-patterngt ltdispatchergtFORWARDltdispatchergt ltdispatchergtREQUESTltdispatchergtltfilter-mappinggt
would result in the Logging Filter being invoked by client requests starting productshellip andunderneath a request dispatcher forward() call where the request dispatcher has path commencingproductshellip
Finally the following code uses the special servlet name
ltfilter-mappinggt ltfilter-namegtAll Dispatch Filterltfilter-namegt ltservlet-namegtltservlet-namegt ltdispatchergtFORWARDltdispatchergtltfilter-mappinggt
This code would result in the All Dispatch Filter being invoked on request dispatcher forward() callsfor all request dispatchers obtained by name or by path
62 Main Concepts
60 Jakarta Servlet Specification Final
Chapter 7 SessionsThe Hypertext Transfer Protocol (HTTP) is by design a stateless protocol To build effective webapplications it is imperative that requests from a particular client be associated with each other Manystrategies for session tracking have evolved over time but all are difficult or troublesome for theprogrammer to use directly
This specification defines a simple HttpSession interface that allows a servlet container to use any ofseveral approaches to track a userrsquos session without involving the Application Developer in thenuances of any one approach
71 Session Tracking MechanismsThe following sections describe approaches to tracking a userrsquos sessions
711 Cookies
Session tracking through HTTP cookies is the most used session tracking mechanism and is required tobe supported by all servlet containers
The container sends a cookie to the client The client will then return the cookie on each subsequentrequest to the server unambiguously associating the request with a session The standard name of thesession tracking cookie must be JSESSIONID Containers may allow the name of the session trackingcookie to be customized through container specific configuration
All servlet containers MUST provide an ability to configure whether or not the container marks thesession tracking cookie as HttpOnly The established configuration must apply to all contexts for whicha context specific configuration has not been established (see SessionCookieConfig javadoc for moredetails)
If a web application configures a custom name for its session tracking cookies the same custom namewill also be used as the name of the URI parameter if the session id is encoded in the URL (providedthat URL rewriting has been enabled)
712 SSL Sessions
Secure Sockets Layer the encryption technology used in the HTTPS protocol has a built-in mechanismallowing multiple requests from a client to be unambiguously identified as being part of a session Aservlet container can easily use this data to define a session
713 URL Rewriting
URL rewriting is the lowest common denominator of session tracking When a client will not accept acookie URL rewriting may be used by the server as the basis for session tracking URL rewritinginvolves adding data a session ID to the URL path that is interpreted by the container to associate the
71 Session Tracking Mechanisms
Final Jakarta Servlet Specification 61
request with a session
The session ID must be encoded as a path parameter in the URL string The name of the parametermust be jsessionid Here is an example of a URL containing encoded path information
httpwwwexamplecomcatalogindexhtmljsessionid=1234
URL rewriting exposes session identifiers in logs bookmarks referer headers cached HTML and theURL bar URL rewriting should not be used as a session tracking mechanism where cookies or SSLsessions are supported and suitable
714 Session Integrity
Web containers must be able to support the HTTP session while servicing HTTP requests from clientsthat do not support the use of cookies To fulfill this requirement web containers commonly supportthe URL rewriting mechanism
72 Creating a SessionA session is considered ldquonewrdquo when it is only a prospective session and has not been establishedBecause HTTP is a request-response based protocol an HTTP session is considered to be new until aclient ldquojoinsrdquo it A client joins a session when session tracking information has been returned to theserver indicating that a session has been established Until the client joins a session it cannot beassumed that the next request from the client will be recognized as part of a session
The session is considered to be ldquonewrdquo if either of the following is true
bull The client does not yet know about the session
bull The client chooses not to join a session
These conditions define the situation where the servlet container has no mechanism by which toassociate a request with a previous request
An Application Developer must design the application to handle a situation where a client has not cannot or will not join a session
Associated with each session there is a string containing a unique identifier which is referred to asthe session id The value of the session id can be obtained by callingjakartaservlethttpHttpSessiongetId() and can be changed after creation by invokingjakartaservlethttpHttpServletRequestchangeSessionId()
73 Session ScopeHttpSession objects must be scoped at the application (or servlet context) level The underlying
72 Creating a Session
62 Jakarta Servlet Specification Final
mechanism such as the cookie used to establish the session can be the same for different contexts butthe object referenced including the attributes in that object must never be shared between contextsby the container
To illustrate this requirement with an example if a servlet uses the RequestDispatcher to call a servletin another web application any sessions created for and visible to the servlet being called must bedifferent from those visible to the calling servlet
Additionally sessions of a context must be resumable by requests into that context regardless ofwhether their associated context was being accessed directly or as the target of a request dispatch atthe time the sessions were created
74 Binding Attributes into a SessionA servlet can bind an object attribute into an HttpSession implementation by name Any object boundinto a session is available to any other servlet that belongs to the same ServletContext and handles arequest identified as being a part of the same session
Some objects may require notification when they are placed into or removed from a session Thisinformation can be obtained by having the object implement the HttpSessionBindingListener interfaceThis interface defines the following methods that will signal an object being bound into or beingunbound from a session
bull valueBound
bull valueUnbound
The valueBound method must be called before the object is made available via the getAttribute methodof the HttpSession interface The valueUnbound method must be called after the object is no longeravailable via the getAttribute method of the HttpSession interface
75 Session TimeoutsIn the HTTP protocol there is no explicit termination signal when a client is no longer active Thismeans that the only mechanism that can be used to indicate when a client is no longer active is a timeout period
The default time out period for sessions is defined by the servlet container and can be obtained via thegetSessionTimeout method of the ServletContext interface or the getMaxInactiveInterval method of theHttpSession interface This time out can be changed by the Application Developer using thesetSessionTimeout method of the ServletContext interface or the setMaxInactiveInterval method of theHttpSession interface The time out periods used by session timeout methods are defined in minutesThe time out periods used by max active interval methods are defined in seconds See the javadoc forsetSessionTimeout for additional normative requirements By definition if the time out period for asession is set to 0 or lesser value the session will never expire The session invalidation will not takeeffect until all servlets using that session have exited the service method Once the session invalidation
74 Binding Attributes into a Session
Final Jakarta Servlet Specification 63
is initiated a new request must not be able to see that session
76 Last Accessed TimesThe getLastAccessedTime method of the HttpSession interface allows a servlet to determine the last timethe session was accessed before the current request The session is considered to be accessed when arequest that is part of the session is first handled by the servlet container
77 Important Session Semantics
771 Threading Issues
Multiple servlets executing request threads may have active access to the same session object at thesame time The container must ensure that manipulation of internal data structures representing thesession attributes is performed in a thread safe manner The Application Developer has theresponsibility for thread safe access to the attribute objects themselves This will protect the attributecollection inside the HttpSession object from concurrent access eliminating the opportunity for anapplication to cause that collection to become corrupted Unless explicitly stated elsewhere in thespecification objects vended from the request or response must be assumed to be non thread safe Thisincludes but is not limited to the PrintWriter returned from ServletResponsegetWriter() and theOutputStream returned from ServletResponsegetOutputStream()
772 Distributed Environments
Within an application marked as distributable all requests that are part of a session must be handledby one JVM at a time The container must be able to handle all objects placed into instances of theHttpSession class using the setAttribute or putValue methods appropriately The following restrictionsare imposed to meet these conditions
bull The container must accept objects that implement the Serializable interface
bull The container may choose to support storage of other designated objects in the HttpSession such asreferences to Jakarta Enterprise Beans components and transactions
bull Migration of sessions will be handled by container-specific facilities
The distributed servlet container must throw an IllegalArgumentException for objects where thecontainer cannot support the mechanism necessary for migration of the session storing them
The distributed servlet container must support the mechanism necessary for migrating objects thatimplement Serializable
These restrictions mean that the Application Developer is ensured that there are no additionalconcurrency issues beyond those encountered in a non-distributed container
The Container Provider can ensure scalability and quality of service features like load-balancing and
76 Last Accessed Times
64 Jakarta Servlet Specification Final
failover by having the ability to move a session object and its contents from any active node of thedistributed system to a different node of the system
If distributed containers persist or migrate sessions to provide quality of service features they are notrestricted to using the native JVM Serialization mechanism for serializing HttpSessions and theirattributes Developers are not guaranteed that containers will call readObject and writeObject methodson session attributes if they implement them but are guaranteed that the Serializable closure of theirattributes will be preserved
Containers must notify any session attributes implementing the HttpSessionActivationListener duringmigration of a session They must notify listeners of passivation prior to serialization of a session andof activation after deserialization of a session
Application Developers writing distributed applications should be aware that since the container mayrun in more than one Java virtual machine the developer cannot depend on static variables for storingan application state They should store such states using an enterprise bean or a database
773 Client Semantics
Due to the fact that cookies or SSL certificates are typically controlled by the web browser process andare not associated with any particular window of the browser requests from all windows of a clientapplication to a servlet container might be part of the same session For maximum portability theApplication Developer should always assume that all windows of a client are participating in the samesession
77 Important Session Semantics
Final Jakarta Servlet Specification 65
77 Important Session Semantics
66 Jakarta Servlet Specification Final
Chapter 8 Annotations and PluggabilityThis chapter describes the use of annotations and other enhancements to enable pluggability offrameworks and libraries for use within a web application
81 Annotations and PluggabilityIn a web application classes using annotations will have their annotations processed only if they arelocated in the WEB-INFclasses directory or if they are packaged in a jar file located in WEB-INFlibwithin the application
The web application deployment descriptor contains a metadata-complete attribute on the web-appelement This attribute defines whether this deployment descriptor and associated web fragments ifany are complete or whether the class files available to this module and packaged with thisapplication should be examined for annotations that specify deployment information Deploymentinformation in this sense refers to any information that could have been specified by the deploymentdescriptor or fragments but instead is specified as annotations on classes
If the value of the metadata-complete attribute is specified as true the deployment tool must ignore anyannotations that specify such deployment information in the class files packaged in the webapplication Please see Section 823 ldquoAssembling the Descriptor from webxml web-fragmentxml andAnnotationsrdquo Section 84 ldquoProcessing Annotations and Fragmentsrdquo and Section 1551 ldquoHandling ofmetadata-completerdquo for additional details on the handling of metadata-complete
If the metadata-complete attribute is not specified or its value is false the deployment tool mustexamine the class files of the application for such annotations Note that a true value for metadata-complete does not preempt the processing of all annotations only those listed below
Annotations that do not have equivalents in the deployment XSD includejakartaservletannotationHandlesTypes and all of the CDI-related annotations These annotationsmust be processed during annotation scanning regardless of the value of metadata-complete
When Jakarta Enterprise Beans are packaged in a war file and the war file contains an ejb-jarxmlfile the metadata-complete attribute of the ejb-jarxml file determines the processing of the annotationsfor enterprise beans If there is no ejb-jarxml file and the webxml specifies the metadata-completeattribute as true these annotations are processed as though there were an ejb-jarxml file whosemetadata-complete attribute was specified as true See the Jakarta Enterprise Beans specification forrequirements pertaining to annotations for Jakarta Enterprise Beans
The following are the annotations in jakartaservlet All of these have corresponding deploymentdescriptor metadata covered by the web xsd
From jakartaservletannotation
bull HttpConstraint
81 Annotations and Pluggability
Final Jakarta Servlet Specification 67
bull HttpMethodConstraint
bull MultipartConfig
bull ServletSecurity
bull WebFilter
bull WebInitParam
bull WebListener
bull WebServlet
The following annotations from related packages are also covered by the webxml and associatedfragments
From jakartaannotation
bull PostConstruct
bull PreDestroy
bull Resource
bull Resources
From jakartaannotationsecurity
bull DeclareRoles
bull RunAs
From jakartaannotationsql
bull DataSourceDefinition
bull DataSourceDefinitions
From jakartaejb
bull EJB
bull EJBs
From jakartajms
bull JMSConnectionFactoryDefinition
bull JMSConnectionFactoryDefinitions
bull JMSDestinationDefinition
bull JMSDestinationDefinitions
From jakartamail
81 Annotations and Pluggability
68 Jakarta Servlet Specification Final
bull MailSessionDefinition
bull MailSessionDefinitions
From jakartapersistence
bull PersistenceContext
bull PersistenceContexts
bull PersistenceUnit
bull PersistenceUnits
From jakartaresource
bull AdministeredObjectDefinition
bull AdministeredObjectDefinitions
bull ConnectionFactoryDefinition
bull ConnectionFactoryDefinitions
All annotations in the following packages
bull jakartajws
bull jakartajwssoap
bull jakartaxmlws
bull jakartaxmlwssoap
bull jakartaxmlwsspi
Following are the annotations that MUST be supported by a servlet compliant web container
811 WebServlet
This annotation is used to define a Servlet component in a web application This annotation isspecified on a class and contains metadata about the Servlet being declared The urlPatterns or thevalue attribute on the annotation MUST be present All other attributes are optional with defaultsettings (see javadocs for more details) It is recommended to use value when the only attribute on theannotation is the url pattern and to use the urlPatterns attribute when the other attributes are alsoused It is illegal to have both value and urlPatterns attribute used together on the same annotationThe default name of the Servlet if not specified is the fully qualified class name The annotated servletMUST specify at least one url pattern to be deployed If the same servlet class is declared in thedeployment descriptor under a different name a new instance of the servlet MUST be instantiated Ifthe same servlet class is added with a different name to the ServletContext via the programmatic APIdefined in Section 441 ldquoProgrammatically Adding and Configuring Servletsrdquo the attribute valuesdeclared via the WebServlet annotation MUST be ignored and a new instance of the servlet with thename specified MUST be created
81 Annotations and Pluggability
Final Jakarta Servlet Specification 69
Classes annotated with WebServlet class MUST extend the jakartaservlethttpHttpServlet class
Following is an example of how this annotation would be used
WebServlet Annotation Example
WebServlet(foo)public class CalculatorServlet extends HttpServlet
Following is an example of how this annotation would be used with some more of the attributesspecified
WebServlet annotation example using other annotation attributes specified
WebServlet(name=MyServlet urlPatterns=foo bar)public class SampleUsingAnnotationAttributes extends HttpServlet
public void doGet(HttpServletRequest req HttpServletResponse res)
812 WebFilter
This annotation is used to define a Filter in a web application This annotation is specified on a classand contains metadata about the filter being declared The default name of the Filter if not specified isthe fully qualified class name The urlPatterns attribute servletNames attribute or the value attribute ofthe annotation MUST be specified All other attributes are optional with default settings (see javadocsfor more details) It is recommended to use value when the only attribute on the annotation is the urlpattern and to use the urlPatterns attribute when the other attributes are also used It is illegal to haveboth value and urlPatterns attribute used together on the same annotation
Classes annotated with WebFilter MUST implement jakartaservletFilter
Following is an example of how this annotation would be used
81 Annotations and Pluggability
70 Jakarta Servlet Specification Final
WebFilter annotation example
WebFilter(foo)public class MyFilter implements Filter
public void doFilter(HttpServletRequest req HttpServletResponse res)
813 WebInitParam
This annotation is used to specify any init parameters that must be passed to the Servlet or the FilterIt is an attribute of the WebServlet and WebFilter annotation
814 WebListener
The WebListener annotation is used to annotate a listener to get events for various operations on theparticular web application context Classes annotated with WebListener MUST implement one of thefollowing interfaces
bull jakartaservletServletContextListener
bull jakartaservletServletContextAttributeListener
bull jakartaservletServletRequestListener
bull jakartaservletServletRequestAttributeListener
bull jakartaservlethttpHttpSessionListener
bull jakartaservlethttpHttpSessionAttributeListener
bull jakartaservlethttpHttpSessionIdListener
An example
WebListenerpublic class MyListener implements ServletContextListener
public void contextInitialized(ServletContextEvent sce) ServletContext sc = scegetServletContext() scaddServlet(myServlet Sample servlet foobarMyServlet null -1) scaddServletMapping(myServlet new String[] urlpattern )
81 Annotations and Pluggability
Final Jakarta Servlet Specification 71
815 MultipartConfig
This annotation when specified on a Servlet indicates that the request it expects is of typemultipartform-data The HttpServletRequest object of the corresponding servlet MUST make availablethe mime attachments via the getParts and getPart methods to iterate over the various mimeattachments The location attribute of the jakartaservletannotationMultipartConfig and theltlocationgt element of the ltmultipart-configgt is interpreted as an absolute path and defaults to thevalue of the jakartaservletcontexttempdir If a relative path is specified it will be relative to thetempdir location The test for absolute path vs relative path MUST be done via javaioFileisAbsolute
816 Other Annotations Conventions
In addition to these annotations all the annotations defined in Section 155 ldquoAnnotations and ResourceInjectionrdquo will continue to work in the context of these new annotations
By default all applications will have indexhtm[l] and indexjsp in the welcome-file-list Thedescriptor may to be used to override these default settings
The order in which the listeners servlets are loaded from the various framework jars classes in theWEB-INFclasses or WEB-INFlib is unspecified when using annotations If ordering is important thenlook at the section for modularity of webxml and ordering of webxml and web-fragmentxml below Theorder can be specified in the deployment descriptor only
82 Pluggability
821 Modularity of webxml
Using the annotations defined above makes the use of webxml optional However for overridingeither the default values or the values set via annotations the deployment descriptor is used Asbefore if the metadata-complete element is set to true in the webxml descriptor annotations that specifydeployment information present in the class files and web-fragments bundled in jars will not beprocessed It implies that all the metadata for the application is specified via the webxml descriptor
For better pluggability and less configuration for developers we introduce the notion of web moduledeployment descriptor fragments (web fragment) A web fragment is a part or all of the webxml thatcan be specified and included in a library or framework jarrsquos META-INF directory A plain old jar file inthe WEB-INFlib directory with no web-fragmentxml is also considered a fragment Any annotationsspecified in it will be processed according to the rules defined in 823 The container will pick up anduse the configuration as per the rules defined below
A web fragment is a logical partitioning of the web application in such a way that the frameworksbeing used within the web application can define all the artifacts without asking developers to edit oradd information in the webxml It can include almost all the same elements that the webxmldescriptor uses However the top level element for the descriptor MUST be web-fragment and thecorresponding descriptor file MUST be called web-fragmentxml The ordering related elements also
82 Pluggability
72 Jakarta Servlet Specification Final
differ between the web-fragmentxml and webxml See the corresponding schema for web-fragmentsin the deployment descriptor section in Chapter 14
If a framework is packaged as a jar file and has metadata information in the form of deploymentdescriptor then the web-fragmentxml descriptor must be in the META-INF directory of the jar file
If a framework wants its META-INFweb-fragmentxml honored in such a way that it augments a webapplicationrsquos webxml the framework must be bundled within the web applicationrsquos WEB-INFlibdirectory In order for any other types of resources (eg class files) of the framework to be madeavailable to a web application it is sufficient for the framework to be present anywhere in theclassloader delegation chain of the web application In other words only JAR files bundled in a webapplicationrsquos WEB-INFlib directory but not those higher up in the class loading delegation chain needto be scanned for web-fragmentxml
During deployment the container is responsible for scanning the location specified above anddiscovering the web-fragmentxml files and processing them The requirements about name uniquenessthat exist currently for a single webxml also apply to the union of a webxml and all applicable web-fragmentxml files
An example of what a library or framework can include is shown below
ltweb-fragmentgt
ltservletgt ltservlet-namegtwelcomeltservlet-namegt ltservlet-classgtcomexampleWelcomeServletltservlet-classgt ltservletgt
ltlistenergt ltlistener-classgtcomexampleRequestListenerltlistener-classgt ltlistenergt
ltweb-fragmentgt
The above web-fragmentxml would be included in the META-INF directory of the frameworkrsquos jar fileThe order in which configuration from web-fragmentxml and annotations should be applied isundefined If ordering is an important aspect for a particular application please see rules definedbelow on how to achieve the order desired
822 Ordering of webxml and web-fragmentxml
Since the specification allows the application configuration resources to be composed of multipleconfiguration files (webxml and web-fragmentxml) discovered and loaded from several different placesin the application the question of ordering must be addressed This section specifies howconfiguration resource authors may declare the ordering requirements of their artifacts
82 Pluggability
Final Jakarta Servlet Specification 73
A web-fragmentxml may have a top level ltnamegt element of type jakartaeejava-identifierType Therecan only be one ltnamegt element in a web-fragmentxml If a ltnamegt element is present it must beconsidered for the ordering of artifacts (unless the duplicate name exception applies as describedbelow)
Two cases must be considered to allow application configuration resources to express their orderingpreferences
1 Absolute ordering an ltabsolute-orderinggt element in the webxml There can only be one ltabsolute-orderinggt element in a webxml
a In this case ordering preferences that would have been handled by case 2 below must beignored
b The webxml and WEB-INFclasses MUST be processed before any of the web-fragments listed inthe absolute-ordering element
c Any ltnamegt element direct children of the ltabsolute-orderinggt MUST be interpreted asindicating the absolute ordering in which those named web-fragments which may or may notbe present must be processed
d The ltabsolute-orderinggt element may contain zero or one ltothersgt element The requiredaction for this element is described below If the ltabsolute-orderinggt element does not containan ltothersgt element any web-fragment not specifically mentioned within ltnamegt elementsMUST be ignored Excluded jars are not scanned for annotated servlets filters or listenersHowever if a servlet filter or listener from an excluded jar is listed in webxml or a non-excluded web-fragmentxml then itrsquos annotations will apply unless otherwise excluded bymetadata-complete ServletContextListeners discovered in TLD files of excluded jars are not ableto configure filters and servlets using the programmatic APIs Any attempt to do so will result inan IllegalStateException If a discovered ServletContainerInitializer is loaded from anexcluded jar it will be ignored Irrespective of the setting of metadata-complete jars excluded byltabsolute-orderinggt elements are not scanned for classes to be handled by anyServletContainerInitializer
e Duplicate name exception if when traversing the children of ltabsolute-orderinggt multiplechildren with the same ltnamegt element are encountered only the first such occurrence must beconsidered
2 Relative ordering an ltorderinggt element within the web-fragmentxml There can only be oneltorderinggt element in a web-fragmentxml
a A web-fragmentxml may have an ltorderinggt element If so this element must contain zero orone ltbeforegt element and zero or one ltaftergt element The meaning of these elements isexplained below
b The webxml and WEB-INFclasses MUST be processed before any of the web-fragments listed inthe ordering element
c Duplicate name exception if when traversing the web-fragments multiple members with thesame ltnamegt element are encountered the application must log an informative error messageincluding information to help fix the problem and must fail to deploy For example one way to
82 Pluggability
74 Jakarta Servlet Specification Final
fix this problem is for the user to use absolute ordering in which case relative ordering isignored
d Consider this abbreviated but illustrative example 3 web-fragments MyFragment1 MyFragment2and MyFragment3 are part of the application that also includes a webxml
web-fragmentxml
ltweb-fragmentgt ltnamegtMyFragment1ltnamegt ltorderinggt ltaftergt ltnamegtMyFragment2ltnamegt ltaftergt ltorderinggt ltweb-fragmentgt
web-fragmentxml
ltweb-fragmentgt ltnamegtMyFragment2ltnamegt ltweb-fragmentgt
web-fragmentxml
ltweb-fragmentgt ltnamegtMyFragment3ltnamegt ltorderinggt ltbeforegt ltothersgt ltbeforegt ltorderinggt ltweb-fragmentgt
webxml
ltweb-appgt ltweb-appgt
In this example the processing order will be
1 webxml
82 Pluggability
Final Jakarta Servlet Specification 75
2 MyFragment3
3 MyFragment2
4 MyFragment1
The preceding example illustrates some but not all of the following principles
bull ltbeforegt means the document must be ordered before the document with the name matching whatis specified within the nested ltnamegt element
bull ltaftergt means the document must be ordered after the document with the name matching what isspecified within the nested ltnamegt element
bull There is a special element ltothersgt which may be included zero or one time within the ltbeforegt orltaftergt element or zero or one time directly within the ltabsolute-orderinggt element The ltothersgtelement must be handled as follows
If the ltbeforegt element contains a nested ltothersgt the document will be moved to thebeginning of the list of sorted documents If there are multiple documents statingltbeforegtltothersgt they will all be at the beginning of the list of sorted documents but theordering within the group of such documents is unspecified
If the ltaftergt element contains a nested ltothersgt the document will be moved to the end ofthe list of sorted documents If there are multiple documents requiring ltaftergtltothersgt theywill all be at the end of the list of sorted documents but the ordering within the group of suchdocuments is unspecified
Within a ltbeforegt or ltaftergt element if an ltothersgt element is present but is not the onlyltnamegt element within its parent element the other elements within that parent must beconsidered in the ordering process
If the ltothersgt element appears directly within the ltabsolute-orderinggt element the runtimemust ensure that any web-fragments not explicitly named in the ltabsolute-orderinggt sectionare included at that point in the processing order
bull If a web-fragmentxml file does not have an ltorderinggt or the webxml does not have an ltabsolute-orderinggt element the artifacts are assumed to not have any ordering dependency
bull If the runtime discovers circular references an informative message must be logged and theapplication must fail to deploy Again one course of action the user may take is to use absoluteordering in the webxml
bull The previous example can be extended to illustrate the case when the webxml contains an orderingsection
82 Pluggability
76 Jakarta Servlet Specification Final
webxml
ltweb-appgt ltabsolute-orderinggt ltnamegtMyFragment3ltnamegt ltnamegtMyFragment2ltnamegt ltabsolute-orderinggt ltweb-appgt
In this example the ordering for the various elements will be
1 webxml
2 MyFragment3
3 MyFragment2
Some additional example scenarios are included below All of these apply to relative ordering and notabsolute ordering
Example 1
Document A
ltaftergt ltothersgt ltnamegtCltnamegtltaftergt
Document B
ltbeforegt ltothersgtltbeforegt
Document C
ltaftergt ltothersgtltaftergt
Document D
no ordering
Document E
82 Pluggability
Final Jakarta Servlet Specification 77
no ordering
Document F
ltbeforegt ltothersgt ltnamegtBltnamegtltbeforegt
Resulting parse order
webxml F B D E C A
Example 2
Document ltno idgt
ltaftergt ltothersgtltaftergtltbeforegt ltnamegtCltnamegtltbeforegt
Document B
ltbeforegt ltothersgtltbeforegt
Document C
no ordering
Document D
ltaftergt ltothersgtltaftergt
Document E
ltbeforegt ltothersgtltbeforegt
82 Pluggability
78 Jakarta Servlet Specification Final
Document F
no ordering
Resulting parse order can be one of the following
bull B E F ltno idgt C D
bull B E F ltno idgt D C
bull E B F ltno idgt C D
bull E B F ltno idgt D C
bull E B F D ltno idgt C
bull E B F D ltno idgt D
Example 3
Document A
ltaftergt ltnamegtBltnamegtltaftergt
Document B
no ordering
Document C
ltbeforegt ltothersgtltbeforegt
Document D
no ordering
Resulting parse order can be one of the following
bull C B D A
bull C D B A
bull C B A D
823 Assembling the Descriptor from webxml web-fragmentxml andAnnotations
If the order in which the listeners servlets filters are invoked is important to an application then adeployment descriptor must be used Also if necessary the ordering element defined above can be
82 Pluggability
Final Jakarta Servlet Specification 79
used As described above when using annotations to define the listeners servlets and filters the orderin which they are invoked is unspecified Below are a set of rules that apply for assembling the finaldeployment descriptor for the application
1 The order for listeners servlets filters if relevant must be specified in either the web-fragmentxmlor the webxml
2 The ordering will be based on the order in which they are defined in the descriptor and on theabsolute-ordering element in the webxml or an ordering element in the web-fragmentxml if present
a Filters that match a request are chained in the order in which they are declared in the webxml
b Servlets are initialized either lazily at request processing time or eagerly during deployment Inthe latter case they are initialized in the order indicated by their load-on-startup elements
c The listeners are invoked in the order in which they are declared in the webxml as specifiedbelow
i Implementations of jakartaservletServletContextListener are invoked at theircontextInitialized method in the order in which they have been declared and at theircontextDestroyed method in reverse order
ii Implementations of jakartaservletServletRequestListener are invoked at theirrequestInitialized method in the order in which they have been declared and at theirrequestDestroyed method in reverse order
iii Implementations of jakartaservlethttpHttpSessionListener are invoked at theirsessionCreated method in the order in which they have been declared and at theirsessionDestroyed method in reverse order
iv The methods of implementation of jakartaservletServletContextAttributeListenerjakartaservletServletRequestAttributeListener andjakartaservletHttpSessionAttributeListener are invoked in the order in which they aredeclared when corresponding events are fired
3 If a servlet is disabled using the enabled element introduced in the webxml then the servlet will notbe available at the url-pattern specified for the servlet
4 The webxml of the web application has the highest precedence when resolving conflicts betweenthe webxml web-fragmentxml and annotations
5 If metadata-complete is not specified in the descriptors or is set to false in the deploymentdescriptor then the effective metadata for the application is derived by combining the metadatapresent in the annotations and the descriptors The rules for merging are specified below
a Configuration settings in web fragments are used to augment those specified in the mainwebxml in such a way as if they had been specified in the same webxml
b The order in which configuration settings of web fragments are added to those in the mainwebxml is as specified above in Section 822 ldquoOrdering of webxml and web-fragmentxmlrdquo
c The metadata-complete attribute when set to true in the main webxml is considered completeand scanning of annotations and fragments will not occur at deployment time The absolute-
82 Pluggability
80 Jakarta Servlet Specification Final
ordering and ordering elements will be ignored if present When set to true on a fragment themetadata-complete attribute applies only to scanning of annotations in that particular jar
d Web fragments are merged into the main webxml unless the metadata-complete is set to true Themerging takes place after annotation processing on the corresponding fragment
e The following are considered configuration conflicts when augmenting a webxml with webfragments
i Multiple ltinit-paramgt elements with the same ltparam-namegt but different ltparam-valuegt
ii Multiple ltmime-mappinggt elements with the same ltextensiongt but different ltmime-typegt
f The above configuration conflicts are resolved as follows
i Configuration conflicts between the main webxml and a web fragment are resolved suchthat the configuration in the webxml takes precedence
ii Configuration conflicts between two web fragments where the element at the center of theconflict is not present in the main webxml will result in an error An informative messagemust be logged and the application must fail to deploy
g After the above conflicts have been resolved these additional rules are applied
i Elements that may be declared any number of times are additive across the web-fragments inthe resulting webxml For example ltcontext-paramgt elements with different ltparam-namegt areadditive
ii Elements that may be declared any number of times if specified in the webxml overrides thevalues specified in the web-fragments with the same name
iii If an element with a minimum occurrence of zero and a maximum occurrence of one ispresent in a web fragment and missing in the main webxml the main webxml inherits thesetting from the web fragment If the element is present in both the main webxml and theweb fragment the configuration setting in the main webxml takes precedence For exampleif both the main webxml and a web fragment declare the same servlet and the servletdeclaration in the web fragment specifies a ltload-on-startupgt element whereas the one inthe main webxml does not then the ltload-on-startupgt element from the web fragment willbe used in the merged webxml
iv It is considered an error if an element with a minimum occurrence of zero and a maximumoccurrence of one is specified differently in two web fragments while absent from themain webxml For example if two web fragments declare the same servlet but withdifferent ltload-on-startupgt elements and the same servlet is also declared in the mainwebxml but without any ltload-on-startupgt then an error must be reported
v ltwelcome-filegt declarations are additive
vi ltservlet-mappinggt elements with the same ltservlet-namegt are additive across web-fragmentsltservlet-mappinggt specified in the webxml overrides values specified in the web-fragmentswith the same ltservlet-namegt
vii ltfilter-mappinggt elements with the same ltfilter-namegt are additive across web-fragmentsltfilter-mappinggt specified in the webxml overrides values specified in the web-fragments
82 Pluggability
Final Jakarta Servlet Specification 81
with the same ltfilter-namegt
viii Multiple ltlistenergt elements with the same ltlistener-classgt are treated as a singleltlistenergt declaration
ix The webxml resulting from the merge is considered ltdistributablegt only if the webxml andall the web fragments are marked as ltdistributablegt
x The top-level lticongt and its children elements ltdisplay-namegt and ltdescriptiongt elementsof a web fragment are ignored
xi jsp-property-group is additive It is recommended that jsp-config element use the url-pattern as opposed to extension mappings when bundling static resources in the META-INFresources directory of a jar file Further more JSP resources for a fragment should be ina sub-directory same as the fragment name if there exists one This helps prevent a web-fragmentrsquos jsp-property-group from affecting the JSPs in the main docroot of the applicationand the jsp-property-group from affecting the JSPs in a fragmentrsquos META-INFresourcesdirectory
h For all the resource reference elements ( env-entry ejb-ref ejb-local-ref service-refresource-ref resource-env-ref message-destination-ref persistence-context-ref andpersistence-unit-ref) the following rules apply
i If any resource reference element is present in a web fragment and is missing in the mainwebxml the main webxml inherits the value from the web fragment If the element ispresent in both the main webxml and the web fragment with the same name the webxmltakes precedence None of the child elements from the fragment are merged into the mainwebxml except for the injection-target as specified below For example if both the mainwebxml and a web fragment declare a ltresource-refgt with the same ltresource-ref-namegt theltresource-refgt from the webxml will be used without any child elements being merged fromthe fragment except ltinjection-targetgt as described below
ii If a resource reference element is specified in two fragments while absent from the mainwebxml and all the attributes and child elements of the resource reference element areidentical the resource reference will be merged into the main webxml It is considered anerror if a resource reference element has the same name specified in two fragments whileabsent from the main webxml and the attributes and child elements are not identical in thetwo fragments An error must be reported and the application MUST fail to deploy Forexample if two web fragments declare a ltresource-refgt with the same ltresource-ref-namegtelement but the type in one is specified as javaxsqlDataSource while the type in the otheris that of a Jakarta Mail resource it is an error and the application will fail to deploy
iii For resource reference element with the same name ltinjection-targetgt elements from thefragments will be merged into the main webxml
i In addition to the merging rules for web-fragmentxml defined above the following rules applywhen using the resource reference annotations (Resource Resources EJB EJBsWebServiceRef WebServiceRefs PersistenceContext PersistenceContextsPersistenceUnitand PersistenceUnits)
82 Pluggability
82 Jakarta Servlet Specification Final
If a resource reference annotation is applied on a class it is equivalent to defining a resourcehowever it is not equivalent to defining an injection-target The rules above apply forinjection-target element in this case
If a resource reference annotation is used on a field it is equivalent to defining the injection-target element in the webxml However if there is no injection-target element in the descriptorthen the injection-target from the fragments will still be merged into the webxml as definedabove
If on the other hand there is an injection-target in the main webxml and there is a resourcereference annotation with the same resource name then it is considered an override for theresource reference annotation In this case since there is an injection-target specified in thedescriptor the rules defined above would apply in addition to overriding the value for theresource reference annotation
j If a data-source element is specified in two fragments while absent from the main webxml andall the attributes and child elements of the data-source element are identical the data-sourcewill be merged into the main webxml It is considered an error if a data-source element has thesame name specified in two fragments while absent from the main webxml and the attributesand child elements are not identical in the two fragments In such a case an error must bereported and the application MUST fail to deploy
Below are some examples that show the outcome in the different cases
Example 1
webxml
no resource-ref definition
Fragment 1 - web-fragmentxml
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBarltinjection-target-classgt ltinjection-target-namegtbazltinjection-target-namegt ltinjection-targetgtltresource-refgt
The effective metadata would be
82 Pluggability
Final Jakarta Servlet Specification 83
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBarltinjection-target-classgt ltinjection-target-namegtbazltinjection-target-namegt ltinjection-targetgtltresource-refgt
Example 2
webxml
ltresource-refgt ltresource-ref-name=foogt ltresource-refgt
Fragment 1 - web-fragmentxml
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBarltinjection-target-classgt ltinjection-target-namegtbazltinjection-target-namegt ltinjection-targetgtltresource-refgt
Fragment 2 - web-fragmentxml
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBar2ltinjection-target-classgt ltinjection-target-namegtbaz2ltinjection-target-namegt ltinjection-targetgtltresource-refgt
The effective metadata would be
82 Pluggability
84 Jakarta Servlet Specification Final
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBarltinjection-target-classgt ltinjection-target-namegtbazltinjection-target-namegt ltinjection-targetgt ltinjection-targetgt ltinjection-target-classgtcomexampleBar2ltinjection-target-classgt ltinjection-target-namegtbaz2ltinjection-target-namegt ltinjection-targetgtltresource-refgt
Example 3
webxml
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBar3ltinjection-target-classgt ltinjection-target-namegtbaz3ltinjection-target-namegt ltinjection-targetgtltresource-refgt
Fragment 1 - web-fragmentxml
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBarltinjection-target-classgt ltinjection-target-namegtbazltinjection-target-namegt ltinjection-targetgtltresource-refgt
82 Pluggability
Final Jakarta Servlet Specification 85
Fragment 2 - web-fragmentxml
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBar2ltinjection-target-classgt ltinjection-target-namegtbaz2ltinjection-target-namegt ltinjection-targetgtltresource-refgt
The effective metadata would be
ltresource-refgt ltresource-ref-name=foogt ltinjection-targetgt ltinjection-target-classgtcomexampleBar3ltinjection-target-classgt ltinjection-target-namegtbaz3ltinjection-target-namegt ltinjection-target-classgtcomexampleBarltinjection-target-classgt ltinjection-target-namegtbazltinjection-target-namegt ltinjection-target-classgtcomexampleBar2ltinjection-target-classgt ltinjection-target-namegtbaz2ltinjection-target-namegt ltinjection-targetgtltresource-refgt
The ltinjection-targetgt from fragment 1 and 2 will be merged into the main webxml
k If the main webxml does not have any ltpost-constructgt element specified and web-fragmentshave specified ltpost-constructgt then the ltpost-constructgt elements from the fragments will bemerged into the main webxml However if in the main webxml at least one ltpost-constructgtelement is specified then the ltpost-constructgt elements from the fragment will not be mergedIt is the responsibility of the author of the webxml to make sure that the ltpost-constructgt list iscomplete
l If the main webxml does not have any ltpre-destroygt element specified and web-fragments havespecified ltpre-destroygt then the ltpre-destroygt elements from the fragments will be merged intothe main webxml However if in the main webxml at least one ltpre-destroygt element is specifiedthen the ltpre-destroygt elements from the fragment will not be merged It is the responsibility ofthe author of the webxml to make sure that the ltpre-destroygt list is complete
m After processing the web-fragmentxml annotations from the corresponding fragment areprocessed to complete the effective metadata for the fragment before processing the nextfragment The following rules are used for processing annotations
i Any metadata specified via an annotation that isnrsquot already present in the descriptor will beused to augment the effective descriptor
82 Pluggability
86 Jakarta Servlet Specification Final
ii Configuration specified in the main webxml or a web fragment takes precedence over theconfiguration specified via annotations
iii For a servlet defined via the WebServlet annotation to override values via the descriptorthe name of the servlet in the descriptor MUST match the name of the servlet specified viathe annotation (explicitly specified or the default name if one is not specified via theannotation)
iv Init params for servlets and filters defined via annotations will be overridden in thedescriptor if the name of the init param exactly matches the name specified via theannotation Init params are additive between the annotations and descriptors
v url-patterns when specified in a descriptor for a given servlet name overrides the urlpatterns specified via the annotation
vi For a filter defined via the WebFilter annotation to override values via the descriptor thename of the filter in the descriptor MUST match the name of the filter specified via theannotation (explicitly specified or the default name if one is not specified via theannotation)
vii url-patterns to which a filter is applied when specified in a descriptor for a given filtername overrides the url patterns specified via the annotation
viii DispatcherTypes to which a filter applies when specified in a descriptor for a given filtername overrides the DispatcherTypes specified via the annotation
ix The following examples demonstrates some of the above rules
A servlet declared via an annotation and packaged with the corresponding webxml in thedescriptor
WebServlet(urlPatterns=MyPattern initParams=WebInitParam(name=ccc value=333))public class comexampleFoo extends HttpServlet
82 Pluggability
Final Jakarta Servlet Specification 87
webxml
ltservletgt ltservlet-classgtcomexampleFooltservlet-classgt ltservlet-namegtFooltservlet-namegt ltinit-paramgt ltparam-namegtaaaltparam-namegt ltparam-valuegt111ltparam-valuegt ltinit-paramgtltservletgtltservletgt ltservlet-classgtcomexampleFooltservlet-classgt ltservlet-namegtFumltservlet-namegt ltinit-paramgt ltparam-namegtbbbltparam-namegt ltparam-valuegt222ltparam-valuegt ltinit-paramgtltservletgtltservlet-mappinggt ltservlet-namegtFooltservlet-namegt lturl-patterngtfoolturl-patterngtltservlet-mappinggtltservlet-mappinggt ltservlet-namegtFumltservlet-namegt lturl-patterngtfumlturl-patterngtltservlet-mappinggt
Since the name of the servlet declared via the annotation does not match the name of theservlet declared in the webxml the annotation specifies a new servlet declaration inaddition to the other declarations in webxml and is equivalent to
webxml
ltservletgt ltservlet-classgtcomexampleFooltservlet-classgt ltservlet-namegtcomexampleFooltservlet-namegt ltinit-paramgt ltparam-namegtcccltparam-namegt ltparam-valuegt333ltparam-namegt ltinit-paramgtltservletgt
If the above webxml were replaced with the following
82 Pluggability
88 Jakarta Servlet Specification Final
webxml
ltservletgt ltservlet-classgtcomexampleFooltservlet-classgt ltservlet-namegtcomexampleFooltservlet-namegt ltinit-paramgt ltparam-namegtaaaltparam-namegt ltparam-valuegt111ltparam-valuegt ltinit-paramgtltservletgtltservlet-mappinggt ltservlet-namegtcomexampleFooltservlet-namegt lturl-patterngtfoolturl-patterngtltservlet-mappinggt
Then the effective descriptor would be equivalent to
webxml
ltservletgt ltservlet-classgtcomexampleFooltservlet-classgt ltservlet-namegtcomexampleFooltservlet-namegt ltinit-paramgt ltparam-namegtaaaltparam-namegt ltparam-valuegt111ltparam-valuegt ltinit-paramgt ltinit-paramgt ltparam-namegtcccltparam-namegt ltparam-valuegt333ltparam-valuegt ltinit-paramgtltservletgtltservlet-mappinggt ltservlet-namegtcomexampleFooltservlet-namegt lturl-patterngtfoolturl-patterngtltservlet-mappinggt
824 Shared Libraries Runtimes Pluggability
In addition to supporting fragments and use of annotations one of the requirements is that not onlywe be able to plug-in things that are bundled in the WEB-INFlib but also plugin shared copies offrameworks - including being able to plug-in to the web container things like JAX-WS JAX-RS and JSFthat build on top of the web container The ServletContainerInitializer allows handling such a usecase as described below
The ServletContainerInitializer class is looked up via the jar services API For each application aninstance of the ServletContainerInitializer is created by the container at application startup time The
82 Pluggability
Final Jakarta Servlet Specification 89
framework providing an implementation of the ServletContainerInitializer MUST bundle in the META-INFservices directory of the jar file a file called jakartaservletServletContainerInitializer as perthe jar services API that points to the implementation class of the ServletContainerInitializer
In addition to the ServletContainerInitializer we also have an annotation - HandlesTypes TheHandlesTypes annotation on the implementation of the ServletContainerInitializer is used to expressinterest in classes that may have annotations (type method or field level annotations) specified in thevalue of the HandlesTypes or if it extends implements one those classes anywhere in the classrsquos supertypes The HandlesTypes annotation is applied irrespective of the setting of metadata-complete
When examining the classes of an application to see if they match any of the criteria specified by theHandlesTypes annotation of a ServletContainerInitializer the container may run into class loadingproblems if one or more of the applicationrsquos optional JAR files are missing Since the container is not ina position to decide whether these types of class loading failures will prevent the application fromworking correctly it must ignore them while at the same time providing a configuration option thatwould log them
If an implementation of ServletContainerInitializer does not have the HandlesTypes annotation or ifthere are no matches to any of the HandlesType specified then it will get invoked once for everyapplication with null as the value of the Set This will allow for the initializer to determine based onthe resources available in the application whether it needs to initialize a servlet filter or not
The onStartup method of the ServletContainerInitializer will be invoked when the application iscoming up before any of the servlet listener events are fired
The onStartup method of the ServletContainerInitializer is called with a Set of Classes that eitherextend implement the classes that the initializer expressed interest in or if it is annotated with any ofthe classes specified via the HandlesTypes annotation
A concrete example below showcases how this would work
Letrsquos take the JAX-WS web services runtime
The implementation of JAX-WS runtime isnrsquot typically bundled in each and every war file Theimplementation would bundle an implementation of the ServletContainerInitializer (shown below)and the container would look that up using the services API (the jar file will bundle in itrsquos META-INFservices directory a file called jakartaservletServletContainerInitializer that will point to theJAXWSServletContainerInitializer (shown below)
82 Pluggability
90 Jakarta Servlet Specification Final
JAXWSServletContainerInitializerjava
HandlesTypes(WebServiceclass)JAXWSServletContainerInitializer implements ServletContainerInitializer
public void onStartup(SetltClassltgtgt c ServletContext ctx) throws ServletException JAX-WS specific code here to initialize the runtime and setup the mapping etc ServletRegistration reg = ctxaddServlet(JAXWSServlet comsunwebserviceJAXWSServlet) regaddServletMapping(foo)
The framework jar file can also be bundled in WEB-INFlib directory of the war file If theServletContainerInitializer is bundled in a JAR file inside the WEB-INFlib directory of an applicationits onStartup method will be invoked only once during the startup of the bundling application If onthe other hand the ServletContainerInitializer is bundled in a JAR file outside of the WEB-INFlibdirectory but still discoverable by the runtimersquos service provider lookup mechanism its onStartupmethod will be invoked every time an application is started
Implementations of the ServletContainerInitializer interface will be discovered by the runtimersquosservice lookup mechanism or a container specific mechanism that is semantically equivalent to it Ineither case ServletContainerInitializer services from web fragment JAR files that are excluded froman absolute ordering MUST be ignored and the order in which these services are discovered MUSTfollow the applicationrsquos class loading delegation model
83 JSP Container PluggabilityThe ServletContainerInitializer and programmatic registration features make it possible to provide aclear separation of responsibilities between the servlet and JSP containers by making the servletcontainer responsible for parsing only webxml and web-fragmentxml resources and delegating theparsing of Tag Library Descriptor (TLD) resources to the JSP container
Previously a web container had to scan TLD resources for any listener declarations With Servlet 30and later versions this responsibility may be delegated to the JSP container A JSP container that isembedded in a servlet container may provide its own ServletContainerInitializer implementationsearch the ServletContext passed to its onStartup method for any TLD resources scan those resourcesfor listener declarations and register the corresponding listeners with the ServletContext
In addition prior to Servlet 30 a JSP container used to have to scan an applicationrsquos deploymentdescriptor for any jsp-config related configuration With Servlet 30 and later versions the servletcontainer must make available via the ServletContextgetJspConfigDescriptor method any jsp-configrelated configuration from the applicationrsquos webxml and web-fragmentxml deployment descriptors
Any ServletContextListeners that were discovered in a TLD and registered programmatically are
83 JSP Container Pluggability
Final Jakarta Servlet Specification 91
limited in the functionality they provide Any attempt to call a ServletContext API methods on themthat was added since Servlet 30 will result in an UnsupportedOperationException
In addition a servlet container compliant with Servlet 30 or later versions must provide aServletContext attribute with name jakartaservletcontextorderedLibs whose value (of typejavautilListltjavalangStringgt) contains the list of names of JAR files in the WEB-INFlib directory ofthe application represented by the ServletContext ordered by their web fragment names (withpossible exclusions if fragment JAR files have been excluded from absolute-ordering) or null if theapplication does not specify any absolute or relative ordering
84 Processing Annotations and FragmentsWeb applications can include both annotations and the webxml web-fragmentxml deploymentdescriptors The version of the descriptor MUST not affect which annotations the container scans for ina web application An implementation of a particular version of the specification MUST scan for allannotations supported in that configuration unless metadata-complete is specified If there is nodeployment descriptor or there is one but does not have the metadata-complete set to true webxml web-fragmentxml and annotations if used in the application must be processed The following tabledescribes whether or not to process annotations and webxml fragments
Table 8-1 Annotations and web fragment processing requirements
Deployment descriptor metadata-complete process annotations and webfragments
webxml 25 yes no
webxml 25 no yes
webxml 30 or later yes no
webxml 30 or later no yes
84 Processing Annotations and Fragments
92 Jakarta Servlet Specification Final
Chapter 9 Dispatching RequestsWhen 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 interfaceprovides a mechanism to accomplish this
When asynchronous processing is enabled on the request the AsyncContext allows a user to dispatchthe request back to the servlet container
91 Obtaining a RequestDispatcherAn object implementing the RequestDispatcher interface may be obtained from the ServletContext viathe following methods
bull getRequestDispatcher
bull getNamedDispatcher
The getRequestDispatcher method takes a String argument describing a path within the scope of theServletContext This path must be relative to the root of the ServletContext and begin with a or beempty The method uses the path to look up a servlet using the servlet path matching rules in Chapter12 Mapping Requests to Servlets wraps it with a RequestDispatcher object and returns the resultingobject If no servlet can be resolved based on the given path a RequestDispatcher is provided thatreturns the content for that path
The getNamedDispatcher method takes a String argument indicating the name of a servlet known to theServletContext If a servlet is found it is wrapped with a RequestDispatcher object and the object isreturned If no servlet is associated with the given name the method must return null
To allow RequestDispatcher objects to be obtained using relative paths that are relative to the path ofthe current request (not relative to the root of the ServletContext) the getRequestDispatcher method isprovided in the ServletRequest interface
The behavior of this method is similar to the method of the same name in the ServletContext Theservlet container uses information in the request object to transform the given relative path againstthe current servlet to a complete path For example in a context rooted at and a request togardentoolshtml a request dispatcher obtained viaServletRequestgetRequestDispatcher(headerhtml) will behave exactly like a call toServletContextgetRequestDispatcher(gardenheaderhtml)
911 Query Strings in Request Dispatcher Paths
The ServletContext and ServletRequest methods that create RequestDispatcher objects using pathinformation allow the optional attachment of query string information to the path For example anApplication Developer may obtain a RequestDispatcher by using the following code
91 Obtaining a RequestDispatcher
Final Jakarta Servlet Specification 93
String path = raisinsjsporderno=5RequestDispatcher rd = contextgetRequestDispatcher(path)rdinclude(request response)
Parameters specified in the query string used to create the RequestDispatcher take precedence overother parameters of the same name passed to the included servlet The parameters associated with aRequestDispatcher are scoped to apply only for the duration of the include or forward call
92 Using a Request DispatcherTo use a request dispatcher a servlet calls either the include method or forward method of theRequestDispatcher interface The parameters to these methods can be either the request and responsearguments that were passed in via the service method of the jakartaservletServlet interface orinstances of subclasses of the request and response wrapper classes that were introduced for version23 of the specification In the latter case the wrapper instances must wrap the request or responseobjects that the container passed into the service method
The Container Provider should ensure that the dispatch of the request to a target servlet occurs in thesame thread of the same JVM as the original request
93 The Include MethodThe include method of the RequestDispatcher interface may be called at any time The target servlet ofthe include method has access to all aspects of the request object but its use of the response object ismore limited
It can only write information to the ServletOutputStream or Writer of the response object and commit aresponse by writing content past the end of the response buffer or by explicitly calling the flushBuffermethod of the ServletResponse interface It cannot set headers or call any method that affects theheaders of the response with the exception of the HttpServletRequestgetSession() andHttpServletRequestgetSession(boolean) methods Any attempt to set the headers must be ignored andany call to HttpServletRequestgetSession() or HttpServletRequestgetSession(boolean) that wouldrequire adding a Cookie response header must throw an IllegalStateException if the response hasbeen committed
If the default servlet is the target of a RequestDispatchinclude() and the requested resource does notexist then the default servlet MUST throw FileNotFoundException If the exception isnrsquot caught andhandled and the response hasnrsquot been committed the status code MUST be set to 500
931 Included Request Parameters
Except for servlets obtained by using the getNamedDispatcher method a servlet that has been invokedby another servlet using the include method of RequestDispatcher has access to the path by which itwas invoked
92 Using a Request Dispatcher
94 Jakarta Servlet Specification Final
The following request attributes must be set
jakartaservletincluderequest_urijakartaservletincludecontext_pathjakartaservletincludeservlet_pathjakartaservletincludemappingjakartaservletincludepath_infojakartaservletincludequery_string
These attributes are accessible from the included servlet via the getAttribute method on the requestobject and their values must be equal to the request URI context path servlet path path info andquery string of the included servlet respectively If the request is subsequently included theseattributes are replaced for that include
If the included servlet was obtained by using the getNamedDispatcher method these attributes must notbe set
94 The Forward MethodThe forward method of the RequestDispatcher interface may be called by the calling servlet only whenno output has been committed to the client If output data exists in the response buffer that has notbeen committed the content must be cleared before the target servletrsquos service method is called If theresponse 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 toobtain the RequestDispatcher
The only exception to this is if the RequestDispatcher was obtained via the getNamedDispatcher methodIn this case the path elements of the request object must reflect those of the original request
Before the forward method of the RequestDispatcher interface returns without exception the responsecontent must be sent and committed and closed by the servlet container unless the request was putinto the asynchronous mode If an error occurs in the target of the RequestDispatcherforward() theexception may be propagated back through all the calling filters and servlets and eventually back tothe container
941 Query String
The request dispatching mechanism is responsible for aggregating query string parameters whenforwarding or including requests
942 Forwarded Request Parameters
Except for servlets obtained by using the getNamedDispatcher method a servlet that has been invokedby another servlet using the forward method of RequestDispatcher has access to the path of the original
94 The Forward Method
Final Jakarta Servlet Specification 95
request
The following request attributes must be set
jakartaservletforwardmappingjakartaservletforwardrequest_urijakartaservletforwardcontext_pathjakartaservletforwardservlet_pathjakartaservletforwardpath_infojakartaservletforwardquery_string
The values of these attributes must be equal to the return values of the HttpServletRequest methodsgetRequestURI getContextPath getServletPath getPathInfo getQueryString respectively invoked on therequest object passed to the first servlet object in the call chain that received the request from theclient
These attributes are accessible from the forwarded servlet via the getAttribute method on the requestobject Note that these attributes must always reflect the information in the original request evenunder the situation that multiple forwards and subsequent includes are called
If the forwarded servlet was obtained by using the getNamedDispatcher method these attributes mustnot be set
95 Error HandlingIf the servlet that is the target of a request dispatcher throws a runtime exception or a checkedexception of type ServletException or IOException it should be propagated to the calling servlet Allother exceptions should be wrapped as ServletExceptions and the root cause of the exception set to theoriginal exception as it should not be propagated
96 Obtaining an AsyncContextAn object implementing the AsyncContext interface may be obtained from the ServletRequest via one ofstartAsync methods Once you have an AsyncContext you can use it to either complete the processing ofthe request via the complete() method or use one of the dispatch methods described below
97 The Dispatch MethodThe following methods can be used to dispatch requests from the AsyncContext
dispatch(path)
The dispatch method takes a String argument describing a path within the scope of theServletContext This path must be relative to the root of the ServletContext and begin with a
95 Error Handling
96 Jakarta Servlet Specification Final
dispatch(servletContext path)
The dispatch method takes a String argument describing a path within the scope of theServletContext specified This path must be relative to the root of the ServletContext specified andbegin with a
dispatch()
The dispatch method takes no argument It uses the original URI as the path If the AsyncContext wasinitialized via the startAsync(ServletRequest ServletResponse) and the request passed is aninstance of HttpServletRequest then the dispatch is to the URI returned byHttpServletRequestgetRequestURI() Otherwise the dispatch is to the URI of the request when it waslast dispatched by the container
One of the dispatch methods of the AsyncContext interface may be called by the application waiting forthe asynchronous event to happen If complete() has been called on the AsyncContext anIllegalStateException must be thrown All the variations of the dispatch methods returns immediatelyand do not commit the response
The path elements of the request object exposed to the target servlet must reflect the path specified inthe AsyncContextdispatch
971 Query String
The request dispatching mechanism is responsible for aggregating query string parameters whendispatching requests
972 Dispatched Request Parameters
A servlet that has been invoked by using the dispatch method of AsyncContext has access to the path ofthe original request
The following request attributes must be set
jakartaservletasyncmappingjakartaservletasyncrequest_urijakartaservletasynccontext_pathjakartaservletasyncservlet_pathjakartaservletasyncpath_infojakartaservletasyncquery_string
The values of these attributes must be equal to the return values of the HttpServletRequest methodsgetRequestURI getContextPath getServletPath getPathInfo getQueryString respectively invoked on therequest object passed to the first servlet object in the call chain that received the request from theclient
These attributes are accessible from the dispatched servlet via the getAttribute method on the request
97 The Dispatch Method
Final Jakarta Servlet Specification 97
object Note that these attributes must always reflect the information in the original request evenunder the situation that multiple dispatches are called
97 The Dispatch Method
98 Jakarta Servlet Specification Final
Chapter 10 Web ApplicationsA web application is a collection of servlets HTML pages classes and other resources that make up acomplete application on a web server The web application can be bundled and run on multiplecontainers from multiple vendors
101 Web Applications Within Web ServersA web application is rooted at a specific path within a web server For example a catalog applicationcould be located at httpwwwexamplecomcatalog All requests that start with this prefix will berouted to the ServletContext which represents the catalog application
A servlet container can establish rules for automatic generation of web applications For example a~user mapping could be used to map to a web application based at homeuserpublic_html
By default an instance of a web application must run on one JVM at any one time This behavior canbe overridden if the application is marked as ldquodistributablerdquo via its deployment descriptor Anapplication marked as distributable must obey a more restrictive set of rules than is required of anormal web application These rules are set out throughout this specification
102 Relationship to ServletContextThe servlet container must enforce a one to one correspondence between a web application and aServletContext A ServletContext object provides a servlet with its view of the application
103 Elements of a Web ApplicationA web application may consist of the following items
bull Servlets
bull JSP Pages [6]
bull Utility Classes
bull Static documents (HTML images sounds etc)
bull Client side Java applets beans and classes
bull Descriptive meta information that ties all of the above elements together
104 Deployment HierarchiesThis specification defines a hierarchical structure used for deployment and packaging purposes thatcan exist in an open file system in an archive file or in some other form It is recommended but notrequired that servlet containers support this structure as a runtime representation
101 Web Applications Within Web Servers
Final Jakarta Servlet Specification 99
105 Directory StructureA web application exists as a structured hierarchy of directories The root of this hierarchy serves asthe document root for files that are part of the application For example for a web application with thecontext path catalog in a web container the indexhtml file at the base of the web applicationhierarchy or in a JAR file inside WEB-INFlib that includes the indexhtml under META-INFresourcesdirectory can be served to satisfy a request from catalogindexhtml If an indexhtml is present bothin the root context and in the META-INFresources directory of a JAR file in the WEB-INFlib directory ofthe application then the file that is available in the root context MUST be used The rules for matchingURLs to context path are laid out in Chapter 12 Mapping Requests to Servlets Since the context path ofan application determines the URL namespace of the contents of the web application web containersmust reject web applications defining a context path that could cause potential conflicts in this URLnamespace This may occur for example by attempting to deploy a second web application with thesame context path Since requests are matched to resources in a case-sensitive manner thisdetermination of potential conflict must be performed in a case-sensitive manner as well
A special directory exists within the application hierarchy named WEB-INF This directory contains allthings related to the application that arenrsquot in the document root of the application Most of the WEB-INFnode is not part of the public document tree of the application Except for static resources and JSPspackaged in the META-INFresources of a JAR file that resides in the WEB-INFlib directory no other filescontained in the WEB-INF directory may be served directly to a client by the container However thecontents of the WEB-INF directory are visible to servlet code using the getResource andgetResourceAsStream method calls on the ServletContext and may be exposed using theRequestDispatcher calls Hence if the Application Developer needs access from servlet code toapplication specific configuration information that should not be exposed directly to the web client itmay be placed under this directory Since requests are matched to resource mappings in a case-sensitive manner client requests for WEB-INFfoo WEb-iNffoo for example should not result incontents of the web application located under WEB-INF being returned nor any form of directorylisting thereof
The contents of the WEB-INF directory are
bull The WEB-INFwebxml deployment descriptor
bull The WEB-INFclasses directory for servlet and utility classes The classes in this directory must beavailable to the application class loader
bull The WEB-INFlibjar area for Java ARchive files These files contain servlets beans staticresources and JSPs packaged in a JAR file and other utility classes useful to the web application Theweb application class loader must be able to load classes from any of these archive files
The web application class loader must load classes from the WEB-INFclasses directory first and thenfrom library JARs in the WEB-INFlib directory Also except for the case where static resources arepackaged in JAR files any requests from the client to access the resources in WEB-INF directory must bereturned with a SC_NOT_FOUND (404) response
105 Directory Structure
100 Jakarta Servlet Specification Final
1051 Example of Application Directory Structure
The following is a listing of all the files in a sample web application
indexhtmlhowtojspfeedbackjspimagesbannergifimagesjumpinggifWEB-INFwebxmlWEB-INFlibjspbeanjarWEB-INFlibcatalogjarMETA-INFresourcescatalogmoreOffersbookshtmlWEB-INFclassescommycorpservletsMyServletclassWEB-INFclassescommycorputilMyUtilsclass
106 Web Application Archive FileWeb applications can be packaged and signed into a Web ARchive format (WAR) file using the standardJava archive tools For example an application for issue tracking might be distributed in an archive filecalled issuetrackwar
When packaged into such a form a META-INF directory will be present which contains informationuseful to Java archive tools This directory must not be directly served as content by the container inresponse to a web clientrsquos request though its contents are visible to servlet code via the getResourceand getResourceAsStream calls on the ServletContext Also any requests to access the resources in META-INF directory must be returned with a SC_NOT_FOUND (404) response
107 Web Application Deployment DescriptorThe web application deployment descriptor (see Chapter 14 Deployment Descriptor) includes thefollowing types of configuration and deployment information
bull ServletContext Init Parameters
bull Session Configuration
bull ServletJSP Definitions
bull ServletJSP Mappings
bull MIME Type Mappings
bull Welcome File list
bull Error Pages
bull Security
106 Web Application Archive File
Final Jakarta Servlet Specification 101
1071 Dependencies On Extensions
When a number of applications make use of the same code or resources they will typically be installedas library files in the container These files are often common or standard APIs that can be usedwithout sacrificing portability Files used only by one or a few applications will be made available foraccess as part of the web application The container must provide a directory for these libraries Thefiles placed within this directory must be available across all web applications The location of thisdirectory is container-specific The class loader the servlet container uses for loading these library filesmust be the same for all web applications within the same JVM This class loader instance must besomewhere in the chain of parent class loaders of the web application class loader
Application developers need to know what extensions are installed on a web container and containersneed to know what dependencies servlets in a WAR have on such libraries in order to preserveportability
The application developer depending on such an extension or extensions must provide a META-INFMANIFESTMF entry in the WAR file listing all extensions needed by the WAR The format of themanifest entry should follow standard JAR manifest format During deployment of the webapplication the web container must make the correct versions of the extensions available to theapplication following the rules defined by the Optional Package Versioning mechanism(httpdocsoraclecomjavase8docstechnotesguidesextensionsversioninghtml)
Web containers must also be able to recognize declared dependencies expressed in the manifest entryof any of the library JARs under the WEB-INFlib entry in a WAR
If a web container is not able to satisfy the dependencies declared in this manner it should reject theapplication with an informative error message
1072 Web Application Class Loader
The class loader that a container uses to load a servlet in a WAR must allow the developer to load anyresources contained in library JARs within the WAR following normal Java SE semantics usinggetResource Servlet containers that are not part of a Jakarta EE product should not allow theapplication to override Jakarta EE platform classes such as those in the jakarta namespaces thatJakarta EE does not allow to be modified The container should not allow applications to override oraccess the containerrsquos implementation classes It is recommended also that the application class loaderbe implemented so that classes and resources packaged within the WAR are loaded in preference toclasses and resources residing in container-wide library JARs An implementation MUST alsoguarantee that for every web application deployed in a container a call toThreadcurrentThreadgetContextClassLoader() MUST return a ClassLoader instance that implementsthe contract specified in this section Furthermore the ClassLoader instance MUST be a separateinstance for each deployed web application The container is required to set the thread contextClassLoader as described above before making any callbacks (including listener callbacks) into the webapplication and set it back to the original ClassLoader once the callback returns
107 Web Application Deployment Descriptor
102 Jakarta Servlet Specification Final
108 Replacing a Web ApplicationA server should be able to replace an application with a new version without restarting the containerWhen an application is replaced the container should provide a robust method for preserving sessiondata within that application
109 Error Handling
1091 Request Attributes
A web application must be able to specify that when errors occur other resources in the applicationare used to provide the content body of the error response The specification of these resources is donein the deployment descriptor
If the location of the error handler is a servlet or a JSP page
bull The original unwrapped request and response objects created by the container are passed to theservlet or JSP page
bull The request path and attributes are set as if a RequestDispatcherforward to the error resource hadbeen performed
bull The request attributes in Table 10-1 ldquoRequest Attributes and their typesrdquo must be set
Table 10-1 Request Attributes and their types
Request Attributes Type
jakartaservleterrorstatus_code javalangInteger
jakartaservleterrorexception_type javalangClass
jakartaservleterrormessage javalangString
jakartaservleterrorexception javalangThrowable
jakartaservleterrorrequest_uri javalangString
jakartaservleterrorservlet_name javalangString
These attributes allow the servlet to generate specialized content depending on the status code theexception type the error message the exception object propagated and the URI of the requestprocessed by the servlet in which the error occurred (as determined by the getRequestURI call) and thelogical name of the servlet in which the error occurred
With the introduction of the exception object to the attributes list for version 23 of this specificationthe exception type and error message attributes are redundant They are retained for backwardscompatibility with earlier versions of the API
108 Replacing a Web Application
Final Jakarta Servlet Specification 103
1092 Error Pages
To allow developers to customize the appearance of content returned to a web client when a servletgenerates an error the deployment descriptor defines a list of error page descriptions The syntaxallows the configuration of resources to be returned by the container either when a servlet or filtercalls sendError on the response for specific status codes or if the servlet generates an exception orerror that propagates to the container
If the sendError method is called on the response the container consults the list of error pagedeclarations for the web application that use the error-code syntax and attempts a match If there is amatch the container returns the resource as indicated by the location entry
A servlet or filter may throw the following exceptions during processing of a request
bull runtime exceptions or errors
bull ServletExceptions or subclasses thereof
bull IOExceptions or subclasses thereof
The web application may have declared error pages using the exception-type element In this case thecontainer matches the exception type by comparing the exception thrown with the list of error-pagedefinitions that use the exception-type element A match results in the container returning theresource indicated in the location entry The closest match in the class hierarchy wins
If no error-page declaration containing an exception-type fits using the class-hierarchy match and theexception thrown is a ServletException or subclass thereof the container extracts the wrappedexception as defined by the ServletExceptiongetRootCause method A second pass is made over theerror page declarations again attempting the match against the error page declarations but using thewrapped exception instead
Error-page declarations using the exception-type element in the deployment descriptor must be uniqueup to the class name of the exception-type Similarly error-page declarations using the error-codeelement must be unique in the deployment descriptor up to the status code
If an error-page element in the deployment descriptor does not contain an exception-type or an error-code element the error page is a default error page
The error page mechanism described does not intervene when errors occur when invoked using theRequestDispatcher or filterdoFilter method In this way a filter or servlet using the RequestDispatcherhas the opportunity to handle errors generated
If a servlet generates an error that is not handled by the error page mechanism as described above thecontainer must ensure to send a response with status 500
The default servlet and container will use the sendError method to send 4xx and 5xx status responsesso that the error mechanism may be invoked The default servlet and container will use the setStatusmethod for 2xx and 3xx responses and will not invoke the error page mechanism
109 Error Handling
104 Jakarta Servlet Specification Final
If the application is using asynchronous operations as described in Section 2333 ldquoAsynchronousprocessingrdquo it is the applicationrsquos responsibility to handle all errors in application created threads Thecontainer MAY take care of the errors from the thread issued via AsyncContextstart For handlingerrors that occur during AsyncContextdispatch see dispatch error handling
1093 Error Filters
The error page mechanism operates on the original unwrappedunfiltered request and responseobjects created by the container The mechanism described in Section 625 ldquoFilters and theRequestDispatcherrdquo may be used to specify filters that are applied before an error response isgenerated
1010 Welcome FilesApplication Developers can define an ordered list of partial URIs called welcome files in the webapplication deployment descriptor The deployment descriptor syntax for the list is described in theweb application deployment descriptor schema
The purpose of this mechanism is to allow the deployer to specify an ordered list of partial URIs for thecontainer to use for appending to URIs when there is a request for a URI that corresponds to adirectory entry in the WAR not mapped to a web component This kind of request is known as a validpartial request
The use for this facility is made clear by the following common example A welcome file of indexhtmlcan be defined so that a request to a URL like hostportwebappdirectory where directory is an entryin the WAR that is not mapped to a servlet or JSP page is returned to the client ashostportwebappdirectoryindexhtml
If a web container receives a valid partial request the web container must examine the welcome filelist defined in the deployment descriptor The welcome file list is an ordered list of partial URLs withno trailing or leading The web server must append each welcome file in the order specified in thedeployment descriptor to the partial request and check whether a static resource in the WAR ismapped to that request URI If no match is found the web server MUST again append each welcomefile in the order specified in the deployment descriptor to the partial request and check if a servlet ismapped to that request URI The web container must send the request to the first resource in the WARthat matches The container may send the request to the welcome resource with a forward a redirector a container specific mechanism that is indistinguishable from a direct request
If no matching welcome file is found in the manner described the container may handle the request ina manner it finds suitable For some configurations this may mean returning a directory listing or forothers returning a 404 response
Consider a web application where
bull The deployment descriptor lists the following welcome files
1010 Welcome Files
Final Jakarta Servlet Specification 105
ltwelcome-file-listgt ltwelcome-filegtindexhtmlltwelcome-filegt ltwelcome-filegtdefaultjspltwelcome-filegtltwelcome-file-listgt
bull The static content in the WAR is as follows
fooindexhtmlfoodefaultjspfooorderformhtmlfoohomegifcatalogdefaultjspcatalogproductsshopjspcatalogproductsregisterjsp
bull A request URI of foo will be redirected to a URI of foo
bull A request URI of foo will be returned as fooindexhtml
bull A request URI of catalog will be redirected to a URI of catalog
bull A request URI of catalog will be returned as catalogdefaultjsp
bull A request URI of catalogindexhtml will cause a 404 not found
bull A request URI of catalogproducts will be redirected to a URI of catalogproducts
bull A request URI of catalogproducts will be passed to the ldquodefaultrdquo servlet if any If no ldquodefaultrdquoservlet is mapped the request may cause a 404 not found may cause a directory listing includingshopjsp and registerjsp or may cause other behavior defined by the container See Section 122ldquoSpecification of Mappingsrdquo for the definition of ldquodefaultrdquo servlet
bull All of the above static content can also be packaged in a JAR file with the content listed abovepackaged in the META-INFresources directory of the jar file The JAR file can then be included in theWEB-INFlib directory of the web application
1011 Web Application EnvironmentServlet containers that are not part of a Jakarta EE technology-compliant implementation areencouraged but not required to implement the application environment functionality described inSection 1522 ldquoWeb Application Environmentrdquo and the Jakarta EE specification If they do notimplement the facilities required to support this environment upon deploying an application thatrelies on them the container should provide a warning
1011 Web Application Environment
106 Jakarta Servlet Specification Final
1012 Web Application DeploymentWhen a web application is deployed into a container the following steps must be performed in thisorder before the web application begins processing client requests
bull Instantiate an instance of each event listener identified by a ltlistenergt element in the deploymentdescriptor
bull For instantiated listener instances that implement ServletContextListener call thecontextInitialized() method
bull Instantiate an instance of each filter identified by a ltfiltergt element in the deployment descriptorand call each filter instancersquos init() method
bull Instantiate an instance of each servlet identified by a ltservletgt element that includes a ltload-on-startupgt element in the order defined by the load-on-startup element values and call each servletinstancersquos init() method
1013 Inclusion of a webxml Deployment DescriptorA web application is NOT required to contain a webxml if it does NOT contain any servlet filter orlistener components or is using annotations to declare the same In other words an applicationcontaining only static files or JSP pages does not require a webxml to be present
[6] See the Jakarta Server Pages specification available from httpsjakartaeespecificationspages
1012 Web Application Deployment
Final Jakarta Servlet Specification 107
1013 Inclusion of a webxml Deployment Descriptor
108 Jakarta Servlet Specification Final
Chapter 11 Application Lifecycle Events
111 IntroductionThe application events facility gives the Application Developer greater control over the lifecycle of theServletContext and HttpSession and ServletRequest allows for better code factorization and increasesefficiency in managing the resources that the web application uses
112 Event ListenersApplication event listeners are classes that implement one or more of the servlet event listenerinterfaces They are instantiated and registered in the web container at the time of the deployment ofthe web application They are provided by the Application Developer in the WAR
Servlet event listeners support event notifications for state changes in the ServletContext HttpSessionand ServletRequest objects Servlet context listeners are used to manage resources or state held at aJVM level for the application HTTP session listeners are used to manage state or resources associatedwith a series of requests made into a web application from the same client or user Servlet requestlisteners are used to manage state across the lifecycle of servlet requests Async listeners are used tomanage async events such as time outs and completion of async processing
There may be multiple listener classes listening to each event type and the Application Developer mayspecify the order in which the container invokes the listener beans for each event type
1121 Event Types and Listener Interfaces
Events types and the listener interfaces used to monitor them are shown in the following tables
Table 11-1 Servlet Context Events
Event Type Description Listener Interface
Lifecycle The servlet context has just beencreated and is available to serviceits first request or the servletcontext is about to be shut down
jakartaservletServletContextListener
Changes to attributes Attributes on the servlet contexthave been added removed orreplaced
jakartaservlet
ServletContextAttributeListener
Table 11-2 HTTP Session Events
Event Type Description Listener Interface
Lifecycle An HttpSession has been createdinvalidated or timed out
jakartaservlethttp
HttpSessionListener
111 Introduction
Final Jakarta Servlet Specification 109
Event Type Description Listener Interface
Changes to attributes Attributes have been addedremoved or replaced on anHttpSession
jakartaservlethttp
HttpSessionAttributeListener
Changes to id The id of HttpSession has beenchanged
jakartaservlethttp
HttpSessionIdListener
Session migration HttpSession has been activated orpassivated
jakartaservlethttp
HttpSessionActivationListener
Object binding Object has been bound to orunbound from HttpSession
jakartaservlethttp
HttpSessionBindingListener
Table 11-3 Table 11-3 Servlet Request Events
Event Type Description Listener Interface
Lifecycle A servlet request has started beingprocessed by web components
jakartaservletServletRequestListener
Changes to attributes Attributes have been addedremoved or replaced on aServletRequest
jakartaservlet
ServletRequestAttributeListener
Async events A timeout connection terminationor completion of async processing
jakartaservletAsyncListener
For details of the API refer to the API reference
1122 An Example of Listener Use
To illustrate a use of the event scheme consider a simple web application containing a number ofservlets that make use of a database The Application Developer has provided a servlet context listenerclass for management of the database connection
1 When the application starts up the listener class is notified The application logs on to the databaseand stores the connection in the servlet context
2 Servlets in the application access the connection as needed during activity in the web application
3 When the web server is shut down or the application is removed from the web server the listenerclass is notified and the database connection is closed
113 Listener Class Configuration
1131 Provision of Listener Classes
The Application Developer of the web application provides listener classes implementing one or more
113 Listener Class Configuration
110 Jakarta Servlet Specification Final
of the listener interfaces in the jakartaservlet API Each listener class must have a public constructortaking no arguments The listener classes are packaged into the WAR either under the WEB-INFclassesarchive entry or inside a JAR in the WEB-INFlib directory
1132 Deployment Declarations
Listener classes are declared in the web application deployment descriptor using the listener elementThey are listed by class name in the order in which they are to be invoked Unlike other listenerslisteners of type AsyncListener may only be registered (with a ServletRequest) programmatically
1133 Listener Registration
The web container creates an instance of each listener class and registers it for event notificationsprior to the processing of the first request by the application The web container registers the listenerinstances according to the interfaces they implement and the order in which they appear in thedeployment descriptor During web application execution listeners for the given events are mostlyinvoked in their registration orders but there are some exceptions For instanceHttpSessionListenerdestroy are invoked in reverse order See Section 823 ldquoAssembling theDescriptor from webxml web-fragmentxml and Annotationsrdquo for details
1134 Notifications At Shutdown
On application shutdown listeners are notified in reverse order to their declarations with notificationsto session listeners preceding notifications to context listeners Session listeners must be notified ofsession invalidations prior to context listeners being notified of application shutdown
114 Deployment Descriptor ExampleThe following example is the deployment grammar for registering two servlet context lifecyclelisteners and an HttpSession listener
Suppose that comexampleMyConnectionManager and comexampleMyLoggingModule both implementjakartaservletServletContextListener and that comexampleMyLoggingModule additionallyimplements jakartaservlethttpHttpSessionListener Also the Application Developer wantscomexampleMyConnectionManager to be notified of servlet context lifecycle events beforecomexampleMyLoggingModule Here is the deployment descriptor for this application
114 Deployment Descriptor Example
Final Jakarta Servlet Specification 111
webxml
ltweb-appgt ltdisplay-namegtMyListeningApplicationltdisplay-namegt ltlistenergt ltlistener-classgtcomexampleMyConnectionManagerltlistener-classgt ltlistenergt
ltlistenergt ltlistener-classgtcomexampleMyLoggingModuleltlistener-classgt ltlistenergt
ltservletgt ltdisplay-namegtRegistrationServletltdisplay-namegt ltservletgtltweb-appgt
115 Listener Instances and ThreadingThe container is required to complete instantiation of the listener classes in a web application prior tothe start of execution of the first request into the application The container must maintain a referenceto each listener instance until the last request is serviced for the web application
Attribute changes to ServletContext and HttpSession objects may occur concurrently The container isnot required to synchronize the resulting notifications to attribute listener classes Listener classes thatmaintain state are responsible for the integrity of the data and should handle this case explicitly
116 Listener ExceptionsApplication code inside a listener may throw an exception during operation Some listenernotifications occur under the call tree of another component in the application An example of this is aservlet that sets a session attribute where the session listener throws an unhandled exception Thecontainer must allow unhandled exceptions to be handled by the error page mechanism described inSection 109 ldquoError Handlingrdquo If there is no error page specified for those exceptions the containermust ensure to send a response back with status 500 In this case no more listeners under that eventare called
Some exceptions do not occur under the call stack of another component in the application Anexample of this is a SessionListener that receives a notification that a session has timed out and throwsan unhandled exception or of a ServletContextListener that throws an unhandled exception during anotification of servlet context initialization or of a ServletRequestListener that throws an unhandledexception during a notification of the initialization or the destruction of the request object In this casethe Application Developer has no opportunity to handle the exception The container may respond toall subsequent requests to the web application with an HTTP status code 500 to indicate an application
115 Listener Instances and Threading
112 Jakarta Servlet Specification Final
error
Developers wishing normal processing to occur after a listener generates an exception must handletheir own exceptions within the notification methods
117 Distributed ContainersIn distributed web containers HttpSession instances are scoped to the particular JVM servicing sessionrequests and the ServletContext object is scoped to the web containerrsquos JVM Distributed containersare not required to propagate either servlet context events or HttpSession events to other JVMsListener class instances are scoped to one per deployment descriptor declaration per JVM
118 Session EventsListener classes provide the Application Developer with a way of tracking sessions within a webapplication It is often useful in tracking sessions to know whether a session became invalid becausethe container timed out the session or because a web component within the application called theinvalidate method The distinction may be determined indirectly using listeners and the HttpSessionAPI methods
117 Distributed Containers
Final Jakarta Servlet Specification 113
118 Session Events
114 Jakarta Servlet Specification Final
Chapter 12 Mapping Requests to ServletsThe mapping techniques described in this chapter are required for web containers mapping clientrequests to servlets
121 Use of URL PathsUpon receipt of a client request the web container determines the web application to which toforward it The web application selected must have the longest context path that matches the start ofthe request URL The matched part of the URL is the context path when mapping to servlets Therequest URL is decoded as a UTF-8 encoded string Implementations may provide container vendorspecific configuration to change this encoding or enable more fine-grained encoding such as using adifferent encoding for the path and query string portions of the URL Note that the encoding used toprocess the remainder of the request after the URL can be configured as specified in Section 312ldquoRequest Data Encodingrdquo
The web container next must locate the servlet to process the request using the path mappingprocedure described below
The path used for mapping to a servlet is the request URL from the request object minus the contextpath and the path parameters The URL path mapping rules below are used in order The firstsuccessful match is used with no further matches attempted
1 The container will try to find an exact match of the path of the request to the path of the servlet Asuccessful match selects the servlet
2 The container will recursively try to match the longest path-prefix This is done by stepping downthe path tree a directory at a time using the character as a path separator The longest matchdetermines the servlet selected
3 If the last segment in the URL path contains an extension (eg jsp) the servlet container will try tomatch a servlet that handles requests for the extension An extension is defined as the part of thelast segment after the last character
4 If neither of the previous three rules result in a servlet match the container will attempt to servecontent appropriate for the resource requested If a default servlet is defined for the applicationit will be used Many containers provide an implicit default servlet for serving content
The container must use case-sensitive string comparisons for matching
122 Specification of MappingsIn the web application deployment descriptor the following syntax is used to define mappings
bull A string beginning with a character and ending with a suffix is used for path mapping
bull A string beginning with a prefix is used as an extension mapping
121 Use of URL Paths
Final Jakarta Servlet Specification 115
bull The empty string () is a special URL pattern that exactly maps to the applicationrsquos context rootie requests of the form httphostportltcontext-rootgt In this case the path info is and theservlet path and context path is empty string ()
bull A string containing only the character indicates the default servlet of the application In thiscase the servlet path is the request URI minus the context path and the path info is null
bull All other strings are used for exact matches only
If the effective webxml (after merging information from fragments and annotations) contains any url-patterns that are mapped to multiple servlets then the deployment must fail
1221 Implicit Mappings
If the container has an internal JSP container the jsp extension is mapped to it allowing JSP pages tobe executed on demand This mapping is termed an implicit mapping If a jsp mapping is defined bythe web application its mapping takes precedence over the implicit mapping
A servlet container is allowed to make other implicit mappings as long as explicit mappings takeprecedence For example an implicit mapping of shtml could be mapped to include functionality onthe server
1222 Example Mapping Set
Consider the following set of mappings
Table 12-1 Example Set of Maps
Path Pattern Servlet
foobar servlet1
baz servlet2
catalog servlet3
bop servlet4
The following behavior would result
Table 12-2 Incoming Paths Applied to Example Maps
Incoming Path Servlet Handling Request
foobarindexhtml servlet1
foobarindexbop servlet1
baz servlet2
bazindexhtml servlet2
catalog servlet3
catalogindexhtml default servlet
catalogracecarbop servlet4
122 Specification of Mappings
116 Jakarta Servlet Specification Final
Incoming Path Servlet Handling Request
indexbop servlet4
Note that in the case of catalogindexhtml and catalogracecarbop the servlet mapped to catalogis not used because the match is not exact
123 Runtime Discovery of MappingsEvery mapping that causes a servlet to be activated regardless of whether or not servlet filters areinvolved is discoverable at runtime via the servlet mapping API
1231 Runtime Discovery of Servlet Mappings
The method getHttpServletMapping() on HttpServletRequest returns an HttpServletMapping
implementation that provides information for the mapping that caused the current Servlet to beinvoked Please see the javadocs for the normative specification Please see sections Section 931ldquoIncluded Request Parametersrdquo Section 942 ldquoForwarded Request Parametersrdquo and Section 972ldquoDispatched Request Parametersrdquo for relevant request attributes As with the included and forwardedrequest parameters the HttpServletMapping is not available for servlets that have been obtained with acall to ServletContextgetNamedDispatcher()
123 Runtime Discovery of Mappings
Final Jakarta Servlet Specification 117
123 Runtime Discovery of Mappings
118 Jakarta Servlet Specification Final
Chapter 13 SecurityWeb applications are created by Application Developers who give sell or otherwise transfer theapplication to a Deployer for installation into a runtime environment Application Developerscommunicate the security requirements to the Deployers and the deployment system This informationmay be conveyed declaratively via the applicationrsquos deployment descriptor by using annotationswithin the application code or programmatically via the setServletSecurity method of theServletRegistrationDynamic interface
This chapter describes the servlet container security mechanisms and interfaces and the deploymentdescriptor annotation and programmatic mechanisms for conveying the security requirements ofapplications
131 IntroductionA web application contains resources that can be accessed by many users These resources oftentraverse unprotected open networks such as the Internet In such an environment a substantialnumber of web applications will have security requirements
Although the quality assurances and implementation details may vary servlet containers havemechanisms and infrastructure for meeting these requirements that share some of the followingcharacteristics
Authentication
The means by which communicating entities prove to one another that they are acting on behalf ofspecific identities that are authorized for access
Access control for resources
The means by which interactions with resources are limited to collections of users or programs forthe purpose of enforcing integrity confidentiality or availability constraints
Data Integrity
The means used to prove that information has not been modified by a third party while in transit
Confidentiality or Data Privacy
The means used to ensure that information is made available only to users who are authorized toaccess it
132 Declarative SecurityDeclarative security refers to the means of expressing an applicationrsquos security model or requirementsincluding roles access control and authentication requirements in a form external to the applicationThe deployment descriptor is the primary vehicle for declarative security in web applications
131 Introduction
Final Jakarta Servlet Specification 119
The Deployer maps the applicationrsquos logical security requirements to a representation of the securitypolicy that is specific to the runtime environment At runtime the servlet container uses the securitypolicy representation to enforce authentication and authorization
The security model applies to the static content part of the web application and to servlets and filterswithin the application that are requested by the client The security model does not apply when aservlet uses the RequestDispatcher to invoke a static resource or servlet using a forward or an include
133 Programmatic SecurityProgrammatic security is used by security aware applications when declarative security alone is notsufficient to express the security model of the application Programmatic security consists of thefollowing methods of the HttpServletRequest interface
bull authenticate
bull login
bull logout
bull getRemoteUser
bull isUserInRole
bull getUserPrincipal
The login method allows an application to perform username and password collection (as analternative to Form-Based Login)
The authenticate methods allow an application to instigate authentication of the request caller by thecontainer from within an unconstrained request context
The logout method is provided to allow an application to reset the caller identity of a request
The getRemoteUser method returns the name of the remote user (that is the caller) associated by thecontainer with the request
The isUserInRole method determines if the remote user (that is the caller) associated with the requestis in a specified security role
The getUserPrincipal method determines the principal name of the remote user (that is the caller) andreturns a javasecurityPrincipal object corresponding to the remote user Calling the getName methodon the Principal returned by getUserPrincipal returns the name of the remote user These APIs allowservlets to make business logic decisions based on the information obtained
If no user has been authenticated the getRemoteUser method returns null the isUserInRole methodalways returns false and the getUserPrincipal method returns null
The isUserInRole method takes a String argument that references an application role For each distinctrole reference used in a call to isUserInRole A security-role-ref element with role-name corresponding
133 Programmatic Security
120 Jakarta Servlet Specification Final
to the role reference should be declared in the deployment descriptor Each security-role-ref shouldcontain a role-link sub-element whose value is the name of the application security role to which theapplication embedded role reference is linked The container uses the security-role-ref with role-nameequal to the role reference to determine which security-role to test the user for membership in
For example to map the security role reference FOO to the security role with role-name managerthe syntax would be
ltsecurity-role-refgt ltrole-namegtFOOltrole-namegt ltrole-linkgtmanagerltrole-linkgtltsecurity-role-refgt
In this case if a servlet called by a user belonging to the manager security role were to callisUserInRole(FOO) the result would be true
If no matching security-role-ref exists for a role reference used in a call to isUserInRole the containermust default to testing the user for membership in the security-role with role-name equal to the rolereference used in the call
The role name should never be used as an argument in calling isUserInRole Any call toisUserInRole with must return false If the role-name of the security-role to be tested is andthe application has NOT declared an application security-role with role-name isUserInRole mustonly return true if the user has been authenticated that is only when getRemoteUser andgetUserPrincipal would both return a non-null value Otherwise the container must check the user formembership in the application role
The declaration of security-role-ref elements informs the deployer of the role references used by theapplication and for which mappings must be defined
134 Programmatic Security Policy ConfigurationThis section defines the annotations and APIs provided to configure the security constraints enforcedby the servlet container
1341 ServletSecurity Annotation
The ServletSecurity annotation provides an alternative mechanism for defining access controlconstraints equivalent to those that could otherwise have been expressed declaratively via security-constraint elements in the portable deployment descriptor or programmatically via thesetServletSecurity method of the ServletRegistration interface Servlet containers MUST support theuse of the ServletSecurity annotation on classes (and subclasses thereof) that implement thejakartaservletServlet interface
134 Programmatic Security Policy Configuration
Final Jakarta Servlet Specification 121
package jakartaservletannotation
InheritedDocumentedTarget(value=TYPE)Retention(value=RUNTIME)public interface ServletSecurity HttpConstraint value() HttpMethodConstraint[] httpMethodConstraints()
TABLE 13-1 The ServletSecurity Interface
Element Description Default
value the HttpConstraint that defines the protection tobe applied to all HTTP methods that are NOTrepresented in the array returned byhttpMethodConstraints
HttpConstraint
httpMethodConstraints the array of HTTP method specific constraints
HttpConstraint
The HttpConstraint annotation is used within the ServletSecurity annotation to represent thesecurity constraint to be applied to all HTTP protocol methods for which a correspondingHttpMethodConstraint does NOT occur within the ServletSecurity annotation
For the special case where an HttpConstraint that returns all default values [7] occurs in combinationwith at least one HttpMethodConstraint that returns other than all default values the HttpConstraintrepresents that no security constraint is to be applied to any of the HTTP protocol methods to which asecurity constraint would otherwise apply This exception is made to ensure that such potentially non-specific uses of HttpConstraint do not yield constraints that will explicitly establish unprotected accessfor such methods given that they would not otherwise be covered by a constraint
package jakartaservletannotation
DocumentedRetention(value=RUNTIME)public interface HttpConstraint ServletSecurityEmptyRoleSemantic value() javalangString[] rolesAllowed() ServletSecurityTransportGuarantee transportGuarantee()
TABLE 13-2 The HttpConstraint Interface
134 Programmatic Security Policy Configuration
122 Jakarta Servlet Specification Final
Element Description Default
value The default authorization semantic that applies(only) when rolesAllowed returns an-empty array
PERMIT
rolesAllowed An array containing the names of the authorizedroles
transportGuarantee The data protection requirements that must besatisfied by the connections on which requestsarrive
NONE
HttpMethodConstraint
The HttpMethodConstraint annotation is used within the ServletSecurity annotation to representsecurity constraints on specific HTTP protocol messages
package jakartaservletannotation
DocumentedRetention(value=RUNTIME)public interface HttpMethodConstraint ServletSecurityEmptyRoleSemantic value() javalangString[] rolesAllowed() ServletSecurityTransportGuarantee transportGuarantee()
TABLE 13-3 The HttpMethodConstraint Interface
Element Description Default
value The HTTP protocol method name
emptyRoleSemantic The default authorization semantic that applies(only) when rolesAllowed returns an empty array
PERMIT
rolesAllowed An array containing the names of the authorizedroles
transportGuarantee The data protection requirements that must besatisfied by the connections on which requestsarrive
NONE
The ServletSecurity annotation may be specified on (that is targeted to) a Servlet implementationclass and its value is inherited by subclasses according to the rules defined for the Inherited meta-annotation At most one instance of the ServletSecurity annotation may occur on a servletimplementation class and the ServletSecurity annotation MUST NOT be specified on (that is targetedto) a Java method
When one or more HttpMethodConstraint annotations are defined within a ServletSecurity
134 Programmatic Security Policy Configuration
Final Jakarta Servlet Specification 123
annotation each HttpMethodConstraint defines the security-constraint that applies to the HTTPprotocol method identified within the HttpMethodConstraint Except for the case where itsHttpConstraint returns all default values and where it contains at least one HttpMethodConstraintthat returns other than all default values the ServletSecurity annotation defines another security-constraint that applies to all HTTP protocol methods for which a corresponding HttpMethodConstrainthas not been defined
The security-constraint elements defined in the portable deployment descriptors are authoritative forall the url-patterns occurring within the constraints
When a security-constraint in the portable deployment descriptor includes a url-pattern that is anexact match for a pattern mapped to a class annotated with ServletSecurity the annotation musthave no effect on the constraints enforced by the servlet container on the pattern
When metadata-complete=true is defined for a portable deployment descriptor the ServletSecurityannotation does not apply to any of the url-patterns mapped to (any servlet mapped to) the annotatedclass in the deployment descriptor
The ServletSecurity annotation is not applied to the url-patterns of a ServletRegistration createdusing the addServlet(String Servlet) method of the ServletContext interface unless the Servlet wasconstructed by the createServlet method of the ServletContext interface
With the exceptions listed above when a servlet class is annotated with ServletSecurity theannotation defines the security constraints that apply to all the url-patterns mapped to all the servletsmapped to the class
When a class has not been annotated with the ServletSecurity annotation the access policy that isapplied to a servlet mapped from that class is established by the applicable security-constraintelements if any in the corresponding portable deployment descriptor or barring any such elementsby the constraints if any established programmatically for the target servlet via thesetServletSecurity method of the ServletRegistration interface
13411 Examples
The following examples demonstrate the use of the ServletSecurity annotation
for all HTTP methods no constraints
ServletSecuritypublic class Example1 extends HttpServlet
134 Programmatic Security Policy Configuration
124 Jakarta Servlet Specification Final
for all HTTP methods no auth-constraint confidential transport required
ServletSecurity(HttpConstraint(transportGuarantee = TransportGuaranteeCONFIDENTIAL))public class Example2 extends HttpServlet
for all HTTP methods all access denied
ServletSecurity(HttpConstraint(EmptyRoleSemanticDENY))public class Example3 extends HttpServlet
for all HTTP methods auth-constraint requiring membership in Role R1
ServletSecurity(HttpConstraint(rolesAllowed = R1))public class Example4 extends HttpServlet
for All HTTP methods except GET and POST no constraints for methods GET and POST auth-constraintrequiring membership in Role R1 for POST confidential transport required
ServletSecurity((httpMethodConstraints = HttpMethodConstraint(value = GET rolesAllowed = R1) HttpMethodConstraint(value = POST rolesAllowed = R1 transportGuarantee = TransportGuaranteeCONFIDENTIAL))public class Example5 extends HttpServlet
for all HTTP methods except GET auth-constraint requiring membership in Role R1 for GET no constraints
ServletSecurity(value = HttpConstraint(rolesAllowed = R1) httpMethodConstraints = HttpMethodConstraint(GET))public class Example6 extends HttpServlet
for all HTTP methods except TRACE
auth-constraint requiring membership in Role R1 for TRACE all access denied
134 Programmatic Security Policy Configuration
Final Jakarta Servlet Specification 125
ServletSecurity(value = HttpConstraint(rolesAllowed = R1) httpMethodConstraints = HttpMethodConstraint(value=TRACE emptyRoleSemantic = EmptyRoleSemanticDENY))public class Example7 extends HttpServlet
13412 Mapping ServletSecurity to security-constraint
This section describes the mapping of the ServletSecurity annotation to its equivalent representationas security-constraint elements It is provided to facilitate enforcement using the existing security-constraint enforcement mechanism of the container The enforcement by servlet containers of theServletSecurity annotation must be equivalent in effect to enforcement by the container of thesecurity-constraint elements resulting from the mapping defined in this section
The ServletSecurity annotation is used to define one method-independent HttpConstraint followedby a list of zero or more HttpMethodConstraint specifications The method-independent constraint isapplied to all HTTP methods for which no HTTP method-specific constraint has been defined
When no HttpMethodConstraint elements are included a ServletSecurity annotation corresponds to asingle security-constraint element containing a web-resource-collection that contains no http-methodelements and thus pertains to all HTTP methods
The following example depicts the representation of a ServletSecurity annotation with no containedHttpMethodConstraint annotations as a single security-constraint element The url-pattern elementsdefined by the corresponding servlet (registration) would be included in the web-resource-collectionand the presence and value of any contained auth-constraint and user-data-constraint elementswould be determined by the mapping of the HttpConstraint value as defined in Section 13413ldquoMapping HttpConstraint and HttpMethodConstraint to XMLrdquo
mapping ServletSecurity with no contained HttpMethodConstraint
ServletSecurity(HttpConstraint(rolesAllowed = Role1))
ltsecurity-constraintgt ltweb-resource-collectiongt lturl-patterngtlturl-patterngt ltweb-resource-collectiongt ltauth-constraintgt ltrole-namegtRole1ltrole-namegt ltauth-constraintgtltsecurity-constraintgt
When one or more HttpMethodConstraint elements are specified the method-independent constraint
134 Programmatic Security Policy Configuration
126 Jakarta Servlet Specification Final
corresponds to a single security-constraint containing a web-resource-collection that contains onhttp-method-omission for each of the HTTP methods named in the HttpMethodConstraint elements Thesecurity-constraint containing http-method-omission elements must NOT be created if the method-independent constraint returns all default values and at least one HttpMethodConstraint does not EachHttpMethodConstraint corresponds to another security-constraint containing a web-resource-
collection containing an http-method element naming the corresponding HTTP method
The following example depicts the mapping of a ServletSecurity annotation with a single containedHttpMethodConstraint to two security-constraint elements The url-pattern elements defined by thecorresponding servlet (registration) would be included in the web-resource-collection of bothconstraints and the presence and value of any contained auth-constraint and user-data-constraintelements would be determined by the mapping of the associated HttpConstraint andHttpMethodConstraint values as defined in Section 13413 ldquoMapping HttpConstraint andHttpMethodConstraint to XMLrdquo
mapping ServletSecurity with contained HttpMethodConstraint
ServletSecurity(value=HttpConstraint(rolesAllowed = Role1) httpMethodConstraints = HttpMethodConstraint(value = TRACE emptyRoleSemantic = EmptyRoleSemanticDENY))
ltsecurity-constraintgt ltweb-resource-collectiongt lturl-patterngtlturl-patterngt lthttp-method-omissiongtTRACElthttp-method-omissiongt ltweb-resource-collectiongt ltauth-constraintgt ltrole-namegtRole1ltrole-namegt ltauth-constraintgtltsecurity-constraintgtltsecurity-constraintgt ltweb-resource-collectiongt lturl-patterngtlturl-patterngt lthttp-methodgtTRACElthttp-methodgt ltweb-resource-collectiongt ltauth-constraintgtltsecurity-constraintgt
13413 Mapping HttpConstraint and HttpMethodConstraint to XML
This section describes the mapping of the HttpConstraint and HttpMethodConstraint annotation values(defined for use within ServletSecurity) to their corresponding auth-constraint and user-data-constraint representations These annotations share a common model for expressing the equivalent ofthe auth-constraint and user-data-constraint elements used within the portable deploymentdescriptor That model is composed of the following 3 elements
134 Programmatic Security Policy Configuration
Final Jakarta Servlet Specification 127
emptyRoleSemantic
The authorization semantic either PERMIT or DENY that applies when no roles are named inrolesAllowed The default value for this element is PERMIT and DENY is not supported in combinationwith a non-empty rolesAllowed list
rolesAllowed
A list containing the names of the authorized roles When this list is empty its meaning depends onthe value of the emptyRoleSemantic The role name has no special meaning when included in thelist of allowed roles When the special role name appears in rolesAllowed it indicates that userauthentication independent of role is required and sufficient The default value for this element isan empty list
transportGuarantee
The data protection requirements either NONE or CONFIDENTIAL that must be satisfied by theconnections on which requests arrive This element is equivalent in meaning to a user-data-constraint containing a transport-guarantee with the corresponding value The default value forthis element is NONE
The following examples depict the correspondence between the HttpConstraint model describedabove and auth-constraint and user-data-constraint elements in webxml
emptyRoleSemantic=PERMIT rolesAllowed= transportGuarantee=NONE
lt-- no constraints --gt
emptyRoleSemantic=PERMIT rolesAllowed= transportGuarantee=CONFIDENTIAL
ltuser-data-constraintgt lttransport-guaranteegtCONFIDENTIALlttransport-guaranteegtltuser-data-constraintgt
emptyRoleSemantic=PERMITrolesAllowed=Role1 transportGuarantee=NONE
ltauth-constraintgt ltsecurity-role-namegtRole1ltsecurity-role-namegtltauth-constraintgt
134 Programmatic Security Policy Configuration
128 Jakarta Servlet Specification Final
emptyRoleSemantic=PERMITrolesAllowed=Role1 transportGuarantee=CONFIDENTIAL
ltauth-constraintgt ltsecurity-role-namegtRole1ltsecurity-role-namegtltauth-constraintgtltuser-data-constraintgt lttransport-guaranteegtCONFIDENTIALlttransport-guaranteegtltuser-data-constraintgt
emptyRoleSemantic=DENY rolesAllowed= transportGuarantee=NONE
ltauth-constraintgt
emptyRoleSemantic=DENY rolesAllowed= transportGuarantee=CONFIDENTIAL
ltauth-constraintgtltuser-data-constraintgt lttransport-guaranteegtCONFIDENTIALlttransport-guaranteegtltuser-data-constraintgt
1342 setServletSecurity of ServletRegistrationDynamic
The setServletSecurity method may be used within a ServletContextListener to define the securityconstraints to be applied to the mappings defined for a ServletRegistration
CollectionltStringgt setServletSecurity(ServletSecurityElement arg)
The jakartaservletServletSecurityElement argument to setServletSecurity is analogous in structureand model to the ServletSecurity interface of the ServletSecurity annotation As such the mappingsdefined in Section 13412 ldquoMapping ServletSecurity to security-constraintrdquo apply analogously to themapping of a ServletSecurityElement with contained HttpConstraintElement andHttpMethodConstraintElement values to its equivalent security-constraint representation
The setServletSecurity method returns the (possibly empty) Set of URL patterns that are already theexact target of a security-constraint element in the portable deployment descriptor (and thus wereunaffected by the call)
This method throws an IllegalStateException if the ServletContext from which theServletRegistration was obtained has already been initialized
When a security-constraint in the portable deployment descriptor includes a url-pattern that is anexact match for a pattern mapped by a ServletRegistration calls to setServletSecurity on theServletRegistration must have no effect on the constraints enforced by the servlet container on thepattern
134 Programmatic Security Policy Configuration
Final Jakarta Servlet Specification 129
With the exceptions listed above and including when the servlet class is annotated withServletSecurity when setServletSecurity is called on a ServletRegistration it establishes the securityconstraints that apply to the url-patterns of the registration
135 RolesA security role is a logical grouping of users defined by the Application Developer or Assembler Whenthe application is deployed roles are mapped by a Deployer to principals or groups in the runtimeenvironment
A servlet container enforces declarative or programmatic security for the principal associated with anincoming request based on the security attributes of the principal This may happen in either of thefollowing ways
1 A deployer has mapped a security role to a user group in the operational environment The usergroups to which the calling principal belongs are retrieved from its security attributes Theprincipal is in the security role only if the principal belongs to the user group to which the securityrole has been mapped by the deployer
2 A deployer has mapped a security role to a principal name in a security policy domain In this casethe principal name of the calling principal is retrieved from its security attributes The principal isin the security role only if the principal name is the same as a principal name to which the securityrole was mapped
136 AuthenticationA web client can authenticate a user to a web server using one of the following mechanisms
bull HTTP Basic Authentication
bull HTTP Digest Authentication
bull HTTPS Client Authentication
bull Form Based Authentication
1361 HTTP Basic Authentication
HTTP Basic Authentication which is based on a username and password is the authenticationmechanism defined in RFC 7617 A web server requests a web client to authenticate the user As part ofthe request the web server passes the realm (a string) in which the user is to be authenticated The webclient obtains the username and the password from the user and transmits them to the web serverThe web server then authenticates the user in the specified realm
Basic Authentication is not a secure authentication protocol User passwords are sent in simple base64encoding and the target server is not authenticated Additional protection can alleviate some of theseconcerns a secure transport mechanism (HTTPS) or security at the network level (such as the IPSEC
135 Roles
130 Jakarta Servlet Specification Final
protocol or VPN strategies) is applied in some deployment scenarios
1362 HTTP Digest Authentication
Like HTTP Basic Authentication HTTP Digest Authentication authenticates a user based on a usernameand a password However unlike HTTP Basic Authentication HTTP Digest Authentication does notsend user passwords over the network In HTTP Digest authentication the client sends a one-waycryptographic hash of the password (and additional data) Although passwords are not sent on thewire HTTP Digest authentication requires that clear text password equivalents [8] be avaialble to theauthenticating container so that it can validate received authenticators by calculating the expecteddigest Servlet containers SHOULD support HTTP_DIGEST authentication
1363 Form Based Authentication
The look and feel of the ldquologin screenrdquo cannot be varied using the web browserrsquos built-inauthentication mechanisms This specification introduces a required form based authenticationmechanism which allows an Application 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 The loginform must contain fields for entering a username and a password These fields must be namedj_username and j_password respectively
When a user attempts to access a protected web resource the container checks the userrsquosauthentication If the user is authenticated and possesses authority to access the resource therequested web resource is activated and a reference to it is returned If the user is not authenticatedall of the following steps occur
1 The login form associated with the security constraint is sent to the client and the URL path andHTTP protocol method triggering the authentication is stored by the container
2 The user is asked to fill out the form including the username and password fields
3 The client posts the form back to the server
4 The container attempts to authenticate the user using the information from the form
5 If authentication fails the error page is returned using either a forward or a redirect and thestatus code of the response is set to 200 The error page contains information about the failure
6 If authentication succeeds the client is redirected to the resource using the store URL path
7 When the redirected and authenticated request arrives at the container the container restores therequest and HTTP protocol method and the authenticated userrsquos principal is checked to see if it isin an authorized role for accessing the resource
8 If the user is authorized the request is accepted for processing by the container
The HTTP protocol method of the redirected request that arrives in step 7 may differ from the HTTPmethod of the request that triggered the authentication As such following the redirection of step 6 theform authenticator must process the redirected request even if authentication is not required for the
136 Authentication
Final Jakarta Servlet Specification 131
HTTP method with which the request arrives To improve the predictability of the HTTP method of theredirected request containers should redirect (in step 6) using the 303 (SC_SEE_OTHER) status codeexcept where interoperability with HTTP10 user agents is required in which cases the 302 status codeshould be used
When conducted over an unprotected transport Form Based Authentication is subject to some of thesame vulnerabilities as Basic Authentication
When the request that is triggering authentication arrives over a secure transport or the login page issubject to a user-data-constraint of CONFIDENTIAL the login page must be returned to the user andsubmitted to the container over a secure transport
The login page should be subject to a user-data-constraint of CONFIDENTIAL and a user-data-constraintof CONFIDENTIAL should be included in every security-constraint that contains a requirement forauthentication
The login method of the HttpServletRequest interface provides an alternative means for an applicationto control the look and feel of its login screens
13631 Login Form Notes
Form based login and URL based session tracking can be problematic to implement Form based loginshould be used only when sessions are 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 bej_security_check This restriction is made so that the login form will work no matter which resource itis for and to avoid requiring the server to specify the action field of the outbound form The login formshould specify autocomplete=off on the password form field
Here is an example showing how the form should be coded into the HTML page
ltform method=POST action=j_security_checkgt ltinput type=text name=j_usernamegt ltinput type=password name=j_password autocomplete=offgtltformgt
If the form based login is invoked because of an HTTP request the original request parameters must bepreserved by the container for use if on successful authentication it redirects the call to the requestedresource
If the user is authenticated using form login and has created an HTTP session the timeout orinvalidation of that session leads to the user being logged out in the sense that subsequent requestsmust cause the user to be re-authenticated The scope of the logout is the same as that of theauthentication for example if the container supports single signon such as Jakarta EE technologycompliant web containers the user would need to reauthenticate with any of the web applicationshosted on the web container
136 Authentication
132 Jakarta Servlet Specification Final
1364 HTTPS Client Authentication
End user authentication using HTTPS (HTTP over SSL) is a strong authentication mechanism Thismechanism requires the client to possess a Public Key Certificate (PKC) Currently PKCs are useful in e-commerce applications and also for a single-signon from within the browser
1365 Additional Container Authentication Mechanisms
Servlet containers should provide public interfaces that may be used to integrate and configureadditional HTTP message layer authentication mechanisms for use by the container on behalf ofdeployed applications These interfaces should be offered for use by parties other than the containervendor (including application developers system administrators and system integrators)
To facilitate portable implementation and integration of additional container authenticationmechanisms it is recommended that all servlet containers implement the Servlet Container Profile ofThe Jakarta Authentication Specification The specification is available for download athttpsjakartaeespecificationsauthentication
137 Server Tracking of Authentication InformationAs the underlying security identities (such as users and groups) to which roles are mapped in aruntime environment are environment specific rather than application specific it is desirable to
1 Make login mechanisms and policies a property of the environment the web application isdeployed in
2 Be able to use the same authentication information to represent a principal to all applicationsdeployed in the same container and
3 Require re-authentication of users only when a security policy domain boundary has been crossed
Therefore a servlet container is required to track authentication information at the container level(rather than at the web application level) This allows users authenticated for one web application toaccess other resources managed by the container permitted to the same security identity
138 Specifying Security ConstraintsSecurity constraints are a declarative way of defining the protection of web content A securityconstraint associates authorization andor user data constraints with HTTP operations on webresources A security constraint represented as a security-constraint in a deployment descriptorconsists of the following elements
bull web resource collection (web-resource-collection in deployment descriptor)
bull authorization constraint (auth-constraint in deployment descriptor)
bull user data constraint (user-data-constraint in deployment descriptor)
137 Server Tracking of Authentication Information
Final Jakarta Servlet Specification 133
The HTTP operations and web resources to which a security constraint applies (ie the constrainedrequests) are identified by one or more web resource collections A web resource collection consists ofthe following elements
bull URL patterns (url-pattern in deployment descriptor)
bull HTTP methods (http-method or http-method-omission elements in the deployment descriptor)
An authorization constraint establishes a requirement for authentication and names the authorizationroles permitted to perform the constrained requests A user must be a member of at least one of thenamed roles to be permitted to perform the constrained requests The special role name is ashorthand for all role names defined in the deployment descriptor The special role name is ashorthand for any authenticated user independent of role When the special role name appears inan authorization constraint it indicates that any authenticated user independent of role is authorizedto perform the constrained requests An authorization constraint that names no roles indicates thataccess to the constrained requests must not be permitted under any circumstances An authorizationconstraint consists of the following element
bull role name (role-name in deployment descriptor)
A user data constraint establishes a requirement that the constrained requests be received over aprotected transport layer connection The strength of the required protection is defined by the value ofthe transport guarantee A transport guarantee of INTEGRAL is used to establish a requirement forcontent integrity and a transport guarantee of CONFIDENTIAL is used to establish a requirement forconfidentiality The transport guarantee of NONE indicates that the container must accept theconstrained requests when received on any connection including an unprotected one Containers mayimpose a confidential transport guarantee in response to the INTEGRAL value A user data constraintconsists of the following element
bull transport guarantee (transport-guarantee in deployment descriptor)
If no authorization constraint applies to a request the container must accept the request withoutrequiring user authentication If no user data constraint applies to a request the container must acceptthe request when received over any connection including an unprotected one
1381 Combining Constraints
For the purpose of combining constraints an HTTP method is said to occur within a web-resource-collection when no HTTP methods are named in the collection or the collection specifically names theHTTP method in a contained http-method element or the collection contains one or more http-method-omission elements none of which names the HTTP method
When a url-pattern and HTTP method pair occurs in combination( ie within a web-resource-collection) in multiple security constraints the constraints (on the pattern and method) are defined bycombining the individual constraints The rules for combining constraints in which the same patternand method occur are as follows
138 Specifying Security Constraints
134 Jakarta Servlet Specification Final
The combination of authorization constraints that name roles or that imply roles via the name shall yield the union of the role names in the individual constraints as permitted roles Anauthorization constraint that names the role shall combine with authorization constraints thatname or imply roles to permit any authenticated user independent of role A security constraint thatdoes not contain an authorization constraint shall combine with authorization constraints that nameor imply roles to allow unauthenticated access The special case of an authorization constraint thatnames no roles shall combine with any other constraints to override their affects and cause access tobe precluded
The combination of user-data-constraints that apply to a common url-pattern and http-method shallyield the union of connection types accepted by the individual constraints as acceptable connectiontypes A security constraint that does not contain a user-data-constraint shall combine with otheruser-data-constraint to cause the unprotected connection type to be an accepted connection type
1382 Example
The following example illustrates the combination of constraints and their translation into a table ofapplicable constraints Suppose that a deployment descriptor contained the following securityconstraints
ltsecurity-constraintgt ltweb-resource-collectiongt ltweb-resource-namegtprecluded methodsltweb-resource-namegt lturl-patterngtlturl-patterngt lturl-patterngtacmewholesalelturl-patterngt lturl-patterngtacmeretaillturl-patterngt lthttp-method-omissiongtGETlthttp-method-omissiongt lthttp-method-omissiongtPOSTlthttp-method-omissiongt ltweb-resource-collectiongt ltauth-constraintgtltsecurity-constraintgt
ltsecurity-constraintgt ltweb-resource-collectiongt ltweb-resource-namegtwholesaleltweb-resource-namegt lturl-patterngtacmewholesalelturl-patterngt lthttp-methodgtGETlthttp-methodgt lthttp-methodgtPUTlthttp-methodgt ltweb-resource-collectiongt ltauth-constraintgt ltrole-namegtSALESCLERKltrole-namegt ltauth-constraintgtltsecurity-constraintgt
ltsecurity-constraintgt ltweb-resource-collectiongt
138 Specifying Security Constraints
Final Jakarta Servlet Specification 135
ltweb-resource-namegtwholesale 2ltweb-resource-namegt lturl-patterngtacmewholesalelturl-patterngt lthttp-methodgtGETlthttp-methodgt lthttp-methodgtPOSTlthttp-methodgt ltweb-resource-collectiongt ltauth-constraintgt ltrole-namegtCONTRACTORltrole-namegt ltauth-constraintgt ltuser-data-constraintgt lttransport-guaranteegtCONFIDENTIALlttransport-guaranteegt ltuser-data-constraintgtltsecurity-constraintgt
ltsecurity-constraintgt ltweb-resource-collectiongt ltweb-resource-namegtretailltweb-resource-namegt lturl-patterngtacmeretaillturl-patterngt lthttp-methodgtGETlthttp-methodgt lthttp-methodgtPOSTlthttp-methodgt ltweb-resource-collectiongt
ltauth-constraintgt ltrole-namegtCONTRACTORltrole-namegt ltrole-namegtHOMEOWNERltrole-namegt ltauth-constraintgtltsecurity-constraintgt
The translation of this hypothetical deployment descriptor would yield the constraints defined in Table13-4 ldquoSecurity Constraint Tablerdquo
Table 13-4 Security Constraint Table
url-pattern http-method permitted roles supported connectiontypes
all methods except GETPOST
access precluded not constrained
acmewholesale all methods except GETPOST
access precluded not constrained
acmewholesale GET CONTRACTORSALESCLERK
not constrained
acmewholesale POST CONTRACTOR CONFIDENTIAL
acmeretail all methods except GETPOST
access precluded not constrained
138 Specifying Security Constraints
136 Jakarta Servlet Specification Final
url-pattern http-method permitted roles supported connectiontypes
acmeretail GET CONTRACTORHOMEOWNER
not constrained
acmeretail POST CONTRACTORHOMEOWNER
not constrained
1383 Processing Requests
When a servlet container receives a request it shall use the algorithm described in Section 121 ldquoUseof URL Pathsrdquo to select the constraints (if any) defined on the url-pattern that is the best match to therequest URI If no constraints are selected the container shall accept the request Otherwise thecontainer shall determine if the HTTP method of the request is constrained at the selected pattern If itis not the request shall be accepted Otherwise the request must satisfy the constraints that apply tothe HTTP method at the url-pattern Both of the following rules must be satisfied for the request to beaccepted and dispatched to the associated servlet
1 The characteristics of the connection on which the request was received must satisfy at least one ofthe supported connection types defined by the constraints If this rule is not satisfied the containershall reject the request and redirect it to the HTTPS port [9]
2 The authentication characteristics of the request must satisfy any authentication and rolerequirements defined by the constraints If this rule is not satisfied because access has beenprecluded (by an authorization constraint naming no roles) the request shall be rejected asforbidden and a 403 (SC_FORBIDDEN) status code shall be returned to the user If access isrestricted to permitted roles and the request has not been authenticated the request shall berejected as unauthorized and a 401 (SC_UNAUTHORIZED) status code shall be returned to causeauthentication If access is restricted to permitted roles and the authentication identity of therequest is not a member of any of these roles the request shall be rejected as forbidden and a 403(SC_FORBIDDEN) status code shall be returned to the user
1384 Uncovered HTTP Protocol Methods
The security-constraint schema provides the ability to enumerate (including by omission) the HTTPprotocol methods to which the protection requirements defined in a security-constraint apply WhenHTTP methods are enumerated within a security-constraint the protections defined by the constraintapply only to the methods established by the enumeration We refer to the HTTP methods that are notestablished by the enumeration as uncovered HTTP methods Uncovered HTTP methods are NOTprotected at all request URLs for which a url-pattern of the security-constraint is a best match
When HTTP methods are not enumerated within a security-constraint the protections defined by theconstraint apply to the complete set of HTTP (extension) methods In that case there are no uncoveredHTTP methods at all request URLs for which a url-pattern of the security-constraint is a best match
The examples that follow depict the three ways in which HTTP protocol methods may be left
138 Specifying Security Constraints
Final Jakarta Servlet Specification 137
uncovered The determination of whether methods are uncovered is made after all the constraints thatapply to a url-pattern have been combined as described in Section 1381 ldquoCombining Constraintsrdquo
1 A security-constraint names one or more HTTP methods in http-method elements All HTTPmethods other than those named in the constraint are uncovered
ltsecurity-constraintgt ltweb-resource-collectiongt ltweb-resource-namegtwholesaleltweb-resource-namegt lturl-patterngtacmewholesalelturl-patterngt lthttp-methodgtGETlthttp-methodgt ltweb-resource-collectiongt ltauth-constraintgt ltrole-namegtSALESCLERKltrole-namegt ltauth-constraintgtltsecurity-constraintgt
All HTTP Methods except GET are uncovered
2 A security-constraint names one or more HTTP methods in http-method-omission elements AllHTTP methods named in the constraint are uncovered
ltsecurity-constraintgt ltweb-resource-collectiongt ltweb-resource-namegtwholesaleltweb-resource-namegt lturl-patterngtacmewholesalelturl-patterngt lthttp-method-omissiongtGETlthttp-method-omissiongt ltweb-resource-collectiongt ltauth-constraintgtltsecurity-constraintgt
GET is uncovered All other methods are covered by the excluding auth-constraint
3 A ServletSecurity annotation includes an HttpConstraint that returns all default values and italso includes at least one HttpMethodConstraint that returns other than all default values All HTTPmethods other than those named in an HTTPMethodConstraint are uncovered by the annotationThis case is analogous to case 1 and equivalent use of the setServletSecurity method of theServletRegistration interface will also produce an analogous result
138 Specifying Security Constraints
138 Jakarta Servlet Specification Final
ServletSecurity((httpMethodConstraints = HttpMethodConstraint(value = GET rolesAllowed = R1) HttpMethodConstraint(value = POST rolesAllowed = R1 transportGuarantee = TransportGuaranteeCONFIDENTIAL) )public class Example5 extends HttpServlet
All HTTP Methods except GET and POST are uncovered
13841 Rules for Security Constraint Configuration
Objective Make sure all HTTP methods at all constrained URL patterns have the intended securityprotections (that is are covered)
1 Do not name HTTP methods in constraints in which case the security protections defined for theURL patterns will apply to all HTTP methods
2 If you canrsquot follow rule 1 add the ltdeny-uncovered-http-methodsgt and declare (using the lthttp-methodgt element or equivalent annotation) all the HTTP methods (with security protections) thatare to be allowed at the constrained URL patterns
3 If you canrsquot follow rule 2 declare constraints to cover all HTTP methods at each constrained URLpattern Use the lthttp-method-omissiongt element or the HttpMethodConstraint annotation torepresent the set of all HTTP methods other than those named by lthttp-methodgt orHttpMethodConstraint When using annotations use the HttpConstraint annotation to define thesecurity semantic to be applied to all other HTTP methods and configure EmptyRoleSemantic=DENY tocause all other HTTP methods to be denied
13842 Handling Uncovered HTTP Methods
During application deployment the container must inform the deployer of any uncovered HTTPmethods present in the application security constraint configuration resulting from the combination ofthe constraints defined for the application The provided information must identify the uncoveredHTTP protocol methods and the corresponding URL patterns at which the HTTP methods areuncovered The requirement to notify the deployer may be satisfied by logging the requiredinformation
When the deny-uncovered-http-methods flag is set in the webxml of an application the container mustdeny any HTTP protocol method when it is used with a request URL for which the HTTP method isuncovered at the combined security constraint that applies to the url-pattern that is the best match forthe request URL The denied request shall be rejected as forbidden and a 403 (SC_FORBIDDEN) statuscode shall be returned
To cause uncovered HTTP methods to be denied the deployment system should establish additional
138 Specifying Security Constraints
Final Jakarta Servlet Specification 139
excluding auth-constraints to cover these HTTP methods at the constrained url-patterns at which theHTTP methods are uncovered
When an applicationrsquos security configuration contains no uncovered methods the deny-uncovered-http-methods flag must have no effect on the effective security configuration of the application
Applying the deny-uncovered-http-methods flag to an application whose security configuration containsuncovered methods may in some cases deny access to resources that must be accessible in order forthe application to function In such cases the security configuration of the application should becompleted such that all uncovered methods are covered by an appropriate constraint configuration
Application Developers should define security constraint configurations that leave no HTTP methodsuncovered and they should set the deny-uncovered-http-methods flag to ensure that their applicationsdo not become dependent on being accessible via uncovered methods
A servlet container may provide a configurable option to select whether the default behavior foruncovered methods is ALLOW or DENY This option may be configured on a per-applicationgranularity or larger Note that setting this default to DENY may cause some applications to fail
139 Default PoliciesBy default authentication is not needed to access resources Authentication is required when thesecurity constraints (if any) that contain the url-pattern that is the best match for the request URIcombine to impose an auth-constraint (naming roles) on the HTTP method of the request Similarly aprotected transport is not required unless the security constraints that apply to the request combine toimpose a user-data-constraint (with a protected transport-guarantee) on the HTTP method of therequest
1310 Login and LogoutThe container establishes the caller identity of a request prior to dispatching the request to the servletengine The caller identity remains unchanged throughout the processing of the request or until theapplication sucessfully calls authenticate login or logout on the request For asynchronous requeststhe caller identity established at the initial dispatch remains unchanged until the processing of theoverall request completes or the application successfully calls authenticate login or logout on therequest
Being logged into an application during the processing of a request corresponds precisely to therebeing a valid non-null caller identity associated with the request as may be determined by callinggetRemoteUser or getUserPrincipal on the request A null return value from either of these methodsindicates that the caller is not logged into the application with respect to the processing of the request
Containers may create HTTP Session objects to track login state If a developer creates a session while auser is not authenticated and the container then authenticates the user the session visible todeveloper code after login must be the same session object that was created prior to login occurring so
139 Default Policies
140 Jakarta Servlet Specification Final
that there is no loss of session information
[7] From methods value() rolesAllowed() and transportGuarantee()[8] The password equivalents can be such that they can only be used to authenticate as the user at a specific realm[9] As an optimization a container should reject the request as forbidden and return a 403 (SC_FORBIDDEN) status code ifit knows that access will ultimately be precluded (by an authorization constraint naming no roles)
1310 Login and Logout
Final Jakarta Servlet Specification 141
1310 Login and Logout
142 Jakarta Servlet Specification Final
Chapter 14 Deployment DescriptorThis chapter specifies the Jakarta Servlet Specification requirements for web container support ofdeployment descriptors The deployment descriptor conveys the elements and configurationinformation of a web application between Application Developers Application Assemblers andDeployers
For Servlet 50 the deployment descriptor is defined in terms of an XML schema document
For backwards compatibility of applications written to previous versions of the API any deploymentdescriptors written to comply with earlier versions of the specification must still be supported suchthat applications continue to deploy For the actual XSD files please visit httpsjakartaeexmlnsjakartaee
141 Deployment Descriptor ElementsThe following types of configuration and deployment information are required to be supported in theweb application deployment descriptor for all servlet containers
bull ServletContext Init Parameters
bull Session Configuration
bull Servlet Declaration
bull Servlet Mappings
bull Application Lifecyle Listener classes
bull Filter Definitions and Filter Mappings
bull MIME Type Mappings
bull Welcome File list
bull Error Pages
bull Locale and Encoding Mappings
bull Security configuration including login-config security-constraint deny-uncovered-http-methodssecurity-role security-role-ref and run-as
142 Rules for Processing the Deployment DescriptorThis section lists some general rules that web containers and developers must note concerning theprocessing of the deployment descriptor for a web application
bull Web containers must remove all leading and trailing whitespace which is defined as S(whitespace) in XML 10 (httpwwww3orgTR2000WD-xml-2e-20000814) for the element content of thetext nodes of a deployment descriptor
141 Deployment Descriptor Elements
Final Jakarta Servlet Specification 143
bull The deployment descriptor must be valid against the schema Web containers and tools thatmanipulate web applications have a wide range of options for checking the validity of a WAR Thisincludes checking the validity of the deployment descriptor document held within
Additionally it is recommended that web containers and tools that manipulate web applicationsprovide a level of semantic checking For example it should be checked that a role referenced in asecurity constraint has the same name as one of the security roles defined in the deploymentdescriptor
In cases of non-conformant web applications tools and containers should inform the developerwith descriptive error messages High-end application server vendors are encouraged to supplythis kind of validity checking in the form of a tool separate from the container
bull The sub elements under web-app can be in an arbitrary order in this version of the specificationBecause of the restriction of XML Schema The multiplicity of the elements distributable session-config welcome-file-list jsp-config login-config and locale-encoding-mapping-list was changedfrom optional to 0 or more The containers must inform the developer with a descriptive errormessage when the deployment descriptor contains more than one element of session-config jsp-config and login-config The container must concatenate the items in welcome-file-list andlocale-encoding-mapping-list when there are multiple occurrences The multiple occurrence ofdistributable must be treated exactly in the same way as the single occurrence of distributable
bull URI paths specified in the deployment descriptor are assumed to be in URL-decoded form Thecontainers must inform the developer with a descriptive error message when URL contains CR(xD)or LF(xA) The containers must preserve all other characters including whitespace in URL
bull Containers must attempt to canonicalize paths in the deployment descriptor For example paths ofthe form ab must be interpreted as b Paths beginning or resolving to paths that begin with are not valid paths in the deployment descriptor
bull URI paths referring to a resource relative to the root of the WAR or a path mapping relative to theroot of the WAR unless otherwise specified should begin with a leading
bull In elements whose value is an enumerated type the value is case sensitive
143 Deployment DescriptorThe deployment descriptor for this revision of the specification is available at httpsjakartaeexmlnsjakartaeeweb-app_5_0xsd
144 ExamplesThe following examples illustrate the usage of the definitions listed in the deployment descriptorschema
143 Deployment Descriptor
144 Jakarta Servlet Specification Final
1441 A Basic Example
Basic Deployment Descriptor Example
ltxml version=10 encoding=UTF-8gtltweb-app xmlns=httpsjakartaeexmlnsjakartaee xmlnsxsi=httpwwww3org2001XMLSchema-instance xsischemaLocation=httpsjakartaeexmlnsjakartaee web-app_5_0xsd version=50gt
ltdisplay-namegtA Simple Applicationltdisplay-namegt
ltcontext-paramgt ltparam-namegtWebmasterltparam-namegt ltparam-valuegtwebmasterexamplecomltparam-valuegt ltcontext-paramgt
ltservletgt ltservlet-namegtcatalogltservlet-namegt ltservlet-classgtcomexampleCatalogServletltservlet-classgt ltinit-paramgt ltparam-namegtcatalogltparam-namegt ltparam-valuegtSpringltparam-valuegt ltinit-paramgt ltservletgt
ltservlet-mappinggt ltservlet-namegtcatalogltservlet-namegt lturl-patterngtcataloglturl-patterngt ltservlet-mappinggt
ltsession-configgt ltsession-timeoutgt30ltsession-timeoutgt ltsession-configgt
ltmime-mappinggt ltextensiongtpdfltextensiongt ltmime-typegtapplicationpdfltmime-typegt ltmime-mappinggt
ltwelcome-file-listgt ltwelcome-filegtindexjspltwelcome-filegt ltwelcome-filegtindexhtmlltwelcome-filegt ltwelcome-filegtindexhtmlltwelcome-filegt ltwelcome-file-listgt
lterror-pagegt
144 Examples
Final Jakarta Servlet Specification 145
lterror-codegt404lterror-codegt ltlocationgt404htmlltlocationgt lterror-pagegt
ltweb-appgt
1442 An Example of Security
Deployment Descriptor Example Using Security
ltxml version=10 encoding=UTF-8gt
ltweb-app xmlns=httpsjakartaeexmlnsjakartaee xmlnsxsi=httpwwww3org2001XMLSchema-instance xsischemaLocation=httpsjakartaeexmlnsjakartaee web-app_5_0xsd version=50gt
ltdisplay-namegtA Secure Applicationltdisplay-namegt
ltservletgt ltservlet-namegtcatalogltservlet-namegt ltservlet-classgtcomexampleCatalogServletltservlet-classgt ltinit-paramgt ltparam-namegtcatalogltparam-namegt ltparam-valuegtSpringltparam-valuegt ltinit-paramgt ltsecurity-role-refgt ltrole-namegtMGRltrole-namegt lt-- role name used in code --gt ltrole-linkgtmanagerltrole-linkgt ltsecurity-role-refgt ltservletgt
ltsecurity-rolegt ltrole-namegtmanagerltrole-namegt ltsecurity-rolegt
ltservlet-mappinggt ltservlet-namegtcatalogltservlet-namegt lturl-patterngtcataloglturl-patterngt ltservlet-mappinggt
ltsecurity-constraintgt ltweb-resource-collectiongt ltweb-resource-namegtSalesInfoltweb-resource-namegt lturl-patterngtsalesinfolturl-patterngt
144 Examples
146 Jakarta Servlet Specification Final
lthttp-methodgtGETlthttp-methodgt lthttp-methodgtPOSTlthttp-methodgt ltweb-resource-collectiongt ltauth-constraintgt ltrole-namegtmanagerltrole-namegt ltauth-constraintgt ltuser-data-constraintgt lttransport-guaranteegtCONFIDENTIALlttransport-guaranteegt ltuser-data-constraintgt ltsecurity-constraintgtltweb-appgt
144 Examples
Final Jakarta Servlet Specification 147
144 Examples
148 Jakarta Servlet Specification Final
Chapter 15 Requirements related to otherSpecificationsThis chapter lists the requirements for web containers that are included in products that also includeother Jakarta technologies
In the following sections any reference to Jakarta applies to not only the full Jakarta EE profile but alsoany profile that includes support for servlet like the Jakarta Web Profile For more information onprofiles please refer to the Jakarta EE Platform Specification
151 SessionsDistributed servlet containers that are part of a Jakarta EE Platform implementation must support themechanism necessary for migrating other Jakarta objects from one JVM to another
152 Web Applications
1521 Web Application Class Loader
Servlet containers that are part of a Jakarta EE Platform product should not allow the application tooverride Java SE or Jakarta EE platform classes such as those in java javax and jakartanamespaces that either Java SE or Jakarta EE do not allow to be modified
1522 Web Application Environment
The Jakarta EE Platform defines a naming environment that allows applications to easily accessresources and external information without explicit knowledge of how the external information isnamed or organized
As servlets are an integral component type of Jakarta technology provision has been made in the webapplication deployment descriptor for specifying information allowing a servlet to obtain references toresources and enterprise beans The deployment elements that contain this information are
bull env-entry
bull ejb-ref
bull ejb-local-ref
bull resource-ref
bull resource-env-ref
bull service-ref
bull message-destination-ref
151 Sessions
Final Jakarta Servlet Specification 149
bull persistence-context-ref
bull persistence-unit-ref
The developer uses these elements to describe certain objects that the web application requires to beregistered in the JNDI namespace in the web container at runtime
The requirements of the Jakarta environment with regard to setting up the environment are describedin Chapter 5 of the Jakarta EE Platform Specification
Servlet containers that are part of a Jakarta technology-compliant implementation are required tosupport this syntax Consult the Jakarta EE Platform Specification for more details This type of servletcontainer must support lookups of such objects and calls made to those objects when performed on athread managed by the servlet container This type of servlet container should support this behaviorwhen performed on threads created by the developer but are not currently required to do so Such arequirement may be added to a future version of this specification Developers are cautioned thatdepending on this capability for application-created threads is not recommended as it is non-portable
1523 JNDI Name for Web Module Context Root URL
The Jakarta EE Platform Specification defines a standardized global JNDI namespace and a series ofrelated namespaces that map to various scopes of a Jakarta application These namespaces can be usedby applications to portably retrieve references to components and resources This section defines theJNDI names by which the base url for a web application is required to be registered
The name of the pre-defined javanetURL resource for the context root of a web application has thefollowing syntax
javaglobal[ltapp-namegt]ltmodule-namegtROOT in the global namespace and
javaappltmodule-namegtROOT in the application-specific namespace
Please see section EE 811 (Component creation) and EE 812 (Application assembly) for the rules todetermine the app-name and module-name
The ltapp-namegt is applicable only when the web application is packaged within a ear file
The javaapp prefix allows a component executing within a Jakarta application to access anapplication-specific namespace The javaapp name allows a module in an enterprise application toreference the context root of another module in the same enterprise application The ltmodule-namegt is arequired part of the syntax for javaapp url
Examples
The above URL can then be used within an application as follows
If a web application is deployed standalone with module-name as myWebApp The URL can then be injectedinto another web module as follows
152 Web Applications
150 Jakarta Servlet Specification Final
Resource(lookup=javaglobalmyWebAppROOT)URL myWebApp
When packaged in an ear file named myApp it can be used as follows
Resource(lookup=javaglobalmyAppmyWebAppROOT)URL myWebApp
153 SecurityThis section details the additional security requirements for web containers when included in aproduct that also contains Jakarta Enterprise Beans Jakarta Authorisation andor JakartaAuthentication The following sections call out the requirements
1531 Propagation of Security Identity in Jakarta Enterprise Bean Calls
A security identity or principal must always be provided for use in a call to an enterprise bean Thedefault mode in calls to enterprise beans from web applications is for the security identity of a webuser to be propagated to the Jakarta Enterprise Bea container
In other scenarios web containers are required to allow web users that are not known to the webcontainer or to the Jakarta Enterprise Bean container to make calls
bull Web containers are required to support access to web resources by clients that have notauthenticated themselves to the container This is the common mode of access to web resources onthe Internet
bull Application code may be the sole processor of signon and customization of data based on calleridentity
In these scenarios a web application deployment descriptor may specify a run-as element When arun-as role is specified for a servlet the servlet container must propagate a principal mapped to therole as the security identity in any call from the servlet to an Jakarta Enterprise Beans including callsoriginating from the servletrsquos init and destroy methods The security role name must be one of thesecurity role names defined for the web application
For web containers running as part of a Jakarta EE platform the use of run-as elements must besupported both for calls to Jakarta Enterprise Bean components within the same Jakarta applicationand for calls to Jakarta Enterprise Bean components deployed in other Jakarta applications
1532 Container Authorization Requirements
In a Jakarta product or in a product that includes support for Jakarta Authorization all servletcontainers MUST implement support for Jakarta Authorization The Jakarta Authorization Specification
153 Security
Final Jakarta Servlet Specification 151
is available for download at httpsjakartaeespecificationsauthorization
1533 Container Authentication Requirements
In a Jakarta product or a product that includes support for Jakarta Authentication all servletcontainers MUST implement the Servlet Container Profile of the Jakarta Authentication specificationThe Jakarta Authentication specification is available for download at httpsjakartaeespecificationsauthentication
154 DeploymentThis section details the deployment descriptor packaging and deployment descriptor processingrequirements of a Jakarta EE Platform technology compliant container and products that includesupport for JSP and or web services
1541 Deployment Descriptor Elements
The following additional elements exist in the web application deployment descriptor to meet therequirements of web containers that are JSP pages enabled or part of a Jakarta application serverThey are not required to be supported by containers wishing to support only the servlet specification
bull jsp-config
bull Syntax for declaring resource references (env-entry ejb-ref ejb-local-ref resource-ref resource-env-ref)
bull Syntax for specifying the message destination(message-destination message-destination-ref)
bull Reference to a web service (service-ref)
bull Reference to a Persistence context (persistence-context-ref)
bull Reference to a Persistence Unit (persistence-unit-ref)
The syntax for these elements is now held in the Jakarta Server Pages specification version 30 and theJakarta EE Platform specification
1542 Packaging and Deployment of JAX-WS Components
Web containers may choose to support running components written to implement a web serviceendpoint as defined by the JAX-RPC andor JAX-WS specifications Web containers embedded in aJakarta conformant implementation are required to support JAX-RPC and JAX-WS web servicecomponents This section describes the packaging and deployment model for web containers whenincluded in a product which also supports JAX-RPC and JAX-WS
Jakarta Enterprise Web Services specification httpsjakartaeespecificationsenterprise-ws
defines the model for packaging a web service interface with its associated WSDL description andassociated classes It defines a mechanism for JAX-WS and JAX-RPC enabled web containers to link to acomponent that implements this web service A JAX-WS or JAX-RPC web service implementation
154 Deployment
152 Jakarta Servlet Specification Final
component uses the APIs defined by the JAX-WS andor JAX-RPC specifications which defines itscontract with the JAX-WS andor JAX-RPC enabled web containers It is packaged into the WAR file Theweb service developer makes a declaration of this component using the usual ltservletgt declaration
JAX-WS and JAX-RPC enabled web containers must support the developer in using the web deploymentdescriptor to define the following information for the endpoint implementation component using thesame syntax as for HTTP servlet components using the servlet element The child elements are used tospecify endpoint information in the following way
bull the servlet-name element defines a logical name which may be used to locate this endpointdescription among the other web components in the WAR
bull the servlet-class element provides the fully qualified Java class name of this endpointimplementation
bull the description element(s) may be used to describe the component and may be displayed in a tool
bull the load-on-startup element specifies the order in which the component is initialized relative toother web components in the web container
bull the security-role-ref element may be used to test whether the authenticated user is in a logicalsecurity role
bull the run-as element may be used to override the identity propagated to Jakarta Enterprise Beanscalled by this component
Any servlet initialization parameters defined by the developer for this web component may be ignoredby the container Additionally the JAX-WS and JAX-RPC enabled web component inherits thetraditional web component mechanisms for defining the following information
bull mapping of the component to the web containerrsquos URL namespace using the servlet mappingtechnique
bull authorization constraints on web components using security constraints
bull the ability to use servlet filters to provide low-level byte stream support for manipulating JAX-WSandor JAX-RPC messages using the filter mapping technique
bull the time out characteristics of any HTTP sessions that are associated with the component
bull links to Jakarta objects stored in the JNDI namespace
All of the above requirements can be met using the pluggability mechanism defined in Section 82ldquoPluggabilityrdquo
1543 Rules for Processing the Deployment Descriptor
The containers and tools that are part of Jakarta EE Platform technology-compliant implementationare required to validate the deployment descriptor against the XML schema for structural correctnessThe validation is recommended but not required for the web containers and tools that are not part ofa Jakarta EE Platform technology compliant implementation
154 Deployment
Final Jakarta Servlet Specification 153
155 Annotations and Resource InjectionThe Java Metadata specification (JSR-175) which is part of J2SE 50 and later versions provides ameans of specifying configuration data in Java code Metadata in Java code is also referred to asannotations In the Jakarta EE Platform annotations are used to declare dependencies on externalresources and configuration data in Java code without the need to define that data in a configurationfile
This section describes the behavior of annotations and resource injection in Jakarta technologycompliant servlet containers This section expands on the Jakarta EE Platform specification section 5titled ldquoResources Naming and Injectionrdquo
Annotations must be supported on container managed classes that implement the following interfacesand are declared in the web application deployment descriptor or using the annotations defined inSection 81 ldquoAnnotations and Pluggabilityrdquo or added programmatically
Table 15-1 Components and Interfaces supporting Annotations and Resource Injection
Component Type Classes implementing the following interfaces
Servlets jakartaservletServlet
Filters jakartaservletFilter
Listeners jakartaservletServletContextListener
jakartaservletServletContextAttributeListener
jakartaservletServletRequestListener
jakartaservletServletRequestAttributeListener
jakartaservlethttpHttpSessionListener
jakartaservlethttpHttpSessionAttributeListener
jakartaservlethttpHttpSessionIdListener jakartaservletAsyncListener
Handlers jakartaservlethttpHttpUgradeHandler
Web containers are not required to perform resource injection for annotations occurring in classesother than those listed above in TABLE 15-1
References must be injected prior to any lifecycle methods being called and the component instancebeing made available the application
In a web application classes using resource injection will have their annotations processed only if theyare located in the WEB-INFclasses directory or if they are packaged in a jar file located in WEB-INFlibContainers may optionally process resource injection annotations for classes found elsewhere in theapplicationrsquos classpath
1551 Handling of metadata-complete
The web application deployment descriptor contains a metadata-complete attribute on the web-appelement The metadata-complete attribute defines whether the webxml descriptor is complete or
155 Annotations and Resource Injection
154 Jakarta Servlet Specification Final
whether other sources of metadata used by the deployment process should be considered Metadatamay come from the webxml file web-fragmentxml files annotations on class files in WEB-INFclassesand annotations on classes in jar files in the WEB-INFlib directory If metadata-complete is set to truethe deployment tool only examines the webxml file and must ignore annotations such as WebServletWebFilter and WebListener present in the class files of the application and must also ignore any web-fragmentxml descriptor packaged in a jar file in WEB-INFlib If the metadata-complete attribute is notspecified or is set to false the deployment tool must examine the class files and web-fragmentxml filesfor metadata as previously specified
The web-fragmentxml also contains the metadata-complete attribute on the web-fragment element Theattribute defines whether the web-fragmentxml descriptor is complete for the given fragment orwhether the deployment tool should scan for annotations in the classes in the associated jar file Ifmetadata-complete is set to true the deployment tool only examines the web-fragmentxml and mustignore annotations such as WebServlet WebFilter and WebListener present in the class files of thefragment If metadata-complete is not specified or is set to false the deployment tool must examine theclass files for metadata
Following are the annotations that are required by a Jakarta technology compliant web container
1552 DeclareRoles
This annotation is used to define the security roles that comprise the security model of the applicationThis annotation is specified on a class and it is used to define roles that could be tested (ie by callingisUserInRole) from within the methods of the annotated class Roles that are implicitly declared as aresult of their use in a RolesAllowed need not be explicitly declared using the DeclareRoles annotaionThe DeclareRoles annotation may only be defined in classes implementing thejakartaservletServlet interface or a subclass thereof
Following is an example of how this annotation would be used
DeclareRoles Annotation Example
DeclareRoles(BusinessAdmin)public class CalculatorServlet extends HttpServlet
Declaring DeclareRoles (BusinessAdmin) is equivalent to defining the following in the webxml
155 Annotations and Resource Injection
Final Jakarta Servlet Specification 155
DeclareRoles webxml
ltweb-appgt ltsecurity-rolegt ltrole-namegtBusinessAdminltrole-namegt ltsecurity-rolegtltweb-appgt
This annotation is not used to relink application roles to other roles When such linking is necessary itis accomplished by defining an appropriate security-role-ref in the associated deployment descriptor
When a call is made to isUserInRole from the annotated class the caller identity associated with theinvocation of the class is tested for membership in the role with the same name as the argument toisCallerInRole If a security-role-ref has been defined for the argument role-name the caller is testedfor membership in the role mapped to the role-name
For further details on the DeclareRoles annotation refer to the Jakarta Annotations for the Jakarta EEPlatform specification section 212
1553 EJB Annotation
Jakarta Enterprise Beans 40 components may be referenced from a web component using the EJBannotation The EJB annotation provides the equivalent functionality of declaring the ejb-ref or ejb-local-ref elements in the deployment descriptor Fields that have a corresponding EJB annotation areinjected with the a reference to the corresponding Jakarta Enterprise Bean component
An example
EJB private ShoppingCart myCart
In the case above a reference to the Jakarta Enterprise Bean component myCart is injected as the valueof the private field myCart prior to the classs declaring the injection being made available
The behavior the EJB annotation is further detailed in section 1151 of the Jakarta Enterprise Bean 40specification
1554 EJBs Annotation
The EJBs annotation allows more than one EJB annotations to be declared on a single resource
An example
155 Annotations and Resource Injection
156 Jakarta Servlet Specification Final
EJBs Annotation Example
EJBs(EJB(Calculator)EJB(ShoppingCart))public class ShoppingCartServlet extends HttpServlet
The example above the Jakarta Enterprise Bean components ShoppingCart and Calculator are madeavailable to ShoppingCartServlet The ShoppingCartServlet must still look up the references using JNDIbut the Jakarta Enterprise Beans do not need to declared in the webxml file
1555 Resource Annotation
The Resource annotation is used to declare a reference to a resource such as a data source JakartaMessaging (JMS) destination or environment entry This annotation is equivalent to declaring aresource-ref message-destination-ref or env-ref or resource-env-ref element in the deploymentdescriptor
The Resource annotation is specified on a class method or field The container is responsible injectingreferences to resources declared by the Resource annotation and mapping it to the proper JNDIresources See the Jakarta EE Platform Specification Chapter 5 for further details
An example of a Resource annotation follows
Resource Example
Resourceprivate javaxsqlDataSource catalogDS
public getProductsByCategory()
get a connection and execute the query Connection conn = catalogDSgetConnection()
In the example code above a servlet filter or listener declares a field catalogDS of typejavaxsqlDataSource for which the reference to the data source is injected by the container prior to thecomponent being made available to the application The data source JNDI mapping is inferred from thefield name catalogDS and type (javaxsqlDataSource) Moreover the catalogDS resource no longerneeds to be defined in the deployment descriptor
The semantics of the Resource annotation are further detailed in the Jakarta Annotations for theJakarta EE Platform specification Section 525
155 Annotations and Resource Injection
Final Jakarta Servlet Specification 157
1556 PersistenceContext Annotation
This annotation specifies the container managed entity manager for referenced persistence units
An example
PersistenceContext Example
PersistenceContext(type=EXTENDED)EntityManager em
The behavior the PersistenceContext annotation is further detailed in section 1051 of the JakartaPersistence API Version 30
1557 PersistenceContexts Annotation
The PersistenceContexts annotation allows more than one PersistenceContext to be declared on aresource The behavior the PersistenceContexts annotation is further detailed in section 1051 of theJakarta Persistence API version 30
1558 PersistenceUnit Annotation
The PersistenceUnit annotation provides Jakarta Enterprise Beans components declared in a servlet areference to a entity manager factory The entity manager factory is bound to a separatepersistencexml configuration file as described in section 1110 of the Jakarta Enterprise Bean 40specification
An example
PersistenceUnit Example
PersistenceUnitEntityManagerFactory emf
The behavior the PersistenceUnit annotation is further detailed in section 1052 of the JakartaPersistence API version 30
1559 PersistenceUnits Annotation
This annotation allows for more than one PersistentUnit annotations to be declared on a resourceThe behavior the PersistenceUnits annotation is further detailed in section 1052 of the JakartaPersistence API version 30
155 Annotations and Resource Injection
158 Jakarta Servlet Specification Final
15510 PostConstruct Annotation
The PostConstruct annotation is declared on a method that does not take any arguments and must notthrow any checked exceptions The return value must be void The method MUST be called after theresources injections have been completed and before any lifecycle methods on the component arecalled
An example
PostConstruct Example
PostConstructpublic void postConstruct()
The example above shows a method using the PostConstruct annotation
The PostConstruct annotation MUST be supported by all classes that support dependency injectionand called even if the class does not request any resources to be injected If the method throws anunchecked exception the class MUST not be put into service and no method on that instance can becalled
Refer to the Jakarta EE Platform specification section 25 and the Jakarta Annotations specificationsection 25 for more details
15511 PreDestroy Annotation
The PreDestroy annotation is declared on a method of a container managed component The methodis called prior to component being removed by the container
An example
PreDestroy Example
PreDestroypublic void cleanup() clean up any open resources
The method annotated with PreDestroy must return void and must not throw a checked exceptionThe method may be public protected package private or private The method must not be statichowever it may be final
Refer to the Jakarta Annotations specification section 26 for more details
155 Annotations and Resource Injection
Final Jakarta Servlet Specification 159
15512 Resources Annotation
The Resources annotation acts as a container for multiple Resource annotations because the JakartaMetaData specification does not allow for multiple annotations with the same name on the sameannotation target
An example
Resources Example
Resources ( Resource(name=myDB type=javaxsqlDataSource) Resource(name=myMQ type=jakartajmsConnectionFactory))public class CalculatorServlet extends HttpServlet
In the example above a JMS connection factory and a data source are made available to theCalculatorServlet by means of an Resources annotation
The semantics of the Resources annotation are further detailed in the Jakarta Annotationsspecification specification section 20
15513 RunAs Annotation
The RunAs annotation is equivalent to the run-as element in the deployment descriptor The RunAsannotation may only be defined in classes implementing the jakartaservletServlet interface or asubclass thereof
An example
155 Annotations and Resource Injection
160 Jakarta Servlet Specification Final
RunAs Example
RunAs(Admin)public class CalculatorServlet extends HttpServlet
EJB private ShoppingCart myCart
public void doGet(HttpServletRequest req HttpServletResponse res) myCartgetTotal()
The RunAs(Admin) statement would be equivalent to defining the following in the webxml
RunAs webxml Example
ltservletgt ltservlet-namegtCalculatorServletltservlet-namegt ltrun-asgtAdminltrun-asgtltservletgt
The example above shows how a servlet uses the RunAs annotation to propagate the security identityAdmin to an Jakarta Enterprise Bean component when the myCartgetTotal() method is called Forfurther details on propagating identities see Section 1531 ldquoPropagation of Security Identity in JakartaEnterprise Bean Callsrdquo
For further details on the RunAs annotation refer to the Jakarta Annotations specification section 27
15514 WebServiceRef Annotation
The WebServiceRef annotation provides a reference to a web service in a web component in sameway as a resource-ref element would in the deployment descriptor
An example
WebServiceRefprivate MyService service
In this example a reference to the web service MyService will be injected to the class declaring theannotation
155 Annotations and Resource Injection
Final Jakarta Servlet Specification 161
This annotation and behavior are further detailed in the JAX-WS Specification section 7
15515 WebServiceRefs Annotation
This annotation allows for more than one WebServiceRef annotations to be declared on a singleresource The behavior of this annotation is further detailed in the JAX-WS Specification section 7
15516 Contexts and Dependency Injection for Jakarta EE PlatformRequirements
In a product that supports Contexts and Dependency Injection (CDI) for Jakarta EE Platform and inwhich CDI is enabled implementations MUST support the use of CDI managed beans Servlets filterslisteners and HttpUpgradeHandlers MUST support CDI injection and the use of interceptors asdescribed in Section 524 Support for Dependency Injection of the Jakarta EE Platform 9specification
155 Annotations and Resource Injection
162 Jakarta Servlet Specification Final
Appendix A Change LogThis document is the final release of the Jakarta Servlet 50 specification developed under the JakartaEE Working Group
A1 Compatibility with Jakarta Servlet SpecificationVersion 40Jakarta Servlet version 50 is only a change of namespaces (see Section A2 ldquoChanges Since JakartaServlet 40rdquo) Thus migrating a Servlet 40 project to Servlet 50 and above requires the replacement ofthe namespace javax with jakarta
A2 Changes Since Jakarta Servlet 40The only major change was a change of namespaces The javax namespaces have been replaced withjakarta
A1 Compatibility with Jakarta Servlet Specification Version 40
Final Jakarta Servlet Specification 163
A2 Changes Since Jakarta Servlet 40
164 Jakarta Servlet Specification Final
GlossaryApplication Developer
The producer of a web application The output of an Application Developer is a set of servlet classesJSP pages HTML pages and supporting libraries and files (such as images compressed archive filesetc) for the web application The Application Developer is typically an application domain expertThe developer is required to be aware of the servlet environment and its consequences whenprogramming including concurrency considerations and create the web application accordingly
Application Assembler
Takes the output of the Application Developer and ensures that it is a deployable unit Thus theinput of the Application Assembler is the servlet classes JSP pages HTML pages and othersupporting libraries and files for the web application The output of the Application Assembler is aweb application archive or a web application in an open directory structure
Deployer
The Deployer takes one or more web application archive files or other directory structures providedby an Application Developer and deploys the application into a specific operational environmentThe operational environment includes a specific servlet container and web server The Deployermust resolve all the external dependencies declared by the developer To perform this role thedeployer uses tools provided by the Servlet Container Provider
The Deployer is an expert in a specific operational environment For example the Deployer isresponsible for mapping the security roles defined by the Application Developer to the user groupsand accounts that exist in the operational environment where the web application is deployed
principal
A principal is an entity that can be authenticated by an authentication protocol A principal isidentified by a principal name and authenticated by using authentication data The content andformat of the principal name and the authentication data depend on the authentication protocol
role (development)
The actions and responsibilities taken by various parties during the development deployment andrunning of a web application In some scenarios a single party may perform several roles inothers each role may be performed by a different party
role (security)
An abstract notion used by an Application Developer in an application that can be mapped by theDeployer to a user or group of users in a security policy domain
security policy domain
The scope over which security policies are defined and enforced by a security administrator of thesecurity service A security policy domain is also sometimes referred to as a realm
Glossary
Final Jakarta Servlet Specification 165
security technology domain
The scope over which the same security mechanism such as Kerberos is used to enforce a securitypolicy Multiple security policy domains can exist within a single technology domain
Servlet Container Provider
A vendor that provides the runtime environment namely the servlet container and possibly theweb server in which a web application runs as well as the tools necessary to deploy webapplications
The expertise of the Container Provider is in HTTP-level programming Since this specification doesnot specify the interface between the web server and the servlet container it is left to the ContainerProvider to split the implementation of the required functionality between the container and theserver
servlet definition
A unique name associated with a fully qualified class name of a class implementing the Servletinterface A set of initialization parameters can be associated with a servlet definition
servlet mapping
A servlet definition that is associated by a servlet container with a URL path pattern All requests tothat path pattern are handled by the servlet associated with the servlet definition
System Administrator
The person responsible for the configuration and administration of the servlet container and webserver The administrator is also responsible for overseeing the well-being of the deployed webapplications at run time
This specification does not define the contracts for system management and administration Theadministrator typically uses runtime monitoring and management tools provided by the ContainerProvider and server vendors to accomplish these tasks
uniform resource locator (URL)
A compact string representation of resources available via the network Once the resourcerepresented by a URL has been accessed various operations may be performed on that resource [10]
A URL is a type of uniform resource identifier (URI) URLs are typically of the form
ltprotocolgtltservernamegtltresourcegt
For the purposes of this specification we are primarily interested in HTTP based URLs which are ofthe form
http[s]ltservernamegt[port]lturl-pathgt[ltquery-stringgt]
Glossary
166 Jakarta Servlet Specification Final
For example
httpwwwexamplecomproductsservletindexhtml
httpsexamplecompurchase
In HTTP-based URLs the character is reserved to separate a hierarchical path structure in theURL-path portion of the URL The server is responsible for determining the meaning of thehierarchical structure There is no correspondence between a URL-path and a given file systempath
web application
A collection of servlets JSP pages HTML documents and other web resources which might includeimage files compressed archives and other data A web application may be packaged into anarchive or exist in an open directory structure
All compatible servlet containers must accept a web application and perform a deployment of itscontents into their runtime This may mean that a container can run the application directly from aweb application archive file or it may mean that it will move the contents of a web application intothe appropriate locations for that particular container
web application archive
A single file that contains all of the components of a web application This archive file is created byusing 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 insteadof jar because that extension is reserved for files which contain a set of class files and that can beplaced in the classpath or double clicked using a GUI to launch an application As the contents of aweb application archive are not suitable for such use a new extension was in order
web application distributable
A web application that is written so that it can be deployed in a web container distributed acrossmultiple Java virtual machines running on the same host or different hosts The deploymentdescriptor for such an application uses the distributable element
[10] See RFC 1738
Glossary
Final Jakarta Servlet Specification 167