4.6.3. Context

The Context element represents a web application, which runs within a particular virtual host.
The web application used to process a particular HTTP request is selected based on matching the longest possible prefix of the Request URI against the context path of every Context. Once selected, the Context selects the appropriate servlet to process the incoming request as defined by servlet mappings in the web application deployment descriptor file (/WEB-INF/web.xml in the web application directory hierarchy).
You may define an arbitrary number of Context elements; however, each Context must have a unique context path. In addition, one Context with an empty context path (zero-length string) must be defined. This Context is used as the default web application for the virtual host and processes any requests with an unmatched context path.

4.6.3.1. Defining Context

Contexts can be specified with explicitly defined Context elements or they can be created automatically.
To specify the context explicitly, define the Context element in some of the following locations depending on the desired behavior:
  • $JBOSS_SERVER_HOME/conf/context.xml: the Context element is loaded by all web applications on the server.
  • $JBOSS_SERVER_HOME/conf/enginename/hostname/context.xml file: the Context element is loaded by all web applications on the host.
  • $JBOSS_SERVER_HOME/conf/enginename/hostname/ directory as individual files with the xml extension: The name of the xml file is used as the context path. To define a multi-level context path, separate the domains with the hash sign (that is, #); for example, the foo#bar.xml file will be resolved as the context path /foo/bar. Define the default web application file as the ROOT.xml file.
  • /META-INF/context.xml in the web application: this context definition is applied only if there is no context file for the application in the $JBOSS_SERVER_HOME/conf/enginename/hostname/ directory.
    If the web application is deployed as a WAR archive, its /META-INF/context.xml file is copied to $JBOSS_SERVER_HOME/conf/enginename/hostname/ directory and renamed to match the application's context path. Mind that the file will not be replaced if a new WAR with a newer /META-INF/context.xml file is placed in the host's appBase.
  • In a Host element in the main server.xml file.

Important

It is not recommended to place the <Context> element in the server.xml file. Such context definitions require more invasive approach when modifying the Context configuration since the main $JBOSS_SERVER_HOME/conf/server.xml file cannot be reloaded without restarting the JBoss Web server.

Table 4.8. Context Element Attributes

Attribute Description
backgroundProcessorDelay
Delay between the invocation of the backgroundProcess method on the context and the invocation of the backgroundProcess method on the child containers of the context (-1 by default and the context relies therefore on the background processing of its parent host)
If set to a positive value, the context produces a thread. The thread waits for the specified amount of time and then invokes the backgroundProcess method on the context and all its child containers.
If the delay of a child container is not negative, the child container is using its own processing thread.
A context uses background processing to perform session expiration and class monitoring for reloading.
className
Class implementing the Context
This class must implement the org.apache.catalina.Context interface. If not specified, the org.apache.catalina.core.StandardContext standard value is used.
cookies
Use cookies for session identifier communication if supported by the client (true by default)
Set to false if you want to disable the feature. The server relies then only on URL rewriting performed by the application.
crossContext
Returning of the context to other web applications (defines the response sent to the ServletContext.getContext() call; set to false by default and the request dispatcher is filled with the NULL value)
If set to true, the context returns the request dispatcher with the ServletContext value to the requesting web application. The requesting web application must run on the same virtual host.
docBase
Document Base, that is the Context Root directory, of the web application or the pathname to the web application archive file
You can define the docBase value as an absolute pathname to the directory or WAR file, or as a pathname relative to the appBase directory of the parent Host.
override
Overriding of explicit settings in the Context element by the corresponding settings in the global or host default contexts (set to use the default context setting)
Set to true to activate the overriding.
If the docBase value is defined as a symbolic link, changes to the symbolic link take effect only after the JBoss Web server is restarted or after the context is undeployed and then re-deployed: context reload is not sufficient.
privileged
Enabling/disabling the context to use container servlets, such as the manager servlet
The privileged attribute changes the context's parent class loader to the Server class loader rather than the Shared class loader (the Common class loader is used for the Server and the Shared class loaders by default).
Set to true to allow the context to use container servlets.
path
Context path of the web application.
The path is matched against the beginning of each request URI to select the appropriate web application for the request processing. Therefore all context paths within a particular host must be unique.
To use the context as the default web application for the host, specify the context path as an empty string (""). The default web application processes any requests, which could not be assigned to any other Context.
Do not set the value of this field unless you want to define the context statically in server.xml as its value is inferred from the file names used for the xml context file or the docBase property.
reloadable
Enabling/disabling the monitoring of class changes in /WEB-INF/classes/ and /WEB-INF/lib and automatic reloading of the web application if a change is detected (false by default).
Note that this feature requires significant runtime overhead and is not recommended for production applications (to reload deployed applications, use the Manager web application).
WrapperClass
Class implementing the org.apache.catalina.Wrapper interface used for servlets in this context
If no value is specified, the standard default value is used.

Table 4.9. Additional Element Attributes of the Standard Context Element Implementation (org.apache.catalina.core.StandardContext)

Attribute Description
allowLinking
Enabling/disabling the usage of symlinks inside the web application if the symlinks point to resources outside of the web application Base directory (set to false by default)
Set to true to allow such symlinks in the web application.
This property must not be set to true on Windows platforms or any other operating systems with case-insensitive file systems as this can result in various security problem, such as disabling of case sensitivity checks and possible disclosure of JSP source code.
antiJARLocking
Enabling/disabling extra measures for keeping JAR files unlocked even if being accessed through URLs (false by default)
Enabling this feature prolongs the start time of applications.
antiResourceLocking
Enabling/disabling file locking by JBoss Web (false by default)
Enabling this features allows full hot deploy and undeploy on platforms or configurations where file locking can occur. However, enabling this feature significantly impacts the start time of applications along with other side effects, such as disabling of JSP reloading in a running server and application deletion on JBoss Web shutdown if the application is outside of the appBase for the Host (in the webapps directory by default).
cacheMaxSize
Defines the maximum size of the static resource cache in kilobytes (set to 10240, that is 10 megabytes by default)
cacheTTL
Defines the amount of time in milliseconds between cache entries revalidation (set to 5000, that is 5 seconds, by default)
cachingAllowed
Enabling the usage of the cache for static resources (set to true by default)
caseSensitive
Enabling case sensitivity checks (set to false by default)
Set to false to disable all case sensitivity checks.
Do not set the property false on Windows platforms or any operating systems that do not have a case sensitive file system as this might result in various security issues including JSP source code disclosure.
processTlds
Enabling processing of tag library descriptors (TLD) on context start up (set to true by default)
Set to false if TLDs are not part of the web application.
swallowOutput
Enabling redirection of System.out and System.err output to the web application logger (false by default)
Set to true to redirect the output to the web application logger.
tldNamespaceAware
Enabling the TLD files XML validation to be namespace-aware (false by default)
The feature is usually enabled along with tldValidation.
tldValidation
Enabling the TLD files XML validation on context start up (false by default)
unloadDelay
Amount of time (in ms) the container waits for servlets to unload (2000 ms by default)
unpackWAR
Enabling unpacking of compressed web applications before they are run (true by default)
useNaming
Enabling a JNDI InitialContext that is compatible with Java Enterprise Edition (JEE) conventions (true by default)
workDir
Path to a directory provided by this Context for temporary read-write use to the servlets in the associated web application
The directory is visible for servlets in the web application through the javax.servlet.context.tempdir servlet context attribute (of type java.io.File) named as described in the Servlet Specification. If not specified, a suitable directory under $JBOSS_SERVER_HOME/work/ is provided.
Context FAQs
Q: What is context.xml?
Q: Why is context.xml placed in WEB-INF in JBoss deployments but META-INF in Tomcat?
Q: What is the difference between jboss-web.xml and context.xml?
Q: Why is context.xml needed at all?
Q: Why is not context.xml usage better documented?
Q: How do I remove the jsessionid from URLs?
Context FAQs
Q:
What is context.xml?
A:
context.xml is a Tomcat configuration file that is used to configure many webapp settings on a per-webapp basis.
Recent versions of JBoss Enterprise Application Platform allow you to place a context.xml file in the WEB-INF directory of your WAR archive.
The JBoss Enterprise Application Platform distribution comes with some in-place context.xml files. They can be found at <JBOSS_HOME>/server/<PROFILE>/deploy/management/console-mgr.sar/web-console.war/WEB-INF/context.xml and <JBOSS_HOME>/server/<PROFILE>/deploy/jbossweb.sar/context.xml.
Q:
Why is context.xml placed in WEB-INF in JBoss deployments but META-INF in Tomcat?
A:
The justification for this is that a WAR archive does not require a META-INF directory however a WEB-INF directory is required.
Q:
What is the difference between jboss-web.xml and context.xml?
A:
Because there is some overlap between jboss-web.xml and context.xml, there is some confusion over how and when context.xml should be used.
The general rule is that if you can set a parameter in jboss-web.xml then the context.xml equivalent is ignored.
Q:
Why is context.xml needed at all?
A:
The reason we need context.xml is that there are some things that are used to configure Tomcat as opposed to the JBoss wrapper around Tomcat. Some examples of ways you would use context.xml are found here:
Q:
Why is not context.xml usage better documented?
A:
Partially because context.xml has no DTD. There is no exhaustive list of possible elements and overlaps with jboss-web.xml.
The path attribute is the most commonly cited overlap jboss-web.xml. You should set the context-root in jboss-web.xml.
Q:
How do I remove the jsessionid from URLs?
A:
To have the jsessionids removed from URLs, do the following:
  1. Create the following JsessionIdRemoveFilter.java in your code base:
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    
    public class JsessionIdRemoveFilter implements Filter {
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
    
            if (!(req instanceof HttpServletRequest)) {
                chain.doFilter(req, res);
                return;
            }
    
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            // Redirect requests with JSESSIONID in URL to clean version (old links bookmarked/stored by bots)
            // This is ONLY triggered if the request did not also contain a JSESSIONID cookie! Which should be fine for bots...
            if (request.isRequestedSessionIdFromURL()) {
                String url = request.getRequestURL()
                             .append(request.getQueryString() != null ? "?"+request.getQueryString() : "")
                             .toString();
                response.setHeader("Location", url);
                response.sendError(HttpServletResponse.SC_MOVED_PERMANENTLY);
                return;
            }
    
            // Prevent rendering of JSESSIONID in URLs for all outgoing links
            HttpServletResponseWrapper wrappedResponse =
                new HttpServletResponseWrapper(response) {
                    @Override
                    public String encodeRedirectUrl(String url) {
                        return url;
                    }
    
                    @Override
                    public String encodeRedirectURL(String url) {
                        return url;
                    }
    
                    @Override
                    public String encodeUrl(String url) {
                        return url;
                    }
    
                    @Override
                    public String encodeURL(String url) {
                        return url;
                    }
                };
            chain.doFilter(req, wrappedResponse);
    
        }
    
         public void destroy() {
         }
    
         public void init(FilterConfig arg0) throws ServletException {
         }
    }
    
  2. Add the following to the web.xml file to have the filter deployed:
    <filter>
      <filter-name>JsessionIdRemoveFilter</filter-name>
      <filter-class>com.example.JsessionIdRemoveFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>JsessionIdRemoveFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
As this disables URL rewriting, the site no longer works without cookies and an additional cookie check might be needed.