| # Apache Tomcat 7 Version 7.0.42, Jul 2 2013 |

Links Docs Home Config Ref. Home FAQ User Comments Top Level Elements Server Service Executors Executor Connectors HTTP AJP Containers Context Engine Host Cluster Nested Components Global Resources JarScanner Listeners Loader Manager Realm Resources Valve Cluster Elements Cluster Manager Channel Channel/Membership Channel/Sender Channel/Receiver Channel/Interceptor Valve Deployer ClusterListener Other Filter System properties | # The Context Container
Table of Contents
Introduction Parallel deployment Naming Defining a context Attributes Common Attributes Standard Implementation Nested Components Special Features Logging Access Logs Automatic Context Configuration Context Parameters Environment Entries Lifecycle Listeners Request Filters Resource Definitions Resource Links Transaction Virtual webapp
Introduction
> The description below uses the variable name $CATALINA_BASE to refer the base directory against which most relative paths are resolved. If you have not configured Tomcat for multiple instances by setting a CATALINA_BASE directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, the directory into which you have installed Tomcat. The Context element represents a web application, which is run within a particular virtual host. Each web application is based on a Web Application Archive (WAR) file, or a corresponding directory containing the corresponding unpacked contents, as described in the Servlet Specification (version 2.2 or later). For more information about web application archives, you can download the Servlet Specification, and review the Tomcat Application Developer's Guide. The web application used to process each HTTP request is selected by Catalina based on matching the longest possible prefix of the Request URI against the context path of each defined Context. Once selected, that Context will select an appropriate servlet to process the incoming request, according to the servlet mappings defined by the web application deployment. You may define as many Context elements as you wish. Each such Context MUST have a unique context name within a virtual host. The context path does not need to be unique (see parallel deployment below). In addition, a Context must be present with a context path equal to a zero-length string. This Context becomes the default web application for this virtual host, and is used to process all requests that do not match any other Context's context path.
> Parallel deployment
> You may deploy multiple versions of a web application with the same context path at the same time. The rules used to match requests to a context version are as follows: If no session information is present in the request, use the latest version. If session information is present in the request, check the session manager of each version for a matching session and if one is found, use that version. If session information is present in the request but no matching session can be found, use the latest version. The Host may be configured (via the `undeployOldVersions`) to remove old versions deployed in this way once they are no longer in use.
> Naming
> > When `autoDeploy` or `deployOnStartup` operations are performed by a Host, the name and context path of the web application are derived from the name(s) of the file(s) that define(s) the web application. Consequently, the context path may not be defined in a `META-INF/context.xml` embedded in the application and there is a close relationship between the context name, context path, context version and the base file name (the name minus any `.war` or `.xml` extension) of the file. If no version is specified then the context name is always the same as the context path. If the context path is the empty string them the base name will be ROOT (always in upper case) otherwise the base name will be the context path with the leading '/' removed and any remaining '/' characters replaced with '#'. If a version is specified then the context path remains unchanged and both the context name and the base name have the string '##' appended to them followed by the version identifier. Some examples of these naming conventions are given below.
> > Context Path | Context Version | Context Name | Base File Name | Example File Names (.xml, .war & directory)
> > /foo | None | /foo | foo | foo.xml, foo.war, foo
> > /foo/bar | None | /foo/bar | foo#bar | foo#bar.xml, foo#bar.war, foo#bar
> > Empty String | None | Empty String | ROOT | ROOT.xml, ROOT.war, ROOT
> > /foo | 42 | /foo##42 | foo##42 | foo##42.xml, foo##42.war, foo##42
> > /foo/bar | 42 | /foo/bar##42 | foo#bar##42 | foo#bar##42.xml, foo#bar##42.war, foo#bar##42
> > Empty String | 42 | ##42 | ROOT##42 | ROOT##42.xml, ROOT##42.war, ROOT##42
> The version component is treated as a `String` both for performance reasons and to allow flexibility in versioning schemes. String comparisons are used to determine version order. If version is not specified, it is treated as the empty string. Therefore, `foo.war` will be treated as an earlier version than `foo##11.war` and `foo##11.war` will be treated as an earlier version than `foo##2.war`. If using a purely numerical versioning scheme it is recommended that zero padding is used so that `foo##002.war` is treated as an earlier version than `foo##011.war`. If you want to deploy a WAR file or a directory using a context path that is not related to the base file name then one of the following options must be used to prevent double-deployment: Disable autoDeploy and deployOnStartup and define all Contexts in server.xml Locate the WAR and/or directory outside of the Host's appBase and use a context.xml file with a docBase attribute to define it.
> Defining a context
> It is NOT recommended to place <Context> elements directly in the server.xml file. This is because it makes modifying the Context configuration more invasive since the main `conf/server.xml` file cannot be reloaded without restarting Tomcat. Individual Context elements may be explicitly defined: In an individual file at `/META-INF/context.xml` inside the application files. Optionally (based on the Host's copyXML attribute) this may be copied to `$CATALINA_BASE/conf/[enginename]/[hostname]/` and renamed to application's base file name plus a ".xml" extension. In individual files (with a ".xml" extension) in the `$CATALINA_BASE/conf/[enginename]/[hostname]/` directory. The context path and version will be derived from the base name of the file (the file name less the .xml extension). This file will always take precedence over any context.xml file packaged in the web application's META-INF directory. Inside a Host element in the main `conf/server.xml`. Default Context elements may be defined that apply to multiple web applications. Configuration for an individual web application will override anything configured in one of these defaults. Any nested elements, e.g. <Resource> elements, that are defined in a default Context will be created once for each Context to which the default applies. They will not be shared between Context elements. In the `$CATALINA_BASE/conf/context.xml` file: the Context element information will be loaded by all web applications. In the `$CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default` file: the Context element information will be loaded by all web applications of that host. With the exception of server.xml, files that define Context elements may only define a single Context element. In addition to explicitly specified Context elements, there are several techniques by which Context elements can be created automatically for you. See Automatic Application Deployment and User Web Applications for more information. To define multiple contexts that use a single WAR file or directory, use one of the options described in the Naming section above for creating a Context that has a path that is not related to the base file name.
Attributes
> Common Attributes
> > All implementations of Context support the following attributes:
> > Attribute | Description
> > --- | ---
> > `allowCasualMultipartParsing` | Set to true if Tomcat should automatically parse multipart/form-data request bodies when HttpServletRequest.getPart* or HttpServletRequest.getParameter* is called, even when the target servlet isn't marked with the @MultipartConfig annotation (See Servlet Specification 3.0, Section 3.2 for details). Note that any setting other than `false` causes Tomcat to behave in a way that is not technically spec-compliant. The default is `false`
> > `backgroundProcessorDelay` | This value represents the delay in seconds between the invocation of the backgroundProcess method on this context and its child containers, including all wrappers. Child containers will not be invoked if their delay value is not negative (which would mean they are using their own processing thread). Setting this to a positive value will cause a thread to be spawn. After waiting the specified amount of time, the thread will invoke the backgroundProcess method on this host and all its child containers. A context will use background processing to perform session expiration and class monitoring for reloading. If not specified, the default value for this attribute is -1, which means the context will rely on the background processing thread of its parent host.
> > `className` | Java class name of the implementation to use. This class must implement the `org.apache.catalina.Context` interface. If not specified, the standard value (defined below) will be used.
> > `cookies` | Set to `true` if you want cookies to be used for session identifier communication if supported by the client (this is the default). Set to `false` if you want to disable the use of cookies for session identifier communication, and rely only on URL rewriting by the application.
> > `crossContext` | Set to `true` if you want calls within this application to `ServletContext.getContext()` to successfully return a request dispatcher for other web applications running on this virtual host. Set to `false` (the default) in security conscious environments, to make `getContext()` always return `null`.
> > `docBase` | The Document Base (also known as the Context Root) directory for this web application, or the pathname to the web application archive file (if this web application is being executed directly from the WAR file). You may specify an absolute pathname for this directory or WAR file, or a pathname that is relative to the `appBase` directory of the owning Host. The value of this field must not be set unless the Context element is defined in server.xml or the `docBase` is not located under the Host's `appBase`. If a symbolic link is used for docBase then changes to the symbolic link will only be effective after a Tomcat restart or by undeploying and redeploying the context. A context reload is not sufficient.
> > `fireRequestListenersOnForwards` | Set to `true` to fire any configured ServletRequestListeners when Tomcat forwards a request. This is primarily of use to users of CDI frameworks that use ServletRequestListeners to configure the necessary environment for a request. If not specified, the default value of `false` is used.
> > `logEffectiveWebXml` | Set to `true` if you want the effective web.xml used for a web application to be logged (at INFO level) when the application starts. The effective web.xml is the result of combining the application's web.xml with any defaults configured by Tomcat and any web-fragment.xml files and annotations discovered. If not specified, the default value of `false` is used.
> > `override` | Set to `true` to ignore any settings in both the global or Host default contexts. By default, settings from a default context will be used but may be overridden by a setting the same attribute explicitly for the Context.
> > `path` | The context path of this web application, which is matched against the beginning of each request URI to select the appropriate web application for processing. All of the context paths within a particular Host must be unique. If you specify a context path of an empty string (""), you are defining the default web application for this Host, which will process all requests not assigned to other Contexts. This attribute must only be used when statically defining a Context in server.xml. In all other circumstances, the path will be inferred from the filenames used for either the .xml context file or the docBase. Even when statically defining a Context in server.xml, this attribute must not be set unless either the docBase is not located under the Host's `appBase` or both `deployOnStartup` and `autoDeploy` are false. If this rule is not followed, double deployment is likely to result.
> > `preemptiveAuthentication` | When set to `true` and the user presents credentials for a resource that is not protected by a security constraint, if the authenticator supports preemptive authentication (the standard authenticators provided with Tomcat do) then the user' credentials will be processed. If not specified, the default of `false`is used.
> > `privileged` | Set to `true` to allow this context to use container servlets, like the manager servlet. Use of the `privileged` attribute will change the context's parent class loader to be the Server class loader rather than the Shared class loader. Note that in a default installation, the Common class loader is used for both the Server and the Shared class loaders.
> > `reloadable` | Set to `true` if you want Catalina to monitor classes in `/WEB-INF/classes/` and `/WEB-INF/lib` for changes, and automatically reload the web application if a change is detected. This feature is very useful during application development, but it requires significant runtime overhead and is not recommended for use on deployed production applications. That's why the default setting for this attribute is false. You can use the Manager web application, however, to trigger reloads of deployed applications on demand.
> > `resourceOnlyServlets` | Comma separated list of Servlet names (as used in `/WEB-INF/web.xml`) that expect a resource to be present. Ensures that welcome files associated with Servlets that expect a resource to be present (such as the JSP Servlet) are not used when there is no resource present. This prevents issues caused by the clarification of welcome file mapping in section 10.10 of the Servlet 3.0 specification. If the `org.apache.catalina.STRICT_SERVLET_COMPLIANCE` system property is set to `true`, the default value of this attribute will be the empty string, else the default value will be `jsp`.
> > `sendRedirectBody` | If `true`, redirect responses will include a short response body that includes details of the redirect as recommended by RFC 2616. This is disabled by default since including a response body may cause problems for some application component such as compression filters.
> > `sessionCookieDomain` | The domain to be used for all session cookies created for this context. If set, this overrides any domain set by the web application. If not set, the value specified by the web application, if any, will be used.
> > `sessionCookieName` | The name to be used for all session cookies created for this context. If set, this overrides any name set by the web application. If not set, the value specified by the web application, if any, will be used, or the name `JSESSIONID` if the web application does not explicitly set one.
> > `sessionCookiePath` | The path to be used for all session cookies created for this context. If set, this overrides any path set by the web application. If not set, the value specified by the web application will be used, or the context path used if the web application does not explicitly set one. To configure all web application to use an empty path (this can be useful for portlet specification implementations) set this attribute to `/` in the global `CATALINA_BASE/conf/context.xml` file.
> > `sessionCookiePathUsesTrailingSlash` | Some browsers, such as IE, will send a session cookie for a context with a path of /foo with a request to /foobar. To prevent this, Tomcat will add a trailing slash to the path associated with the session cookie so, in the above example, the cookie path becomes /foo/. However, with a cookie path of /foo/, IE will no longer send the cookie with a request to /foo. This should not be a problem unless there is a servlet mapped to /*. In this case this feature will need to be disabled. The default value for this attribute is `true.` To disable this feature, set the attribute to `false`.
> > `swallowAbortedUploads` | Set to false if Tomcat should not read any additional request body data for aborted uploads and instead abort the client connection. This setting is used in the following situations: the size of the request body is larger than the `maxPostSize` configured in the connector the size limit of a MultiPart upload is reached the servlet sets the response status to 413 (Request Entity Too Large) Not reading the additional data will free the request processing thread more quickly. Unfortunately most HTTP clients will not read the response if they can not write the full request. The default is `true`, so additional data will be read. Note if an error occurs during the request processing that triggers a 5xx response, any unread request data will always be ignored and the client connection will be closed once the error response has been written.
> > `swallowOutput` | If the value of this flag is `true`, the bytes output to System.out and System.err by the web application will be redirected to the web application logger. If not specified, the default value of the flag is `false`.
> > `tldNamespaceAware` | If the value of this flag is `true`, the TLD files XML validation will be namespace-aware. If you turn this flag on, you should probably also turn `tldValidation` on. If the `org.apache.catalina.STRICT_SERVLET_COMPLIANCE` system property is set to `true`, the default value of this attribute will be `true`, else the default value will be `false`. Setting this attribute to `true` will incur a performance penalty.
> > `tldValidation` | If the value of this flag is `true`, the TLD files will be XML validated on context startup. If the `org.apache.catalina.STRICT_SERVLET_COMPLIANCE` system property is set to `true`, the default value of this attribute will be `true`, else the default value will be `false`. Setting this attribute to `true` will incur a performance penalty.
> > `useHttpOnly` | Should the HttpOnly flag be set on session cookies to prevent client side script from accessing the session ID? Defaults to `true`.
> > `wrapperClass` | Java class name of the `org.apache.catalina.Wrapper` implementation class that will be used for servlets managed by this Context. If not specified, a standard default value will be used.
> > `xmlNamespaceAware` | If the value of this flag is `true`, the validation of XML files will be namespace-aware. If you turn this flag on, you should probably also turn `xmlValidation` on. If the `org.apache.catalina.STRICT_SERVLET_COMPLIANCE` system property is set to `true`, the default value of this attribute will be `true`, else the default value will be `false`. Setting this attribute to `true` will incur a performance penalty.
> > `xmlValidation` | If the value of this flag is `true`, the XML files will be validated on context startup. If the `org.apache.catalina.STRICT_SERVLET_COMPLIANCE` system property is set to `true`, the default value of this attribute will be `true`, else the default value will be `false`. Setting this attribute to `true` will incur a performance penalty.
> Standard Implementation
> > The standard implementation of Context is org.apache.catalina.core.StandardContext. It supports the following additional attributes (in addition to the common attributes listed above):
> > Attribute | Description
> > --- | ---
> > `addWebinfClassesResources` | This attribute controls if, in addition to static resources being served from `META-INF/resources` inside web application JAR files, static resources are also served from `WEB-INF/classes/META-INF/resources`. This only applies to web applications with a major version of 3 or higher. Since this is a proprietary extension to the Servlet 3 specification, it is disabled by default. To enable this feature, set the attribute to `true`.
> > `aliases` | This attribute provides a list of external locations from which to load resources for this context. The list of aliases should be of the form `"/aliasPath1=docBase1,/aliasPath2=docBase2"` where `aliasPathN` must include a leading '/' and `docBaseN` must be an absolute path to either a .war file or a directory. Whitespace is permitted around both the `,` and `=` delimiters, and will be trimmed. Therefore, an aliases attribute with the value `"/aliasPath1 = docBase1, /aliasPath2= docBase2"` is equivalent to `"/aliasPath1=docBase1,/aliasPath2=docBase2"` A resource will be searched for in the first `docBaseN` for which `aliasPathN` is a leading path segment of the resource. If there is no such alias, then the resource will be searched in the usual way. Using '/' as an aliasPath is not allowed. Consider using `docBase` instead. These external locations will not be emptied if the context is un-deployed. A more powerful feature (for development only) is Virtual webapp.
> > `allowLinking` | If the value of this flag is `true`, symlinks will be allowed inside the web application, pointing to resources outside the web application base path. If not specified, the default value of the flag is `false`. NOTE: This flag MUST NOT be set to true on the Windows platform (or any other OS which does not have a case sensitive filesystem), as it will disable case sensitivity checks, allowing JSP source code disclosure, among other security problems.
> > `antiJARLocking` | If true, the Tomcat classloader will take extra measures to avoid JAR file locking when resources are accessed inside JARs through URLs. This will impact startup time of applications, but could prove to be useful on platforms or configurations where file locking can occur. If not specified, the default value is `false`. `antiJARLocking` is a subset of `antiResourceLocking` and therefore, to prevent duplicate work and possible issues, only one of these attributes should be set to `true` at any one time.
> > `antiResourceLocking` | If true, Tomcat will prevent any file locking. This will significantly impact startup time of applications, but allows full webapp hot deploy and undeploy on platforms or configurations where file locking can occur. If not specified, the default value is `false`. `antiJARLocking` is a subset of `antiResourceLocking` and therefore, to prevent duplicate work and possible issues, only one of these attributes should be set to `true` at any one time. Please note that setting this to `true` has some side effects, including the disabling of JSP reloading in a running server: see Bugzilla 37668. Please note that setting this flag to true in applications that are outside the appBase for the Host (the `webapps` directory by default) will cause the application to be deleted on Tomcat shutdown. You probably don't want to do this, so think twice before setting antiResourceLocking=true on a webapp that's outside the appBase for its Host.
> > `cacheMaxSize` | Maximum size of the static resource cache in kilobytes. If not specified, the default value is `10240` (10 megabytes).
> > `cacheObjectMaxSize` | Maximum size of the static resource that will be placed in the cache. If not specified, the default value is `512` (512 kilobytes). If this value is greater than `cacheMaxSize/20` it will be reduced to `cacheMaxSize/20`.
> > `cacheTTL` | Amount of time in milliseconds between cache entries revalidation. If not specified, the default value is `5000` (5 seconds).
> > `cachingAllowed` | If the value of this flag is `true`, the cache for static resources will be used. If not specified, the default value of the flag is `true`.
> > `clearReferencesHttpClientKeepAliveThread` | If `true` and an `sun.net.www.http.HttpClient` keep-alive timer thread has been started by this web application and is still running, Tomcat will change the context class loader for that thread from the current `WebappClassLoader` to `WebappClassLoader#parent` to prevent a memory leak. Note that the keep-alive timer thread will stop on its own once the keep-alives all expire however, on a busy system that might not happen for some time. If not specified, the default value of `true` will be used.
> > `clearReferencesStatic` | If `true`, Tomcat attempts to null out any static or final fields from loaded classes when a web application is stopped as a work around for apparent garbage collection bugs and application coding errors. There have been some issues reported with log4j when this is `true`. Applications without memory leaks using recent JVMs should operate correctly with this attribute set to `false`. If not specified, the default value of `false` will be used.
> > `clearReferencesStopThreads` | If `true`, Tomcat attempts to terminate threads that have been started by the web application. Stopping threads is performed via the deprecated (for good reason) `Thread.stop()` method and is likely to result in instability. As such, enabling this should be viewed as an option of last resort in a development environment and is not recommended in a production environment. If not specified, the default value of `false` will be used.
> > `clearReferencesStopTimerThreads` | If `true`, Tomcat attempts to terminate `java.util.Timer` threads that have been started by the web application. Unlike standard threads, timer threads can be stopped safely although there may still be side-effects for the application. If not specified, the default value of `false` will be used.
> > `jndiExceptionOnFailedWrite` | If `true`, any attempt by an application to modify the provided JNDI context with a call to bind(), unbind(), createSubContext(), destroySubContext() or close() will trigger a `javax.naming.OperationNotSupportedException` as required by section EE.5.3.4 of the Java EE specification. This exception can be disabled by setting this attribute to true in which case any calls to modify the JNDI context will return without making any changes and methods that return values will return `null`. If not specified, the specification compliant default of `true` will be used.
> > `processTlds` | Whether the context should process TLDs on startup. The default is true. The false setting is intended for special cases that know in advance TLDs are not part of the webapp.
> > `renewThreadsWhenStoppingContext` | If `true`, when this context is stopped, Tomcat renews all the threads from the thread pool that was used to serve this context. This also requires that the `ThreadLocalLeakPreventionListener` be configured in `server.xml` and that the `threadRenewalDelay` property of the `Executor` be >=0. If not specified, the default value of `true` will be used.
> > `unloadDelay` | Number of ms that the container will wait for servlets to unload. If not specified, the default value is `2000` ms.
> > `unpackWAR` | If `false`, the unpackWARs attribute of the owning Host will be overridden and the WAR file will not be unpacked. If `true`, the value of the owning Host's unpackWARs attribute will determine if the WAR is unpacked. If not specified, the default value is `true`. Note that WAR files located outside of a Host's appBase are never unpacked.
> > `useNaming` | Set to `true` (the default) to have Catalina enable a JNDI `InitialContext` for this web application that is compatible with Java2 Enterprise Edition (J2EE) platform conventions.
> > `workDir` | Pathname to a scratch directory to be provided by this Context for temporary read-write use by servlets within the associated web application. This directory will be made visible to servlets in the web application by a servlet context attribute (of type `java.io.File`) named `javax.servlet.context.tempdir` as described in the Servlet Specification. If not specified, a suitable directory underneath `$CATALINA_BASE/work` will be provided.
Nested Components
You can nest at most one instance of the following utility components by nesting a corresponding element inside your Context element: Loader - Configure the web application class loader that will be used to load servlet and bean classes for this web application. Normally, the default configuration of the class loader will be sufficient. Manager - Configure the session manager that will be used to create, destroy, and persist HTTP sessions for this web application. Normally, the default configuration of the session manager will be sufficient. Realm - Configure a realm that will allow its database of users, and their associated roles, to be utilized solely for this particular web application. If not specified, this web application will utilize the Realm associated with the owning Host or Engine. Resources - Configure the resource manager that will be used to access the static resources associated with this web application. Normally, the default configuration of the resource manager will be sufficient. WatchedResource - The auto deployer will monitor the specified static resource of the web application for updates, and will reload the web application if it is updated. The content of this element must be a string.
Special Features
> Logging
> A context is associated with the `org.apache.catalina.core.ContainerBase.[enginename].[hostname].[path]` log category. Note that the brackets are actually part of the name, don't omit them.
> Access Logs
> > When you run a web server, one of the output files normally generated is an access log, which generates one line of information for each request processed by the server, in a standard format. Catalina includes an optional Valve implementation that can create access logs in the same standard format created by web servers, or in any number of custom formats. You can ask Catalina to create an access log for all requests processed by an Engine, Host, or Context by nesting a Valve element like this:
> >     <Context>
> >       ...
> >       <Valve className="org.apache.catalina.valves.AccessLogValve"
> >              prefix="localhost_access_log." suffix=".txt"
> >              pattern="common"/>
> >       ...
> >     </Context>
> See Access Log Valve for more information on the configuration attributes that are supported.
> Automatic Context Configuration
> If you use the standard Context implementation, the following configuration steps occur automatically when Catalina is started, or whenever this web application is reloaded. No special configuration is required to enable this feature. If you have not declared your own Loader element, a standard web application class loader will be configured. If you have not declared your own Manager element, a standard session manager will be configured. If you have not declared your own Resources element, a standard resources manager will be configured. The web application properties listed in `conf/web.xml` will be processed as defaults for this web application. This is used to establish default mappings (such as mapping the `*.jsp` extension to the corresponding JSP servlet), and other standard features that apply to all web applications. The web application properties listed in the `/WEB-INF/web.xml` resource for this web application will be processed (if this resource exists). If your web application has specified security constraints that might require user authentication, an appropriate Authenticator that implements the login method you have selected will be configured.
> Context Parameters
> > You can configure named values that will be made visible to the web application as servlet context initialization parameters by nesting `<Parameter>` elements inside this element. For example, you can create an initialization parameter like this:
> >     <Context>
> >       ...
> >       <Parameter name="companyName" value="My Company, Incorporated"
> >              override="false"/>
> >       ...
> >     </Context>
> > This is equivalent to the inclusion of the following element in the web application deployment descriptor (`/WEB-INF/web.xml`):
> >     <context-param>
> >       <param-name>companyName</param-name>
> >       <param-value>My Company, Incorporated</param-value>
> >     </context-param>
> > but does not require modification of the deployment descriptor to customize this value. The valid attributes for a `<Parameter>` element are as follows:
> > Attribute | Description
> > --- | ---
> > `description` | Optional, human-readable description of this context initialization parameter.
> > `name` | The name of the context initialization parameter to be created.
> > `override` | Set this to `false` if you do not want a `<context-param>` for the same parameter name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.
> > `value` | The parameter value that will be presented to the application when requested by calling `ServletContext.getInitParameter()`.
> Environment Entries
> > You can configure named values that will be made visible to the web application as environment entry resources, by nesting `<Environment>` entries inside this element. For example, you can create an environment entry like this:
> >     <Context>
> >       ...
> >       <Environment name="maxExemptions" value="10"
> >              type="java.lang.Integer" override="false"/>
> >       ...
> >     </Context>
> > This is equivalent to the inclusion of the following element in the web application deployment descriptor (`/WEB-INF/web.xml`):
> >     <env-entry>
> >       <env-entry-name>maxExemptions</env-entry-name>
> >       <env-entry-value>10</env-entry-value>
> >       <env-entry-type>java.lang.Integer</env-entry-type>
> >     </env-entry>
> > but does not require modification of the deployment descriptor to customize this value. The valid attributes for an `<Environment>` element are as follows:
> > Attribute | Description
> > --- | ---
> > `description` | Optional, human-readable description of this environment entry.
> > `name` | The name of the environment entry to be created, relative to the `java:comp/env` context.
> > `override` | Set this to `false` if you do not want an `<env-entry>` for the same environment entry name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.
> > `type` | The fully qualified Java class name expected by the web application for this environment entry. Must be a legal value for `<env-entry-type>` in the web application deployment descriptor.
> > `value` | The parameter value that will be presented to the application when requested from the JNDI context. This value must be convertable to the Java type defined by the `type` attribute.
> Lifecycle Listeners
> > If you have implemented a Java object that needs to know when this Context is started or stopped, you can declare it by nesting a Listener element inside this element. The class name you specify must implement the `org.apache.catalina.LifecycleListener` interface, and the class must be packaged in a jar and placed in the `$CATALINA_HOME/lib` directory. It will be notified about the occurrence of the corresponding lifecycle events. Configuration of such a listener looks like this:
> >     <Context>
> >       ...
> >       <Listener className="com.mycompany.mypackage.MyListener" ... >
> >       ...
> >     </Context>
> Note that a Listener can have any number of additional properties that may be configured from this element. Attribute names are matched to corresponding JavaBean property names using the standard property method naming patterns.
> Request Filters
> > You can ask Catalina to check the IP address, or host name, on every incoming request directed to the surrounding Engine, Host, or Context element. The remote address or name will be checked against configured "accept" and/or "deny" filters, which are defined using `java.util.regex` Regular Expression syntax. Requests that come from locations that are not accepted will be rejected with an HTTP "Forbidden" error. Example filter declarations:
> >     <Context>
> >       ...
> >       <Valve className="org.apache.catalina.valves.RemoteHostValve"
> >              allow=".*\.mycompany\.com|www\.yourcompany\.com"/>
> >       <Valve className="org.apache.catalina.valves.RemoteAddrValve"
> >              deny="192\.168\.1\.\d+"/>
> >       ...
> >     </Context>
> See Remote Address Filter and Remote Host Filter for more information about the configuration options that are supported.
> Resource Definitions
> > You can declare the characteristics of the resource to be returned for JNDI lookups of `<resource-ref>` and `<resource-env-ref>` elements in the web application deployment descriptor. You MUST also define the needed resource parameters as attributes of the `Resource` element, to configure the object factory to be used (if not known to Tomcat already), and the properties used to configure that object factory. For example, you can create a resource definition like this:
> >     <Context>
> >       ...
> >       <Resource name="jdbc/EmployeeDB" auth="Container"
> >                 type="javax.sql.DataSource"
> >          description="Employees Database for HR Applications"/>
> >       ...
> >     </Context>
> > This is equivalent to the inclusion of the following element in the web application deployment descriptor (`/WEB-INF/web.xml`):
> >     <resource-ref>
> >       <description>Employees Database for HR Applications</description>
> >       <res-ref-name>jdbc/EmployeeDB</res-ref-name>
> >       <res-ref-type>javax.sql.DataSource</res-ref-type>
> >       <res-auth>Container</res-auth>
> >     </resource-ref>
> > but does not require modification of the deployment descriptor to customize this value. The valid attributes for a `<Resource>` element are as follows:
> > Attribute | Description
> > --- | ---
> > `auth` | Specify whether the web Application code signs on to the corresponding resource manager programatically, or whether the Container will sign on to the resource manager on behalf of the application. The value of this attribute must be `Application` or `Container`. This attribute is required if the web application will use a `<resource-ref>` element in the web application deployment descriptor, but is optional if the application uses a `<resource-env-ref>` instead.
> > `closeMethod` | Name of the zero-argument method to call on a singleton resource when it is no longer required. This is intended to speed up clean-up of resources that would otherwise happen as part of garbage collection. This attribute is ignored if the `singleton` attribute is false. If not specificed, no default is defined and no close method will be called. For Apache Commons DBCP and Apache Tomcat JDBC connection pools you can use `closeMethod="close"`.
> > `description` | Optional, human-readable description of this resource.
> > `name` | The name of the resource to be created, relative to the `java:comp/env` context.
> > `scope` | Specify whether connections obtained through this resource manager can be shared. The value of this attribute must be `Shareable` or `Unshareable`. By default, connections are assumed to be shareable.
> > `singleton` | Specify whether this resource definition is for a singleton resource, i.e. one where there is only a single instance of the resource. If this attribute is `true`, multiple JNDI lookups for this resource will return the same object. If this attribute is `false`, multiple JNDI lookups for this resource will return different objects. This attribute must be `true` for `javax.sql.DataSource` resources to enable JMX registration of the DataSource. The value of this attribute must be `true` or `false`. By default, this attribute is `true`.
> > `type` | The fully qualified Java class name expected by the web application when it performs a lookup for this resource.
> Resource Links
> > This element is used to create a link to a global JNDI resource. Doing a JNDI lookup on the link name will then return the linked global resource. For example, you can create a resource link like this:
> >     <Context>
> >       ...
> >       <ResourceLink name="linkToGlobalResource"
> >                 global="simpleValue"
> >                 type="java.lang.Integer"
> >       ...
> >     </Context>
> > The valid attributes for a `<ResourceLink>` element are as follows:
> > Attribute | Description
> > --- | ---
> > `global` | The name of the linked global resource in the global JNDI context.
> > `name` | The name of the resource link to be created, relative to the `java:comp/env` context.
> > `type` | The fully qualified Java class name expected by the web application when it performs a lookup for this resource link.
> > `factory` | The fully qualified Java class name for the class creating these objects. This class should implement the `javax.naming.spi.ObjectFactory` interface.
> > When the attribute `factory="org.apache.naming.factory.DataSourceLinkFactory"` the resource link can be used with two additional attributes to allow a shared data source to be used with different credentials. When these two additional attributes are used in combination with the `javax.sql.DataSource` type, different contexts can share a global data source with different credentials. Under the hood, what happens is that a call to `getConnection()` is simply translated to a call `getConnection(username, password)` on the global data source. This is an easy way to get code to be transparent to what schemas are being used, yet be able to control connections (or pools) in the global configuration.
> > Attribute | Description
> > --- | ---
> > `username` | `username` value for the `getConnection(username, password)` call on the linked global DataSource.
> > `password` | `password` value for the `getConnection(username, password)` call on the linked global DataSource.
> > Shared Data Source Example: Warning: This feature works only if the global DataSource supports `getConnection(username, password)` method. Apache Commons DBCP pool that Tomcat uses by default does not support it. See its Javadoc for `BasicDataSource` class. Apache Tomcat JDBC pool does support it, but by default this support is disabled and can be enabled by `alternateUsernameAllowed` attribute. See its documentation for details.
> >     <GlobalNamingResources>
> >       ...
> >       <Resource name="sharedDataSource"
> >                 global="sharedDataSource"
> >                 type="javax.sql.DataSource"
> >                 factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
> >                 alternateUsernameAllowed="true"
> >                 username="bar"
> >                 password="barpass"
> >                 ...
> >       ...
> >     </GlobalNamingResources>

> >     <Context path="/foo"...>
> >       ...
> >       <ResourceLink
> >                 name="appDataSource"
> >                 global="sharedDataSource"
> >                 type="javax.sql.DataSource"
> >                 factory="org.apache.naming.factory.DataSourceLinkFactory"
> >                 username="foo"
> >                 password="foopass"
> >       ...
> >     </Context>
> >     <Context path="/bar"...>
> >       ...
> >       <ResourceLink
> >                 name="appDataSource"
> >                 global="sharedDataSource"
> >                 type="javax.sql.DataSource"
> >       ...
> >     </Context>
> When a request for `getConnection()` is made in the `/foo` context, the request is translated into `getConnection("foo","foopass")`, while a request in the `/bar` gets passed straight through.
> Transaction
> > You can declare the characteristics of the UserTransaction to be returned for JNDI lookup for `java:comp/UserTransaction`. You MUST define an object factory class to instantiate this object as well as the needed resource parameters as attributes of the `Transaction` element, and the properties used to configure that object factory. The valid attributes for the `<Transaction>` element are as follows:
> > Attribute | Description
> > --- | ---
> > `factory` | The class name for the JNDI object factory.
> Virtual webapp
> > During development it may be more productive to avoid copying files (static resources, JSPs, classes, jars...) and configure tomcat to use files from their source locations. To do that, several customisations of the context configuration are required: The `VirtualDirContext` implementation of Resources The `VirtualWebappLoader` implementation of Loader `scanAllDirectories="true"` on the JarScanner To illustrate this feature, here is an example of a standard maven webapp source tree:
> >     mywebapp/
> >              src/
> >                  main/
> >                       java/
> >                       resources/
> >                       webapp/
> >                              WEB-INF/
> >                                      classes/
> >              target/
> >                     classes/
> > To deploy such an application (assuming it also uses the log4j maven artefact), the context configuration looks like:
> >     <Context path="/mywebapp" docBase="/Users/theuser/mywebapp/src/main/webapp" >
> >       <Resources className="org.apache.naming.resources.VirtualDirContext"
> >         extraResourcePaths=
> >           "/WEB-INF/classes=/Users/theuser/mywebapp/target/classes" />
> >       <Loader className="org.apache.catalina.loader.VirtualWebappLoader"
> >         virtualClasspath="/Users/theuser/mywebapp/target/classes;
> >           /Users/theuser/.m2/repository/log4j/log4j/1.2.15/log4j-1.2.15.jar" />
> >       <JarScanner scanAllDirectories="true" />
> >     </Context>
> > Here is another example where the webapp serves pictures under /pictures and movies under /movies and also depends on another maven project mylib that would normally produce a jar to be packaged in WEB-INF/lib:
> >     mylib/
> >           src/
> >               main/
> >                    java/
> >                    resources/
> >                              META-INF/
> >                                       resources/
> >           target/
> >                  classes/
> >     mymovies/
> >     mypictures/
> >     mywebapp/
> >              src/
> >                  main/
> >                       java/
> >                       resources/
> >                       webapp/
> >                              WEB-INF/
> >                                      classes/
> >              target/
> >                     classes/
> > The configuration is:
> > | `<Context path="/mywebapp" docBase="/Users/theuser/mywebapp/src/main/webapp" > <Resources className="org.apache.naming.resources.VirtualDirContext" extraResourcePaths="/WEB-INF/classes=/Users/theuser/mywebapp/target/classes,/pictures=/Users/theuser/mypictures,/movies=/Users/theuser/mymovies" /> <Loader className="org.apache.catalina.loader.VirtualWebappLoader" virtualClasspath="/Users/theuser/mywebapp/target/classes;/Users/theuser/mylib/target/classes;/Users/theuser/.m2/repository/log4j/log4j/1.2.15/log4j-1.2.15.jar" /> <JarScanner scanAllDirectories="true" /> </Context>` |
> Note that resources in mylib/target/classes/META-INF/resources/ are mapped to / as required by servlet 3 specification.
Comments
Notice: This comments section collects your suggestions on improving documentation for Apache Tomcat. If you have trouble and need help, read Find Help page and ask your question on the tomcat-users mailing list. Do not ask such questions here. This is not a Q&A section. The Apache Comments System is explained here. Comments may be removed by our moderators if they are either implemented or considered invalid/off-topic.
Copyright © 1999-2013, Apache Software Foundation