Tomcat

Tomcat context.xml Configuration Example

In Tomcat, the Context Container represents a single web application running within a given instance of Tomcat. A web site is made up of one or more Contexts. For each explicitly configured web application, there should be one context element either in server.xml or in a separate context XML fragment file.

Once a Context has been defined, Catalina will attempt to match incoming HTTP requests to its context path. There is no limit to the number of Contexts that can be defined, as long as each Context is given its own unique context path. The context path, which is contained within the context, specifies where the application’s resources can be located. Applications can either be stored in a Web Application Archive (WAR) file, in which case they will be dynamically uncompressed as needed, or as organized unpacked resources in a directory.

Don’t do the same Context configuration work twice. Tomcat lets you save complete server configuration profiles, and apply them to new instances with a single click.

 
Once Catalina has matched a context with a request, the selected Context passes the request to the correct servlet to process the request, based on definitions contained in the web application deployment descriptor file.

Here is an example of context.xml

context.xml

<?xml version='1.0' encoding='utf-8'?>

<!--  +++++++++++++++++++++++++++++++++++++++++++++

This file is one of a suite of configuration files ...
  context.xml
  web.xml
  tomcat_user.xml
  server.xml
that we set up on our "deploying Apache httpd and Tomcat" course to
configure Tomcat and web applications that are running within it.

+++++++++++++++++++++++++++++++++++++++++++++++++++  -->

<!-- The contents of this file will be loaded for each web application -->

<Context reloadable="true" privileged="true">

<!-- **** Note - we have added in the reloadable and privileged attributes
to enable the invoker servlet and cgi support (other changes needed in
web.xml too for that, though **** -->

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Disable session persistence across Tomcat restarts -->

    <Manager pathname="" />

    <!-- Enable Comet connection tracking (provides events
         on session expiration as well as webapp lifecycle) -->

    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
</Context>
  • Context reloadable = “true” and privileged = “true” – to enable reloading and invoker servlet and cgi support.
  • WatchedResource = “web.xml” – we are setting this context.xml to monitor the changes made to the web.xml of the application being deployed.
  • Manager – specifying this will disable session persistence across tomcat restarts
  • Valve – specifies the connection tracker for the web application lifecycle.

The Default Context elements may be defined for multiple web applications and these can be configured individually. The application will override all that’s defined in this file.

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

Common Attributes of context.xml

  • 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.
  • containerSciFilter
    The regular expression that specifies which container provided SCIs should be filtered out and not used for this context. Matching uses java.util.regex.Matcher.find() so the regular expression only has to match a sub-string of the fully qualified class name of the container provided SCI for it to be filtered out. If not specified, no filtering will be applied.
  • 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.
  • docBasε
    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.
  • failCtxIfServletStartFails
    Set to true to have the context fail its startup if any servlet that has load-on-startup >=0 fails its own startup.
  • 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.
  • 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 falseis 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.
  • 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.
  • 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.
  • xmlBlockExternal
    If the value of this flag is true, the parsing of web.xml, web-fragment.xml, *.tld, *.jspx, *.tagx and tagPlugins.xml files for this web application will not permit external entities to be loaded. If not specified, the default value of true will be used.
  • xmlNamespaceAware
    If the value of this flag is true, the parsing of web.xml and web-fragment.xml files for this web application will be namespace-aware. Note that *.tld, *.jspx and *.tagx files are always parsed using a namespace-aware parser and that the tagPlugins.xml file (if any) is never parsed using a namespace-aware parser. Note also that 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 parsing of web.xml and web-fragment.xml files for this web application will use a validating parser. 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.
  • In summary, when an HTTP request is made, Catalina receives it, and passes it to the appropriate Context, which in turn passes the request to the appropriate servlet to serve it.

    In the event that the request does not match any specific context paths, Catalina passes the request to a Context whose context path is a zero-length string. This Context is required for Tomcat to run properly, because it is considered the “default” web application, responsible for processing requests that do not match any other specific context paths.

    For further reference: context.xml documentation in the Apache Tomcat website

    Alvin Reyes

    Alvin has an Information Technology Degree from Mapua Institute of Technology. During his studies, he was already heavily involved in a number of small to large projects where he primarily contributes by doing programming, analysis design. After graduating, he continued to do side projects on Mobile, Desktop and Web Applications.
    Subscribe
    Notify of
    guest

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    2 Comments
    Oldest
    Newest Most Voted
    Inline Feedbacks
    View all comments
    dave
    dave
    3 years ago

    Ok great….but where does it go? In conf somewhere? or in the web-inf of a webapp directory?

    tomcat
    tomcat
    3 years ago
    Reply to  dave

    in $CATALINA_HOME/conf

    Back to top button