Apache Tomcat Configuration Reference

http://www.jaxmao.org/tomcat-docs/config/index.html

概 述

Printer Friendly Version
print-friendly
version
Overview

这个手册包括可能被包括在conf/server.xml文件里来配置Tomcat 5 Servlet/JSP容器行为的所有配置指令的参考信息。这里没有描述哪些配置指令应该被怎样用来执行哪些特殊的任务——关于这些,参看主要索引页面(main index page)里的各种HOW-TO文档资料。

关于配置元素的描述被组织成下列几种主要类型:

  • 最上层元素 - <Server>是整个配置文件的根元素,而<Service>代表与Engine相关联的一组连接器。
  • 连接器 - 代表发送请求的(以及接受回应的)外部客户与某个特定服务之间的界面。
  • 容器 - 代表那些具有处理接收到的请求和产生相应的回应功能的组件。一个Engine为一个Service处理所有的请求,一个Host为一个特殊的虚拟机处理所有的请求,一个Context为一个特定的web应用程序处理所有的请求。
  • 嵌套的组件 - 代表那些可以被嵌套在一个容器元素里的元素。有些元素可以嵌套在任何容器里,而另外一些则仅仅能被嵌套在一个Context里。

对于每个元素,其相应的文档资料遵循下面这个一般大纲:

  • 简介 - 关于这个特殊组件的全面描述。这里会有一个被一个或多个标准实现执行的相应的Java界面(在org.apache.catalina软件包里)。
  • 属性 - 对这个元素合法的一组属性。通常,这组属性又被再分为两组:一组是被这个相应的Java界面的所有实现支持的公用属性,另一组是执行这个界面的某一特别的Java类所特定的标准实现属性。所必需的属性名称是被强调粗写的(bolded)。
  • 嵌套的组件 - 列举哪些嵌套的组件可以被合法地嵌套在这个元素里边。
  • 特别性能 - 描述了被这个界面的标准实现支持的多种特别性能(每个元素类型所特定的)的配置。

服务器组件

Printer Friendly Version
print-friendly
version
Introduction

一个Server(服务器)元素代表整个Catalina servlet容器。因此,它必须是conf/server.xml配置文件里面的最外层元素。它的属性代表了这个servlet容器的总体特征。

Attributes
Common Attributes

Server(服务器)的所有实现支持下列属性:

AttributeDescription
className

要使用的implementation的Java类名。这个类必须执行org.apache.catalina.Server 接口。如果没有指定类名,将使用标准实现。

port

TCP/IP端口数目,这个服务器在此等待关闭。这个连接必须从正在运行这个Tomcat实例的相同的服务器计算机上被初始化。

shutdown

要关闭Tomcat,必须通过TCP/IP连接到指定的端口数目来被接受的命令字符串。

Standard Implementation

这个服务器的标准实现是org.apache.catalina.core.StandardServer。它支持下面其他属性(除了上面列出的通用属性外):

AttributeDescription
Nested Components

下列组件可以被嵌套在一个Server(服务器)元素里面:

Special Features

Server(服务器)元素没有任何专有特征。

服务组件

Printer Friendly Version
print-friendly
version
Introduction

一个Service元素代表一个或多个连接器(Connector)组件的组合,这些连接器组件共享一个Engine component来处理进入的请求。一个或多个Service元素可以嵌套在一个Server(服务器)元素里面。

Attributes
Common Attributes

Service的所有实现支持下列属性:

AttributeDescription
className

要使用的implementation的Java类名。这个类必须执行org.apache.catalina.Service 接口。如果没有指定类名,将使用标准实现。

name

这个Service元素所显示的名字,如果你使用标准的Catalina组件,它会被包括在log messages里面。每个与某一特殊的Server(服务器)相关联的Service的名字必须是独特的。

Standard Implementation

这个Service的标准实现是org.apache.catalina.core.StandardService 。它支持下面其他属性(除了上面列出的通用属性外):

AttributeDescription
Nested Components

唯一的能够嵌套在一个Service元素里的组件是一个或多个Connector元素,后面紧跟着一个(仅仅一个)Engine元素。

Special Features

Service元素没有任何专有特征。

The HTTP Connector

Printer Friendly Version
print-friendly
version
Introduction

HTTP Connector代表一个支持HTTP/1.1协定的Connector组件。它使Catalina在具有执行servlets和JSP页面能力之外,还能够作为独立的web服务器运作。这个组件的一个特殊的实例是在这个服务器上的一个特定的TCP端口数目上监听连接。一个或多个这样的Connectors(连接器)可以配置为一单个Service的一部分,每一个Connectors(连接器)转向它相关的Engine去处理请求和产生回应。

If you wish to configure the Connector that is used for connections to web servers using the AJP protocol (such as the mod_jk 1.2.x connector for Apache 1.3), see here instead.

在服务器启动时间,这个Connector将产生许多处理请求的线程(根据配置的minSpareThreads属性的值)。每个进入的请求在这个请求其间需要一个线程。如果同时发生的多个请求被接收到,它们可以被当前可使用的处理请求的线程来处理,另外的线程将被产生直到所配置的最大数(就是maxThreads属性的值)。如果还有同时发生的多个请求被接收到,它们就在Connector所产生的server socket里面被堆积起来, 直到所配置的最大数为止(就是acceptCount属性的值)。其他更多的同时发生的请求将会收到"connection refused" 的错误信息,直到有资源能处理它们为止。

Attributes
Common Attributes

Connector的所有实现支持下列属性:

AttributeDescription
allowTrace

一个布林值,可以用来启用或取消TRACE HTTP方法。如果没有指定,这个属性被设置为false。

emptySessionPath

If set to true, all paths for session cookies will be set to /. This can be useful for portlet specification implementations, but will greatly affect performance if many applications are accessed on a given server by the client. If not specified, this attribute is set to false.

enableLookups

如果你想为了返回远程客户的实际主机名而调用request.getRemoteHost()方法来执行DNS查询,就把它设置为true。要跳过DNS查询并返回String形式的IP地址,就把它设置为false(这样可以提高性能)。在缺省情况下,DNS查询是可以启用的。

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

maxSavePostSize

The maximum size in bytes of the POST which will be saved/buffered by the container during FORM or CLIENT-CERT authentication. For both types of authentication, the POST will be saved/buffered before the user is authenticated. For CLIENT-CERT authentication, the POST is buffered for the duration of the SSL handshake and the buffer emptied when the request is processed. For FORM authentication the POST is saved whilst the user is re-directed to the login form and is retained until the user successfully authenticates or the session associated with the authentication request expires. The limit can be disabled by setting this attribute to -1. Setting the attribute to zero will disable the saving of POST data during authentication . If not specified, this attribute is set to 4096 (4 kilobytes).

protocol

This attribute value must be HTTP/1.1 to use the HTTP handler, which is the default.

proxyName

If this Connector is being used in a proxy configuration, configure this attribute to specify the server name to be returned for calls to request.getServerName(). See Proxy Support for more information.

proxyPort

If this Connector is being used in a proxy configuration, configure this attribute to specify the server port to be returned for calls to request.getServerPort(). See Proxy Support for more information.

redirectPort

If this Connector is supporting non-SSL requests, and a request is received for which a matching <security-constraint> requires SSL transport, Catalina will automatically redirect the request to the port number specified here.

scheme

Set this attribute to the name of the protocol you wish to have returned by calls to request.getScheme(). For example, you would set this attribute to "https" for an SSL Connector. The default value is "http". See SSL Support for more information.

secure

Set this attribute to true if you wish to have calls to request.isSecure() to return true for requests received by this Connector (you would want this on an SSL Connector). The default value is false.

URIEncoding

This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.

useBodyEncodingForURI

This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitely set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.

useIPVHosts

Set this attribute to true to cause Tomcat to use the IP address that the request was recieved on to determine the Host to send the request to. The default value is false.

xpoweredBy

Set this attribute to true to cause Tomcat to advertise support for the Servlet specification using the header recommended in the specification. The default value is false.

Standard Implementation

HTTP supports the following additional attributes (in addition to the common attributes listed above):

AttributeDescription
acceptCount

The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 10.

address

对于具有不止一个IP地址的服务器来说,这个属性指定了哪一个地址将被用来在指定的端口监听。在缺省情况下,这个端口会被使用在所有与这个服务器相关的IP地址上。

bufferSize

The size (in bytes) of the buffer to be provided for input streams created by this connector. By default, buffers of 2048 bytes will be provided.

compressableMimeType

The value is a comma separated list of MIME types for which HTTP compression may be used. The default value is text/html,text/xml,text/plain.

compression

The Connector may use HTTP/1.1 GZIP compression in an attempt to save server bandwidth. The acceptable values for the parameter is "off" (disable compression), "on" (allow compression, which causes text data to be compressed), "force" (forces compression in all cases), or a numerical integer value (which is equivalent to "on", but specifies the minimum amount of data before the output is compressed). If the content-length is not known and compression is set to "on" or more aggressive, the output will also be compressed. If not specified, this attribute is set to "off".

connectionLinger

The number of milliseconds during which the sockets used by this Connector will linger when they are closed. The default value is -1 (socket linger is disabled).

connectionTimeout

The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. The default value is 60000 (i.e. 60 seconds).

disableUploadTimeout

This flag allows the servlet container to use a different, longer connection timeout while a servlet is being executed, which in the end allows either the servlet a longer amount of time to complete its execution, or a longer timeout during data upload. If not specified, this attribute is set to "true".

maxHttpHeaderSize

The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

maxKeepAliveRequests

The maximum number of HTTP requests which can be pipelined until the connection is closed by the server. Setting this attribute to 1 will disable HTTP/1.0 keep-alive, as well as HTTP/1.1 keep-alive and pipelining. Setting this to -1 will allow an unlimited amount of pipelined or keep-alive HTTP requests. If not specified, this attribute is set to 100.

maxSpareThreads

The maximum number of unused request processing threads that will be allowed to exist until the thread pool starts stopping the unnecessary threads. The default value is 50.

maxThreads

The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200.

minSpareThreads

The number of request processing threads that will be created when this Connector is first started. The connector will also make sure it has the specified number of idle processing threads available. This attribute should be set to a value smaller than that set for maxThreads. The default value is 4.

noCompressionUserAgents

The value is a comma separated list of regular expressions matching user-agents of HTTP clients for which compression should not be used, because these clients, although they do advertise support for the feature, have a broken implementation. The default value is an empty String (regexp matching disabled).

port

The TCP port number on which this Connector will create a server socket and await incoming connections. Your operating system will allow only one server application to listen to a particular port number on a particular IP address.

restrictedUserAgents

The value is a comma separated list of regular expressions matching user-agents of HTTP clients for which HTTP/1.1 or HTTP/1.0 keep alive should not be used, even if the clients advertise support for these features. The default value is an empty String (regexp matching disabled).

server

The Server header for the http response. Unless your paranoid, you won't need this feature.

socketBuffer

The size (in bytes) of the buffer to be provided for socket output buffering. -1 can be specified to disable the use of a buffer. By default, a buffers of 9000 bytes will be used.

strategy

The thread pooling strategy which will be used. The default strategy does not use a master thread, but a more conventional strategy using a master listener thread can be used by setting "ms" as this attribute's value. The master strategy will work significantly better using the threadPriority attribute, which will apply only to the thread which listens on the server socket. This is set to lf by default.

tcpNoDelay

If set to true, the TCP_NO_DELAY option will be set on the server socket, which improves performance under most circumstances. This is set to true by default.

threadPriority

The priority of the request processing threads within the JVM. The default value is java.lang.Thread#NORM_PRIORITY. See the JavaDoc for the java.lang.Thread class for more details on what this priority means.

Nested Components

None at this time.

Special Features
HTTP/1.1 and HTTP/1.0 Support

This Connector supports all of the required features of the HTTP/1.1 protocol, as described in RFC 2616, including persistent connections, pipelining, expectations and chunked encoding. If the client (typically a browser) supports only HTTP/1.0, the Connector will gracefully fall back to supporting this protocol as well. No special configuration is required to enable this support. The Connector also supports HTTP/1.0 keep-alive.

RFC 2616 requires that HTTP servers always begin their responses with the highest HTTP version that they claim to support. Therefore, this Connector will always return HTTP/1.1 at the beginning of its responses.

Proxy Support

The proxyName and proxyPort attributes can be used when Tomcat is run behind a proxy server. These attributes modify the values returned to web applications that call the request.getServerName() and request.getServerPort() methods, which are often used to construct absolute URLs for redirects. Without configuring these attributes, the values returned would reflect the server name and port on which the connection from the proxy server was received, rather than the server name and port to whom the client directed the original request.

For more information, see the Proxy Support HOW-TO.

SSL Support

You can enable SSL support for a particular instance of this Connector by setting the secure attribute to true. In addition, you may need to configure the following attributes:

AttributeDescription
algorithm

The certificate encoding algorithm to be used. If not specified, the default value is SunX509.

clientAuth

Set to true if you want the SSL stack to require a valid certificate chain from the client before accepting a connection. Set to want if you want the SSL stack to request a client Certificate, but not fail if one isn't presented. A false value (which is the default) will not require a certificate chain unless the client requests a resource protected by a security constraint that uses CLIENT-CERT authentication. See the SSL HowTo for an example.

keystoreFile

The pathname of the keystore file where you have stored the server certificate to be loaded. By default, the pathname is the file ".keystore" in the operating system home directory of the user that is running Tomcat.

keystorePass

The password used to access the server certificate from the specified keystore file. The default value is "changeit".

keystoreType

The type of keystore file to be used for the server certificate. If not specified, the default value is "JKS".

sslProtocol

The version of the SSL protocol to use. If not specified, the default is "TLS".

ciphers

A comma seperated list of the encryption ciphers that may be used. If not specified, then any available cipher may be used.

For more information, see the SSL Configuration HOW-TO.

The AJP Connector

Printer Friendly Version
print-friendly
version
Introduction

The AJP Connector element represents a Connector component that communicates with a web connector via the AJP protocol. This is used for cases where you wish to invisibly integrate Tomcat 5 into an existing (or new) Apache installation, and you want Apache to handle the static content contained in the web application, and/or utilize Apache's SSL processing.

This connector supports load balancing when used in conjunction with the jvmRoute attribute of the Engine.

The native connectors supported with this Tomcat release are:

  • JK 1.2.x with any of the supported servers
  • mod_proxy on Apache httpd 2.x (included by default in Apache HTTP Server 2.2), with AJP enabled

Other native connectors supporting AJP may work, but are no longer supported.

Attributes
Common Attributes

Connector的所有实现支持下列属性:

AttributeDescription
allowTrace

一个布林值,可以用来启用或取消TRACE HTTP方法。如果没有指定,这个属性被设置为false。

emptySessionPath

If set to true, all paths for session cookies will be set to /. This can be useful for portlet specification implementations, but will greatly affect performance if many applications are accessed on a given server by the client. If not specified, this attribute is set to false.

enableLookups

如果你想为了返回远程客户的实际主机名而调用request.getRemoteHost()方法来执行DNS查询,就把它设置为true。要跳过DNS查询并返回String形式的IP地址,就把它设置为false(这样可以提高性能)。在缺省情况下,DNS查询是可以启用的。

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The feature can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

maxSavePostSize

The maximum size in bytes of the POST which will be saved/buffered by the container during FORM or CLIENT-CERT authentication. For both types of authentication, the POST will be saved/buffered before the user is authenticated. For CLIENT-CERT authentication, the POST is buffered for the duration of the SSL handshake and the buffer emptied when the request is processed. For FORM authentication the POST is saved whilst the user is re-directed to the login form and is retained until the user successfully authenticates or the session associated with the authentication request expires. The limit can be disabled by setting this attribute to -1. Setting the attribute to zero will disable the saving of POST data during authentication. If not specified, this attribute is set to 4096 (4 kilobytes).

protocol

This attribute value must be AJP/1.3 to use the AJP handler.

proxyName

If this Connector is being used in a proxy configuration, configure this attribute to specify the server name to be returned for calls to request.getServerName(). See Proxy Support for more information.

proxyPort

If this Connector is being used in a proxy configuration, configure this attribute to specify the server port to be returned for calls to request.getServerPort(). See Proxy Support for more information.

redirectPort

If this Connector is supporting non-SSL requests, and a request is received for which a matching <security-constraint> requires SSL transport, Catalina will automatically redirect the request to the port number specified here.

request.registerRequests

This attribute controls request registration for JMX monitoring of the Connector. It is enabled by default, but may be turned it off to save a bit of memory.

scheme

Set this attribute to the name of the protocol you wish to have returned by calls to request.getScheme(). For example, you would set this attribute to "https" for an SSL Connector. The default value is "http". See SSL Support for more information.

secure

Set this attribute to true if you wish to have calls to request.isSecure() to return true for requests received by this Connector (you would want this on an SSL Connector). The default value is false.

URIEncoding

This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.

useBodyEncodingForURI

This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitely set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.

useIPVHosts

Set this attribute to true to cause Tomcat to use the ServerName passed by the native web server to determine the Host to send the request to. The default value is false.

xpoweredBy

Set this attribute to true to cause Tomcat to advertise support for the Srevlet specification using the header recommended in the specification. The default value is false.

Standard Implementation

To use AJP, you must specify the protocol attribute (see above).

This implementation supports the AJP 1.3 protocol.

It supports the following additional attributes (in addition to the common attributes listed above):

AttributeDescription
address

For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server. A value of 127.0.0.1 indicates that the Connector will only listen on the loopback interface.

backlog

The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 10.

bufferSize

The size of the output buffer to use. If less than or equal to zero, then output buffering is disabled. The default value is -1 (i.e. buffering disabled)

connectionTimeout

The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. The default value is infinite (i.e. no timeout).

minProcessors弃用

The minimum number of processors to start at initialization time. If not specified, this atttribute is set to 5.

maxProcessors弃用

The maximum number of processors allowed. This should be set to a value that is greater than or equal to the maximum number of concurrent connections the remote web server can open to Tomcat simultaneously. For example, if the web server is Apache 1.x or 2.x Tomcat's maxProcessors should be set to the value of Apache's maxClients directive.

A maxProcessors value of zero (0) signifies that the number of processors is unlimited. If not specified, this atttribute defaults to 20.

maxSpareThreads

The maximum number of unused request processing threads that will be allowed to exist until the thread pool starts stopping the unnecessary threads. The default value is 50.

maxThreads

The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200.

minSpareThreads

The number of request processing threads that will be created when this Connector is first started. The connector will also make sure it has the specified number of idle processing threads available. This attribute should be set to a value smaller than that set for maxThreads. The default value is 4.

port

The TCP port number on which this Connector will create a server socket and await incoming connections. Your operating system will allow only one server application to listen to a particular port number on a particular IP address.

tcpNoDelay

If set to true, the TCP_NO_DELAY option will be set on the server socket, which improves performance under most circumstances. This is set to true by default.

tomcatAuthentication

If set to true, the authetication will be done in Tomcat. Otherwise, the authenticated principal will be propagated from the native webaserver and used for authorization in Tomcat. The default value is true.

Nested Components

None at this time.

The Context Container

Printer Friendly Version
print-friendly
version
Introduction

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 in the web application deployment descriptor file (which MUST be located at /WEB-INF/web.xml within the web app's directory hierarchy).

You may define as many Context elements as you wish. Each such Context MUST have a unique context path. 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.

For Tomcat 5, unlike Tomcat 4.x, it is NOT recommended to place <Context> elements directly in the server.xml file. This is because it makes modifing the Context configuration more invasive since the main conf/server.xml file cannot be reloaded without restarting Tomcat.

Context elements may be explicitly defined:

  • in the $CATALINA_HOME/conf/context.xml file: the Context element information will be loaded by all webapps
  • in the $CATALINA_HOME/conf/[enginename]/[hostname]/context.xml.default file: the Context element information will be loaded by all webapps of that host
  • in individual files (with a ".xml" extension) in the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml) extension will be used as the context path. Multi-level context paths may be defined using #, e.g. context#path.xml. The default web application may be defined by using a file called ROOT.xml.
  • if the previous file was not found for this application, in an individual file at /META-INF/context.xml inside the application files
  • inside a Host element in the main conf/server.xml

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.

在下面的描述中使用变量名$CATALINA_HOME来代指Tomcat5所安装的目录地址,这是一个基础目录(base directory),其他的相关路径由它而派生。不过,如果你已经把Tomcat设置成多个体实例(multiple instances),并且设立了一个$CATALINA_BASE目录,那么你就应使用$CATALINA_BASE而不是$CATALINA_HOME作为参照。

Attributes
Common Attributes

Context的所有实现支持下列属性:

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

override

Set to true to have explicit settings in this Context element override any corresponding settings in the default settings associated with the owning Host. The default is false.

privileged

Set to true to allow this context to use container servlets, like the manager servlet.

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. The value of this field must not be set except when statically defining a Context in server.xml, as it will be infered from the filenames used for either the .xml context file or the docBase.

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.

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.

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):

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

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.

Please note that setting this to true has some side effects, including the disabling of JSP reloading in a running server: see Bugzilla 37668.

cacheMaxSize

Maximum size of the static resource cache in kilobytes. If not specified, the default value is 10240 (10 megabytes).

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.

caseSensitive

If the value of this flag is true, all case sensitivity checks will be disabled. If not specified, the default value of the flag is true.

NOTE: This flag MUST NOT be set to false 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.

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.

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. The default value for this flag is false, and setting it 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. The default value for this flag is false, and setting it to true will incur a performance penalty.

unloadDelay

Amount of ms that the container will wait for servlets to unload. If not specified, the default value of the flag is 2000 ms.

unpackWAR

If true, Tomcat will unpack all compressed web applications before running them. If not specified, the default value is true.

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_HOME/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 is 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 path="/examples" ...>
  ...
  <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 automtically 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:

AttributeDescription
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</param-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:

AttributeDescription
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 one of the legal values for <env-entry-type> in the web application deployment descriptor: java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Short, or java.lang.String.

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 it will be notified about the occurrence of the coresponding lifecycle events. Configuration of such a listener looks like this:

<Context path="/examples" ...>
  ...
  <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 a configured list of "accept" and/or "deny" filters, which are defined using the Regular Expression syntax supported by the Jakarta Regexp regular expression library. Requests that come from locations that are not accepted will be rejected with an HTTP "Forbidden" error. Example filter declarations:

<Context path="/examples" ...>
  ...
  <Valve className="org.apache.catalina.valves.RemoteHostValve"
         allow="*.mycompany.com,www.yourcompany.com"/>
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         deny="192.168.1.*"/>
  ...
</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:

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

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.

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:

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

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:

AttributeDescription
factory

The class name for the JNDI object factory.

The Engine Container

Printer Friendly Version
print-friendly
version
Introduction

The Engine element represents the entire request processing machinery associated with a particular Catalina Service. It receives and processes all requests from one or more Connectors, and returns the completed response to the Connector for ultimate transmission back to the client.

Exactly one Engine element MUST be nested inside a Service element, following all of the corresponding Connector elements associated with this Service.

Attributes
Common Attributes

Engine的所有实现支持下列属性:

AttributeDescription
backgroundProcessorDelay

This value represents the delay in seconds between the invocation of the backgroundProcess method on this engine and its child containers, including all hosts and contexts. 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 engine and all its child containers. If not specified, the default value for this attribute is 10, which represent a 10 seconds delay.

className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Engine interface. If not specified, the standard value (defined below) will be used.

defaultHost

The default host name, which identifies the Host that will process requests directed to host names on this server, but which are not configured in this configuration file. This name MUST match the name attributes of one of the Host elements nested immediately inside.

jvmRoute

Identifier which must be used in load balancing scenarios to enable session affinity. The identifier, which must be unique across all Tomcat 5 servers which participate in the cluster, will be appended to the generated session identifier, therefore allowing the front end proxy to always forward a particular session to the same Tomcat 5 instance.

name

Logical name of this Engine, used in log and error messages. When using muliple Service elements in the same Server, each Engine MUST be assigned a unique name.

Standard Implementation

The standard implementation of Engine is org.apache.catalina.core.StandardEngine. It supports the following additional attributes (in addition to the common attributes listed above):

AttributeDescription
Nested Components

You can nest one or more Host elements inside this Engine element, each representing a different virtual host associated with this server. At least one Host is required, and one of the nested Hosts MUST have a name that matches the name specified for the defaultHost attribute, listed above.

You can nest at most one instance of the following utility components by nesting a corresponding element inside your Engine element:

  • Realm - Configure a realm that will allow its database of users, and their associated roles, to be shared across all Hosts and Contexts nested inside this Engine, unless overridden by a Realm configuration at a lower level.
Special Features
Logging

An engine is associated with the org.apache.catalina.core.ContainerBase.[enginename] 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:

<Engine name="Standalone" ...>
  ...
  <Valve className="org.apache.catalina.valves.AccessLogValve"
         prefix="catalina_access_log." suffix=".txt"
         pattern="common"/>
  ...
</Engine>

See Access Log Valve for more information on the configuration attributes that are supported.

Lifecycle Listeners

If you have implemented a Java object that needs to know when this Engine 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 it will be notified about the occurrence of the coresponding lifecycle events. Configuration of such a listener looks like this:

<Engine name="Standalone" ...>
  ...
  <Listener className="com.mycompany.mypackage.MyListener" ... >
  ...
</Engine>

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 a configured list of "accept" and/or "deny" filters, which are defined using the Regular Expression syntax supported by the Jakarta Regexp regular expression library. Requests that come from locations that are not accepted will be rejected with an HTTP "Forbidden" error. Example filter declarations:

<Engine name="Standalone" ...>
  ...
  <Valve className="org.apache.catalina.valves.RemoteHostValve"
         allow="*.mycompany.com,www.yourcompany.com"/>
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         deny="192.168.1.*"/>
  ...
</Engine>

See Remote Address Filter and Remote Host Filter for more information about the configuration options that are supported.

The Host Container

Printer Friendly Version
print-friendly
version
Introduction

The Host element represents a virtual host, which is an association of a network name for a server (such as "www.mycompany.com" with the particular server on which Catalina is running. In order to be effective, this name must be registered in the Domain Name Service (DNS) server that manages the Internet domain you belong to - contact your Network Administrator for more information.

In many cases, System Administrators wish to associate more than one network name (such as www.mycompany.com and company.com) with the same virtual host and applications. This can be accomplished using the Host Name Aliases feature discussed below.

One or more Host elements are nested inside an Engine element. Inside the Host element, you can nest Context elements for the web applications associated with this virtual host. Exactly one of the Hosts associated with each Engine MUST have a name matching the defaultHost attribute of that Engine.

在下面的描述中使用变量名$CATALINA_HOME来代指Tomcat5所安装的目录地址,这是一个基础目录(base directory),其他的相关路径由它而派生。不过,如果你已经把Tomcat设置成多个体实例(multiple instances),并且设立了一个$CATALINA_BASE目录,那么你就应使用$CATALINA_BASE而不是$CATALINA_HOME作为参照。

Attributes
Common Attributes

Host的所有实现支持下列属性:

AttributeDescription
appBase

The Application Base directory for this virtual host. This is the pathname of a directory that may contain web applications to be deployed on this virtual host. You may specify an absolute pathname for this directory, or a pathname that is relative to the $CATALINA_BASE directory. See Automatic Application Deployment for more information on automatic recognition and deployment of web applications to be deployed automatically.

autoDeploy

This flag value indicates if new web applications, dropped in to the appBase directory while Tomcat is running, should be automatically deployed. The flag's value defaults to true. See Automatic Application Deployment for more information.

backgroundProcessorDelay

This value represents the delay in seconds between the invocation of the backgroundProcess method on this host and its child containers, including all contexts. 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 host will use background processing to perform live web application deployment related tasks. If not specified, the default value for this attribute is -1, which means the host will rely on the background processing thread of its parent engine.

className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Host interface. If not specified, the standard value (defined below) will be used.

deployOnStartup

This flag value indicates if web applications from this host should be automatically deployed by the host configurator. The flag's value defaults to true. See Automatic Application Deployment for more information.

name

Network name of this virtual host, as registered in your Domain Name Service server. One of the Hosts nested within an Engine MUST have a name that matches the defaultHost setting for that Engine. See Host Name Aliases for information on how to assign more than one network name to the same virtual host.

Standard Implementation

The standard implementation of Host is org.apache.catalina.core.StandardHost. It supports the following additional attributes (in addition to the common attributes listed above):

AttributeDescription
deployXML

Set to false if you want to disable parsing the context.xml file embedded inside the application (located at /META-INF/context.xml). Security consious environments should set this to false to prevent applications from interacting with the container's configuration. The administrator will then be responsible for providing an external context configuration file, and put it in $CATALINA_HOME/conf/[enginename]/[hostname]/. The flag's value defaults to true.

errorReportValveClass

Java class name of the error reporting valve which will be used by this Host. The responsability of this valve is to output error reports. Setting this property allows to customize the look of the error pages which will be generated by Tomcat. This class must implement the org.apache.catalina.Valve interface. If none is specified, the value org.apache.catalina.valves.ErrorReportValve will be used by default.

unpackWARs

Set to true if you want web applications that are placed in the appBase directory as web application archive (WAR) files to be unpacked into a corresponding disk directory structure, false to run such web applications directly from a WAR file. See Automatic Application Deployment for more information.

workDir

Pathname to a scratch directory to be used by applications for this Host. Each application will have its own sub directory with temporary read-write use. Configuring a Context workDir will override use of the Host workDir configuration. 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_HOME/work will be provided.

Nested Components

You can nest one or more Context elements inside this Host element, each representing a different web application associated with this virtual host.

You can nest at most one instance of the following utility components by nesting a corresponding element inside your Host element:

  • Realm - Configure a realm that will allow its database of users, and their associated roles, to be shared across all Contexts nested inside this Host (unless overridden by a Realm configuration at a lower level).
Special Features
Logging

A host is associated with the org.apache.catalina.core.ContainerBase.[enginename].[hostname] log category. Note that the brackets are actuall 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:

<Host name="localhost" ...>
  ...
  <Valve className="org.apache.catalina.valves.AccessLogValve"
         prefix="localhost_access_log." suffix=".txt"
         pattern="common"/>
  ...
</Host>

See Access Log Valve for more information on the configuration attributes that are supported.

Automatic Application Deployment

If you are using the standard Host implementation, the following actions take place automatically when Catalina is first started, if the deployOnStartup property is set to true (which is the default value):

  • Any XML file in the $CATALINA_HOME/conf/[engine_name]/[host_name] directory is assumed to contain a Context element (and its associated subelements) for a single web application. The docBase attribute of this <Context> element will typically be the absolute pathname to a web application directory, or the absolute pathname of a web application archive (WAR) file (which will not be expanded).
  • Any web application archive file within the application base (appBase) directory that does not have a corresponding directory of the same name (without the ".war" extension) will be automatically expanded, unless the unpackWARs property is set to false. If you redeploy an updated WAR file, be sure to delete the expanded directory when restarting Tomcat, so that the updated WAR file will be re-expanded (note that the auto deployer, if enabled, will automatically expand the updated WAR file once the previously expanded directory is removed).
  • Any subdirectory within the application base directory that appears to be an unpacked web application (that is, it contains a /WEB-INF/web.xml file) will receive an automatically generated Context element, even if this directory is not mentioned in the conf/server.xml file. This generated Context entry will be configured according to the defaults configured for this Host element. The context path for this deployed Context will be a slash character ("/") followed by the directory name, unless the directory name is ROOT, in which case the context path will be an empty string ("").

In addition to the automatic deployment that occurs at startup time, you can also request that new XML configuration files, WAR files, or subdirectories (containing web applications) that are dropped in to the appBase (or $CATALINA_HOME/conf/[engine_name]/[host_name] in the case of an XML configuration file) directory while Tomcat is running will be automatically deployed, according to the rules described above. The auto deployer will also track web applications for the following changes:

  • An update to the WEB-INF/web.xml file will trigger a reload of the web application
  • An update to a WAR which has been expanded will trigger an undeploy (with a removal of the expanded webapp), followed by a deployment
  • An update to a XML configuration file will trigger an undeploy (without the removal of any expanded directory), followed by a deployment of the associated web application

When using automatic deployment, the docBase defined by an XML Context file should be outside of the appBase directory. If this is not the case difficulties may be experienced deploying the web application or the application may be deployed twice.

Finally, note that if you are defining contexts explicitly, you should probably turn off automatic application deployment. Otherwise, your context will be deployed twice each, and that may cause problems for your app.

Host Name Aliases

In many server environments, Network Administrators have configured more than one network name (in the Domain Name Service (DNS) server), that resolve to the IP address of the same server. Normally, each such network name would be configured as a separate Host element in conf/server.xml, each with its own set of web applications.

However, in some circumstances, it is desireable that two or more network names should resolve to the same virtual host, running the same set of applications. A common use case for this scenario is a corporate web site, where it is desireable that users be able to utilize either www.mycompany.com or company.com to access exactly the same content and applications.

This is accomplished by utilizing one or more Alias elements nested inside your Host element. For example:

<Host name="www.mycompany.com" ...>
  ...
  <Alias>mycompany.com</Alias>
  ...
</Host>

In order for this strategy to be effective, all of the network names involved must be registered in your DNS server to resolve to the same computer that is running this instance of Catalina.

Lifecycle Listeners

If you have implemented a Java object that needs to know when this Host 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 it will be notified about the occurrence of the coresponding lifecycle events. Configuration of such a listener looks like this:

<Host name="localhost" ...>
  ...
  <Listener className="com.mycompany.mypackage.MyListener" ... >
  ...
</Host>

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 a configured list of "accept" and/or "deny" filters, which are defined using the Regular Expression syntax supported by the Jakarta Regexp regular expression library. Requests that come from locations that are not accepted will be rejected with an HTTP "Forbidden" error. Example filter declarations:

<Host name="localhost" ...>
  ...
  <Valve className="org.apache.catalina.valves.RemoteHostValve"
         allow="*.mycompany.com,www.yourcompany.com"/>
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         deny="192.168.1.*"/>
  ...
</Host>

See Remote Address Filter and Remote Host Filter for more information about the configuration options that are supported.

Single Sign On

In many environments, but particularly in portal environments, it is desireable to have a user challenged to authenticate themselves only once over a set of web applications deployed on a particular virtual host. This can be accomplished by nesting an element like this inside the Host element for this virtual host:

<Host name="localhost" ...>
  ...
  <Valve className="org.apache.catalina.authenticator.SingleSignOn"
         debug="0"/>
  ...
</Host>

The Single Sign On facility operates according to the following rules:

  • All web applications configured for this virtual host must share the same Realm. In practice, that means you can nest the Realm element inside this Host element (or the surrounding Engine element), but not inside a Context element for one of the involved web applications.
  • As long as the user accesses only unprotected resources in any of the web applications on this virtual host, they will not be challenged to authenticate themselves.
  • As soon as the user accesses a protected resource in any web application associated with this virtual host, the user will be challenged to authenticate himself or herself, using the login method defined for the web application currently being accessed.
  • Once authenticated, the roles associated with this user will be utilized for access control decisions across all of the associated web applications, without challenging the user to authenticate themselves to each application individually.
  • As soon as the user logs out of one web application (for example, by invalidating the corresponding session if form based login is used), the user's sessions in all web applications will be invalidated. Any subsequent attempt to access a protected resource in any application will require the user to authenticate himself or herself again.
  • The Single Sign On feature utilizes HTTP cookies to transmit a token that associates each request with the saved user identity, so it can only be utilized in client environments that support cookies.
User Web Applications

Many web servers can automatically map a request URI starting with a tilde character ("~") and a username to a directory (commonly named public_html) in that user's home directory on the server. You can accomplish the same thing in Catalina by using a special Listener element like this (on a Unix system that uses the /etc/passwd file to identify valid users):

<Host name="localhost" ...>
  ...
  <Listener className="org.apache.catalina.startup.UserConfig"
            directoryName="public_html"
            userClass="org.apache.catalina.startup.PasswdUserDatabase"/>
  ...
</Host>

On a server where /etc/passwd is not in use, you can request Catalina to consider all directories found in a specified base directory (such as c:\Homes in this example) to be considered "user home" directories for the purposes of this directive:

<Host name="localhost" ...>
  ...
  <Listener className="org.apache.catalina.startup.UserConfig"
            directoryName="public_html"
            homeBase=c:\Homes"
            userClass="org.apache.catalina.startup.HomesUserDatabase"/>
  ...
</Host>

If a user home directory has been set up for a user named craigmcc, then its contents will be visible from a client browser by making a request to a URL like:

http://www.mycompany.com:8080/~craigmcc

Successful use of this feature requires recognition of the following considerations:

  • Each user web application will be deployed with characteristics established by any defaults you have configured for this Host.
  • It is legal to include more than one instance of this Listener element. This would only be useful, however, in circumstances where you wanted to configure more than one "homeBase" directory.
  • The operating system username under which Catalina is executed MUST have read access to each user's web application directory, and all of its contents.

The GlobalNamingResources Component

Printer Friendly Version
print-friendly
version
Introduction

The GlobalNamingResources element defines the global JNDI resources for the Server.

These resources are listed in the server's global JNDI resource context. This context is distinct from the per-web-application JNDI contexts described in the JNDI Resources HOW-TO. The resources defined in this element are not visible in the per-web-application contexts unless you explicitly link them with <ResourceLink> elements.

Attributes
Nested Components
Special Features
Environment Entries

You can configure named values that will be made visible to all web applications as environment entry resources by nesting <Environment> entries inside this element. For example, you can create an environment entry like this:

<GlobalNamingResources ...>
  ...
  <Environment name="maxExemptions" value="10"
         type="java.lang.Integer" override="false"/>
  ...
</GlobalNamingResources>

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:

AttributeDescription
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 one of the legal values for <env-entry-type> in the web application deployment descriptor: java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Short, or java.lang.String.

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.

Resource Definitions

You can declare the characteristics of resources to be returned for JNDI lookups of <resource-ref> and <resource-env-ref> elements in the web application deployment descriptor by defining them in this element and then linking them with <ResourceLink> elements in the <Context> element. You MUST also define any other needed parameters using attributes on 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:

<GlobalNamingResources ...>
  ...
  <Resource name="jdbc/EmployeeDB" auth="Container"
            type="javax.sql.DataSource"
     description="Employees Database for HR Applications"/>
  ...
</GlobalNamingResources>

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 attriutes for a <Resource> element are as follows:

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

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.

type

The fully qualified Java class name expected by the web application when it performs a lookup for this resource.

Resource Links

Use <ResourceLink> elements to link resources from the global context into per-web-application contexts. Here is an example of making a custom factory available to a web applications, based on the example definition in the JNDI Resource HOW-TO:

      
        <Context>
          <ResourceLink 
            name="bean/MyBeanFactory"
            global="bean/MyBeanFactory"
            type="com.mycompany.MyBean"
          />
        </Context>
      
    
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:

AttributeDescription
factory

The class name for the JNDI object factory.

The Loader Component

Printer Friendly Version
print-friendly
version
Introduction

The Loader element represents the web application class loader that will be used to load Java classes and resources for your web application. Such a class loader must follow the requirements of the Servlet Specification, and load classes from the following locations:

  • From the /WEB-INF/classes directory inside your web application.
  • From JAR files in the /WEB-INF/lib directory inside your web application.
  • From resources made available by Catalina to all web applications globally.

A Loader element MAY be nested inside a Context component. If it is not included, a default Loader configuration will be created automatically, which is sufficient for most requirements.

For a more in-depth description of the class loader hierarchy that is implemented by Catalina, see the ClassLoader HowTo.

在下面的描述中使用变量名$CATALINA_HOME来代指Tomcat5所安装的目录地址,这是一个基础目录(base directory),其他的相关路径由它而派生。不过,如果你已经把Tomcat设置成多个体实例(multiple instances),并且设立了一个$CATALINA_BASE目录,那么你就应使用$CATALINA_BASE而不是$CATALINA_HOME作为参照。

Attributes
Common Attributes

Loader的所有实现支持下列属性:

AttributeDescription
className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Loader interface. If not specified, the standard value (defined below) will be used.

delegate

Set to true if you want the class loader to follow the standard Java2 delegation model, and attempt to load classes from parent class loaders before looking inside the web application. Set to false (the default) to have the class loader look inside the web application first, before asking parent class loaders to find requested classes or resources.

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. You can use the Manager web application, however, to trigger reloads of deployed applications on demand.

NOTE - The value for this property will be inherited from the reloadable attribute you set on the surrounding Context component, and any value you explicitly set here will be replaced.

Standard Implementation

The standard implementation of Loader is org.apache.catalina.loader.WebappLoader. It supports the following additional attributes (in addition to the common attributes listed above):

AttributeDescription
backgroundProcesssorDelay

The number of seconds between checks for modified classes and resources, if reloadable has been set to true.

See the general documentation for this parameter at Host Container.

loaderClass

Java class name of the java.lang.ClassLoader implementation class to use. If not specified, the default value is org.apache.catalina.loader.WebappClassLoader.

useSystemClassLoaderAsParent

If no parent classloader is specified, should the system classloader be used? The default of true mantains backwards compatibility with previous releases however most users will want to set this to false to obtain the parent classloader from the associated container.

This attribute will not be present in Tomcat 6 where the Loader API has changed and the parent class loader is always obtained from the associated container.

Nested Components

No components may be nested inside a Loader element.

Special Features
Logging

A loader is associated with the log category based on its classname.

The Manager Component

Printer Friendly Version
print-friendly
version
Introduction

The Manager element represents the session manager that will be used to create and maintain HTTP sessions as requested by the associated web application.

A Manager element MAY be nested inside a Context component. If it is not included, a default Manager configuration will be created automatically, which is sufficient for most requirements.

Attributes
Common Attributes

Manager的所有实现支持下列属性:

AttributeDescription
className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Manager interface. If not specified, the standard value (defined below) will be used.

distributable

Set to true to ask the session manager to enforce the restrictions described in the Servlet Specification on distributable applications (primarily, this would mean that all session attributes must implement java.io.Serializable). Set to false (the default) to not enforce these restrictions.

NOTE - The value for this property is inherited automatically based on the presence or absence of the <distributable> element in the web application deployment descriptor (/WEB-INF/web.xml).

Standard Implementation

Tomcat provides two standard implementations of Manager for use - the default one stores active sessions, while the optional one stores active sessions that have been swapped out (in addition to saving sessions across a restart of Tomcat) in a storage location that is selected via the use of an appropriate Store nested element.

Standard Manager Implementation

The standard implementation of Manager is org.apache.catalina.session.StandardManager. It supports the following additional attributes (in addition to the common attributes listed above):

AttributeDescription
algorithm

Name of the Message Digest algorithm used to calculate session identifiers produced by this Manager. This value must be supported by the java.security.MessageDigest class. If not specified, the default value is "MD5".

entropy

A String value that is utilized when seeding the random number generator used to create session identifiers for this Manager. If not specified, a semi-useful value is calculated, but a long String value should be specified in security-conscious environments.

maxActiveSessions

The maximum number of active sessions that will be created by this Manager, or -1 (the default) for no limit.

maxInactiveInterval

The initial maximum time interval, in seconds, between client requests before a session is invalidated. A negative value will result in sessions never timing out. If the attribute is not provided, a default of 60 seconds is used.

This attribute provides the initial value whenever a new session is created, but the interval may be dynamically varied by a servlet via the setMaxInactiveInterval method of the HttpSession object.

pathname

Absolute or relative (to the work directory for this Context) pathname of the file in which session state will be preserved across application restarts, if possible. The default is "SESSIONS.ser". See Restart Persistence for more information. Restart persistence may be disabled by setting this attribute to an empty string.

processExpiresFrequency

Frequency of the session expiration, and related manager operations. Manager operations will be done once for the specified amount of backgrondProcess calls (ie, the lower the amount, the more often the checks will occur). The minimum value is 1, and the default value is 6.

randomClass

Java class name of the java.util.Random implementation class to use. If not specified, the default value is java.security.SecureRandom.

sessionIdLength

The length of session ids created by this Manager, excluding any JVM route information used for load balancing. The default is 16.

Persistent Manager Implementation

WARNING - Use of this Manager implementation has not been thoroughly tested, and should be considered experimental!

The persistent implementation of Manager is org.apache.catalina.session.PersistentManager. In addition to the usual operations of creating and deleting sessions, a PersistentManager has the capability to swap active (but idle) sessions out to a persistent storage mechanism, as well as to save all sessions across a normal restart of Tomcat. The actual persistent storage mechanism used is selected by your choice of a Store element nested inside the Manager element - this is required for use of PersistentManager.

This implementation of Manager supports the following attributes in addition to the Common Attributes described earlier.

AttributeDescription
algorithm

Name of the Message Digest algorithm used to calculate session identifiers produced by this Manager. This value must be supported by the java.security.MessageDigest class. If not specified, the default value is "MD5".

className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Manager interface. You must specify org.apache.catalina.session.PersistentManager to use this manager implementation.

entropy

A String value that is utilized when seeding the random number generator used to create session identifiers for this Manager. If not specified, a semi-useful value is calculated, but a long String value should be specified in security-conscious environments.

maxActiveSessions

The maximum number of active sessions that will be created by this Manager, or -1 (the default) for no limit.

maxIdleBackup

The time interval (in seconds) since the last access to a session before it is eligible for being persisted to the session store, or -1 to disable this feature. By default, this feature is disabled.

maxIdleSwap

The time interval (in seconds) since the last access to a session before it should be persisted to the session store, and passivated out of the server's memory, or -1 to disable this feature. If this feature is enabled, the time interval specified here should be equal to or longer than the value specified for maxIdleBackup. By default, this feature is disabled.

minIdleSwap

The time interval (in seconds) since the last access to a session before it will be eligible to be persisted to the session store, and passivated out of the server's memory, or -1 for this swapping to be available at any time. If specified, this value should be less than that specified by maxIdleSwap. By default, this value is set to -1.

maxInactiveInterval

The initial maximum time interval, in seconds, between client requests before a session is invalidated. A negative value will result in sessions never timing out. If the attribute is not provided, a default of 60 seconds is used.

This attribute provides the initial value whenever a new session is created, but the interval may be dynamically varied by a servlet via the setMaxInactiveIntervalmethod of the HttpSession object.

randomClass

Java class name of the java.util.Random implementation class to use. If not specified, the default value is java.security.SecureRandom.

saveOnRestart

Should all sessions be persisted and reloaded when Tomcat is shut down and restarted (or when this application is reloaded)? By default, this attribute is set to true.

sessionIdLength

The length of session ids created by this Manager, excluding any JVM route information used for load balancing. The default is 16.

In order to successfully use a PersistentManager, you must nest inside it a <Store> element, as described below.

Nested Components

Standard Manager Implementation

If you are using the Standard Manager Implementation as described above, no elements may be nested inside your <Manager> element.

Persistent Manager Implementation

If you are using the Persistent Manager Implementation as described above, you MUST nest a <Store> element inside, which defines the characteristics of the persistent data storage. Two implementations of the <Store> element are currently available, with different characteristics, as described belowl

File Based Store

The File Based Store implementation saves swapped out sessions in individual files (named based on the session identifier) in a configurable directory. Therefore, you are likely to encounter scalability problems as the number of active sessions increases, and this should primarily be considered a means to easily experiment.

To configure this, add a <Store> nested inside your <Manager> element with the following attributes:

AttributeDescription
checkInterval

The interval (in seconds) between checks for expired sessions among those sessions that are currently swapped out. By default, this interval is set to 60 seconds (one minute).

className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Store interface. You must specify org.apache.catalina.session.FileStore to use this implementation.

directory

Absolute or relative (to the temporary work directory for this web application) pathname of the directory into which individual session files are written. If not specified, the temporary work directory assigned by the container is utilized.

JDBC Based Store

The JDBC Based Store implementation saves swapped out sessions in individual rows of a preconfigured table in a database that is accessed via a JDBC driver. With large numbers of swapped out sessions, this implementation will exhibit improved performance over the File Based Store described above.

To configure this, add a <Store> nested inside your <Manager> element with the following attributes:

AttributeDescription
checkInterval

The interval (in seconds) between checks for expired sessions among those sessions that are currently swapped out. By default, this interval is set to 60 seconds (one minute).

className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Store interface. You must specify org.apache.catalina.session.JDBCStore to use this implementation.

connectionURL

The connection URL that will be handed to the configured JDBC driver to establish a connection to the database containing our session table.

driverName

Java class name of the JDBC driver to be used.

sessionAppCol

Name of the database column, contained in the specified session table, that contains the Engine, Host, and Web Application Context name in the format /Engine/Host/Context.

sessionDataCol

Name of the database column, contained in the specified session table, that contains the serialized form of all session attributes for a swapped out session. The column type must accept a binary object (typically called a BLOB).

sessionIdCol

Name of the database column, contained in the specified session table, that contains the session identifier of the swapped out session. The column type must accept character string data of at least as many characters as are contained in session identifiers created by Tomcat (typically 32).

sessionLastAccessedCol

Name of the database column, contained in the specified session table, that contains the lastAccessedTime property of this session. The column type must accept a Java long (64 bits).

sessionMaxInactiveCol

Name of the database column, contained in the specified session table, that contains the maxInactiveInterval property of this session. The column type must accept a Java integer (32 bits).

sessionTable

Name of the database table to be used for storing swapped out sessions. This table must contain (at least) the database columns that are configured by the other attributes of this element.

sessionValidCol

Name of the database column, contained in the specified session table, that contains a flag indicating whether this swapped out session is still valid or not. The column type must accept a single character.

Before attempting to use the JDBC Based Store for the first time, you must create the table that will be used to store swapped out sessions. Detailed SQL commands vary depending on the database you are using, but a script like this will generally be required:

create table tomcat_sessions (
  session_id     varchar(100) not null primary key,
  valid_session  char(1) not null,
  max_inactive   int not null,
  last_access    bigint not null,
  app_name       varchar(255),
  session_data   mediumblob,
  KEY kapp_name(app_name)
);

In order for the JDBC Based Store to successfully connect to your database, the JDBC driver you configure must be visible to Tomcat's internal class loader. Generally, that means you must place the JAR file containing this driver into the $CATALINA_HOME/server/lib directory (if your applications do not also need it) or into the $CATALINA_HOME/common/lib directory (if you wish to share this driver with your web applications.

Special Features
Restart Persistence

Whenver Catalina is shut down normally and restarted, or when an application reload is triggered, the standard Manager implementation will attempt to serialize all currently active sessions to a disk file located via the pathname attribute. All such saved sessions will then be deserialized and activated (assuming they have not expired in the mean time) when the application reload is completed.

In order to successfully restore the state of session attributes, all such attributes MUST implement the java.io.Serializable interface. You MAY cause the Manager to enforce this restriction by including the <distributable> element in your web application deployment descriptor (/WEB-INF/web.xml).

The Realm Component

Printer Friendly Version
print-friendly
version
Introduction

A Realm element represents a "database" of usernames, passwords, and roles (similar to Unix groups) assigned to those users. Different implementations of Realm allow Catalina to be integrated into environments where such authentication information is already being created and maintained, and then utilize that information to implement Container Managed Security as described in the Servlet Specification.

You may nest a Realm inside any Catalina container Engine, Host, or Context). In addition, Realms associated with an Engine or a Host are automatically inherited by lower-level containers, unless explicitly overridden.

For more in-depth information about container managed security in web applications, as well as more information on configuring and using the standard realm component implementations, please see the Container-Managed Security Guide.

在下面的描述中使用变量名$CATALINA_HOME来代指Tomcat5所安装的目录地址,这是一个基础目录(base directory),其他的相关路径由它而派生。不过,如果你已经把Tomcat设置成多个体实例(multiple instances),并且设立了一个$CATALINA_BASE目录,那么你就应使用$CATALINA_BASE而不是$CATALINA_HOME作为参照。

Attributes
Common Attributes

Realm的所有实现支持下列属性:

AttributeDescription
className

Java class name of the implementation to use. This class must implement the org.apache.catalina.Realm interface.

digest

用来以非明文形式贮存密码的“文摘”算法,那些被java.security.MessageDigest类里所接受的算法名称的值才是有效的值。更多信息请参见Digested 密码。如果没指定,密码以明文形式贮存。

digestEncoding

The charset for encoding digests. If not specified, the platform default will be used.

Standard Implementation

Unlike most Catalina components, there are several standard Realm implementations available. As a result, the className attribute MUST be used to select the implementation you wish to use.

JDBC Database Realm (org.apache.catalina.realm.JDBCRealm)

The JDBC Database Realm connects Catalina to a relational database, accessed through an appropriate JDBC driver, to perform lookups of usernames, passwords, and their associated roles. Because the lookup is done each time that it is required, changes to the database will be immediately reflected in the information used to authenticate new logins.

A rich set of additional attributes lets you configure the required connection to the underlying database, as well as the table and column names used to retrieve the required information:

AttributeDescription
connectionName

The database username to use when establishing the JDBC connection.

connectionPassword

The database password to use when establishing the JDBC connection.

connectionURL

The connection URL to be passed to the JDBC driver when establishing a database connection.

driverName

Fully qualified Java class name of the JDBC driver to be used to connect to the authentication database. Consult the documentation for your JDBC driver for the appropriate value.

roleNameCol

Name of the column, in the "user roles" table, which contains a role name assigned to the corresponding user.

userCredCol

Name of the column, in the "users" table, which contains the user's credentials (i.e. password). If a value for the digest attribute is specified, this component will assume that the passwords have been encoded with the specified algorithm. Otherwise, they will be assumed to be in clear text.

userNameCol

Name of the column, in the "users" and "user roles" table, that contains the user's username.

userRoleTable

表名,它的每一行包含指派给某一特定用户名称的一个角色。这个表格必须至少包括那些由userNameColroleNameCol属性定名的列。

userTable

表名,它的每一行包含一个可被Tomcat识别的用户名称。这个表格必须至少包括那些由userNameCol userCredCol 属性定名的列。

See the Container-Managed Security Guide for more information on setting up container managed security using the JDBC Database Realm component.

DataSource Database Realm (org.apache.catalina.realm.DataSourceRealm)

The DataSource Database Realm connects Catalina to a relational database, accessed through a JNDI named JDBC DataSource to perform lookups of usernames, passwords, and their associated roles. Because the lookup is done each time that it is required, changes to the database will be immediately reflected in the information used to authenticate new logins.

The JDBC Realm uses a single db connection. This requires that realm based authentication be synchronized, i.e. only one authentication can be done at a time. This could be a bottleneck for applications with high volumes of realm based authentications.

The DataSource Database Realm supports simultaneous realm based authentications and allows the underlying JDBC DataSource to handle optimizations like database connection pooling.

A rich set of additional attributes lets you configure the name of the JNDI JDBC DataSource, as well as the table and column names used to retrieve the required information:

AttributeDescription
dataSourceName

你的数据库需要的一个叫做JDBC DataSource的JNDI。如果这个DataSource对于上下文来说是局部的话,这个名字与java:/comp/env相关,否则这个名字应该和定义全球性DataSource的名字相映射。

localDataSource

当这个realm被套嵌在一个Context元素里边,就允许这个realm使用为这个Context定义的DataSource,而不是全球性DataSource 。如果没有指定,默认值是false:使用全球性DataSource 。

roleNameCol

Name of the column, in the "user roles" table, which contains a role name assigned to the corresponding user.

userCredCol

Name of the column, in the "users" table, which contains the user's credentials (i.e. password). If a value for the digest attribute is specified, this component will assume that the passwords have been encoded with the specified algorithm. Otherwise, they will be assumed to be in clear text.

userNameCol

Name of the column, in the "users" and "user roles" table, that contains the user's username.

userRoleTable

表名,它的每一行包含指派给某一特定用户名称的一个角色。这个表格必须至少包括那些由userNameColroleNameCol属性定名的列。

userTable

表名,它的每一行包含一个可被Tomcat识别的用户名称。这个表格必须至少包括那些由userNameCol userCredCol 属性定名的列。

See the DataSource Realm HOW-TO for more information on setting up container managed security using the DataSource Database Realm component.

JNDI Directory Realm (org.apache.catalina.realm.JNDIRealm)

The JNDI Directory Realm connects Catalina to an LDAP Directory, accessed through an appropriate JNDI driver, that stores usernames, passwords, and their associated roles. Changes to the directory are immediately reflected in the information used to authenticate new logins.

The directory realm supports a variety of approaches to using LDAP for authentication:

  • The realm can either use a pattern to determine the distinguished name (DN) of the user's directory entry, or search the directory to locate that entry.
  • The realm can authenticate the user either by binding to the directory with the DN of the user's entry and the password presented by the user, or by retrieving the password from the user's entry and performing a comparison locally.
  • Roles may be represented in the directory as explicit entries found by a directory search (e.g. group entries of which the user is a member), as the values of an attribute in the user's entry, or both.

A rich set of additional attributes lets you configure the required behaviour as well as the connection to the underlying directory and the element and attribute names used to retrieve information from the directory:

AttributeDescription
alternateURL

If a socket connection can not be made to the provider at the connectionURL an attempt will be made to use the alternateURL.

authentication

A string specifying the type of authentication to use. "none", "simple", "strong" or a provider specific definition can be used. If no value is given the providers default is used.

connectionName

建立与LDAP search操作目录的连接时使用的目录用户名。如果没有指定,就使用无名的连接,除非你指定了userPassword属性,通常这就足够了。

connectionPassword

建立与LDAP search操作目录的连接时使用的目录密码。如果没有指定,就使用无名的连接,除非你指定了userPassword属性,通常这就足够了。

connectionURL

在建立与目录的连接时传递给JNDI驱动的连接URL。

contextFactory

Fully qualified Java class name of the factory class used to acquire our JNDI InitialContext. By default, assumes that the standard JNDI LDAP provider will be utilized (com.sun.jndi.ldap.LdapCtxFactory).

derefAliases

A string specifying how aliases are to be dereferenced during search operations. The allowed values are "always", "never", "finding" and "searching". If not specified, "always" is used.

protocol

A string specifying the security protocol to use. If not given the providers default is used.

roleBase

The base directory entry for performing role searches. If not specified the top-level element in the directory context will be used.

roleName

属性的名字,它包含被角色搜寻查找到的目录输入里的角色名字。另外,你可以在包含有额外的角色名字的用户输入里使用userRoleName property来指定一个attribute的名字。如果roleName没有被指定,角色搜寻就不会发生,只能从用户的输入里得到角色。

roleSearch

用来执行角色搜寻的LDAP过滤器表达式,后面紧跟着由java.text.MessageFormat类支持的语法。使用{0}来代替用户的独特名字(distinguished name (DN)),并且/或者用{1}来代替用户名(username)。如果没有被指定,角色搜寻就不发生,角色就由userRoleName property指定的用户输入里的属性来决定。

roleSubtree

在查找与用户相关的角色输入时,如果你想搜寻roleBase property指定的元素的整个subtree,设值为true。默认值为false,它仅仅使得顶层元素被搜寻。

userBase

通过使用userSearch表达式来执行的用户搜寻基本元素。如果没有指定,目录context里的顶层元素将被使用。如果你在使用userPattern表达式,就不用使用它。

userPassword

Name of the attribute in the user's entry containing the user's password. If you specify this value, JNDIRealm will bind to the directory using the values specified by connectionName and connectionPassword properties, and retrieve the corresponding attribute for comparison to the value specified by the user being authenticated. If the digest attribute is set, the specified digest algorithm is applied to the password offered by the user before comparing it with the value retrieved from the directory. If you do not specify this value, JNDIRealm will attempt a simple bind to the directory using the DN of the user's entry and the password presented by the user, with a successful bind being interpreted as an authenticated user.

userPattern

Pattern for the distinguished name (DN) of the user's directory entry, following the syntax supported by the java.text.MessageFormat class. with {0} marking where the actual username should be inserted. You can use this property instead of userSearch, userSubtree and userBase when the distinguished name contains the username and is otherwise the same for all users.

userRoleName

用户目录输入中的一个属性名,该属性包含了零个或多个指定给用户的角色名称的值。另外,可以使用roleName属性来指定属性名,这个属性可以通过搜索目录在单独的角色输入里得到。如果不指定userRoleName,用户的所有角色通过角色搜索得到。

userSearch

搜索用户目录输入时,使用的LDAP过滤器表达式,{0}代表实际用户名应该在什么地方被插入。使用这个userSearch属性(和userBase以及userSubtree属性一起),而不是userPattern,来搜索目录寻找用户的输入。

userSubtree

如果想要搜索由userBase属性指定的元素的整个subtree,设为true,缺省值为false,即仅仅是顶级元素被搜索。如果使用userPattern表达式,则不使用这个属性。

See the Container-Managed Security Guide for more information on setting up container managed security using the JNDI Directory Realm component.

Memory Based Realm (org.apache.catalina.realm.MemoryRealm)

The Memory Based Realm is a simple Realm implementation that reads user information from an XML format, and represents it as a collection of Java objects in memory. This implementation is intended solely to get up and running with container managed security - it is NOT intended for production use. As such, there are no mechanisms for updating the in-memory collection of users when the content of the underlying data file is changed.

The Memory Based Realm implementation supports the following additional attributes:

AttributeDescription
pathname

Absolute or relative (to $CATALINA_HOME) pathname to the XML file containing our user information. See below for details on the XML element format required. If no pathname is specified, the default value is conf/tomcat-users.xml.

The XML document referenced by the pathname attribute must conform to the following requirements:

  • The root (outer) element must be <tomcat-users>.
  • Each authorized user must be represented by a single XML element <user>, nested inside the root element.
  • Each <user> element must have the following attributes:
    • name - Username of this user (must be unique within this file).
    • password - Password of this user (in clear text).
    • roles - Comma-delimited list of the role names assigned to this user.

See the Container-Managed Security Guide for more information on setting up container managed security using the Memory Based Realm component.

User Database Realm (org.apache.catalina.realm.UserDatabaseRealm)

The User Database Realm is Realm implementation that is based on an implementation of the UserDatabase interface that is made available through the global JNDI resources configured for this Tomcat instance.

The User Database Realm implementation supports the following additional attributes:

AttributeDescription
resourceName

The global JNDI name of the UserDatabase resource used by this Realm.

See the Container-Managed Security Guide for more information on setting up container managed security using the UserDatabase Realm component.

JAAS Realm (org.apache.catalina.realm.JAASRealm)

The JAAS Realm implementation supports the following additional attributes:

AttributeDescription
appName

你在login配置文件中( JAAS LoginConfig)配置的应用程序名。

userClassNames

由逗号分隔开的,你为你的用户Principals制作的类名列单。

roleClassNames

由逗号分隔开的,你为你的角色Principals制作的类名列单。

useContextClassLoader

Instructs JAASRealm to use the context class loader for loading the user-specified LoginModule class and associated Principal classes. The default value is true, which is backwards-compatible with the way Tomcat 4 works. To load classes using the container's classloader, specify false.

See the Container-Managed Security Guide for more information on setting up container managed security using the JASS Realm component.

Nested Components

No components may be nested inside a Realm element.

Special Features

See Single Sign On for information about configuring Single Sign On support for a virtual host.

The Resources Component

Printer Friendly Version
print-friendly
version
Introduction

The Resources element represents the web application static resources, from which classes will be loaded, HTML, JSP and the other static files will be served. This allows the webapp to reside on various mediums other than the filesystem, like compressed in a WAR file, in a JDBC database, or in a more advanced versioning repository.

A unified caching engine is provided for all accesses to the webapp resources made by the servlet container and web applications which use the container provided mechanisms to access such resources, such as class laoder access, access through the ServletContext interface, or native access through the DirectoryContext interface.

Note: Running a webapp with non-filesystem based Resources implementations is only possible when the webapp does not rely on direct filesystem access to its own resources, and uses the methods in the ServletContext interface to access them.

A Resources element MAY be nested inside a Context component. If it is not included, a default filesystem based Resources will be created automatically, which is sufficient for most requirements.

Attributes
Common Attributes

Resources的所有实现支持下列属性:

AttributeDescription
className

Java class name of the implementation to use. This class must implement the javax.naming.directory.DirContext interface. It is recommended for optimal functionality and performance, but not mandatory, that the class extend org.apache.naming.resources.BaseDirContext, as well as use the special object types provided in the org.apache.naming.resources for returned objects. If not specified, the standard value (defined below) will be used.

Standard Implementation

The standard implementation of Resources is org.apache.naming.resources.FileDirContext, and is configured by its parent Context element.

Nested Components

No components may be nested inside a Resources element.

Special Features

No special features are associated with a Resources element.

The Valve Component

Printer Friendly Version
print-friendly
version
Introduction

A Valve element represents a component that will be inserted into the request processing pipeline for the associated Catalina container (Engine, Host, or Context). Individual Valves have distinct processing capabilities, and are described individually below.

在下面的描述中使用变量名$CATALINA_HOME来代指Tomcat5所安装的目录地址,这是一个基础目录(base directory),其他的相关路径由它而派生。不过,如果你已经把Tomcat设置成多个体实例(multiple instances),并且设立了一个$CATALINA_BASE目录,那么你就应使用$CATALINA_BASE而不是$CATALINA_HOME作为参照。

Access Log Valve
Introduction

The Access Log Valve creates log files in the same format as those created by standard web servers. These logs can later be analyzed by standard log analysis tools to track page hit counts, user session activity, and so on. The files produces by this Valve are rolled over nightly at midnight. This Valve may be associated with any Catalina container (Context, Host, or Engine), and will record ALL requests processed by that container.

Attributes

Access Log Valve 支持下列配置属性:

AttributeDescription
className

Java class name of the implementation to use. This MUST be set to org.apache.catalina.valves.AccessLogValve to use the default access log valve. To use a more optimized access log valve designed for production use, you MUST set this attribute to org.apache.catalina.valves.FastCommonAccessLogValve. In this case, only the common and combined patterns are supported.

directory

Absolute or relative pathname of a directory in which log files created by this valve will be placed. If a relative path is specified, it is interpreted as relative to $CATALINA_HOME. If no directory attribute is specified, the default value is "logs" (relative to $CATALINA_HOME).

pattern

A formatting layout identifying the various information fields from the request and response to be logged, or the word common or combined to select a standard format. See below for more information on configuring this attribute. Note that the optimized access does only support common and combined as the value for this attribute.

prefix

The prefix added to the start of each log file's name. If not specified, the default value is "access_log.". To specify no prefix, use a zero-length string.

resolveHosts

Set to true to convert the IP address of the remote host into the corresponding host name via a DNS lookup. Set to false to skip this lookup, and report the remote IP address instead.

suffix

The suffix added to the end of each log file's name. If not specified, the default value is "". To specify no suffix, use a zero-length string.

rotatable

Deafult true. Flag to determine if log rotation should occur. If set to false, then this file is never rotated and fileDateFormat is ignored. Use with caution!

condition

Turns on conditional logging. If set, requests will be logged only if ServletRequest.getAttribute() is null. For example, if this value is set to junk, then a particular request will only be logged if ServletRequest.getAttribute("junk") == null. The use of Filters is an easy way to set/unset the attribute in the ServletRequest on many different requests.

fileDateFormat

Allows a customized date format in the access log file name. The date format also decides how often the file is rotated. If you wish to rotate every hour, then set this value to: yyyy-MM-dd.HH

Values for the pattern attribute are made up of literal text strings, combined with pattern identifiers prefixed by the "%" character to cause replacement by the corresponding variable value from the current request and response. The following pattern codes are supported:

  • %a - Remote IP address
  • %A - Local IP address
  • %b - Bytes sent, excluding HTTP headers, or '-' if zero
  • %B - Bytes sent, excluding HTTP headers
  • %h - Remote host name (or IP address if resolveHosts is false)
  • %H - Request protocol
  • %l - Remote logical username from identd (always returns '-')
  • %m - Request method (GET, POST, etc.)
  • %p - Local port on which this request was received
  • %q - Query string (prepended with a '?' if it exists)
  • %r - First line of the request (method and request URI)
  • %s - HTTP status code of the response
  • %S - User session ID
  • %t - Date and time, in Common Log Format
  • %u - Remote user that was authenticated (if any), else '-'
  • %U - Requested URL path
  • %v - Local server name
  • %D - Time taken to process the request, in millis
  • %T - Time taken to process the request, in seconds

There is also support to write information from the cookie, incoming header, the Session or something else in the ServletRequest. It is modeled after the apache syntax:

  • %{xxx}i for incoming headers
  • %{xxx}c for a specific cookie
  • %{xxx}r xxx is an attribute in the ServletRequest
  • %{xxx}s xxx is an attribute in the HttpSession

The shorthand pattern name common (which is also the default) corresponds to %h %l %u %t "%r" %s %b".

The shorthand pattern name combined appends the values of the Referer and User-Agent headers, each in double quotes, to the common pattern described in the previous paragraph.

Remote Address Filter
Introduction

The Remote Address Filter allows you to compare the IP address of the client that submitted this request against one or more regular expressions, and either allow the request to continue or refuse to process the request from this client. A Remote Address Filter can be associated with any Catalina container (Engine, Host, or Context), and must accept any request presented to this container for processing before it will be passed on.

The syntax for regular expressions is different than that for 'standard' wildcard matching. Tomcat uses the Jakarta Regexp library. Please consult the Regexp documentation for details of the expressions supported.

Attributes

Remote Address Filter 支持下列配置属性:

AttributeDescription
className

Java class name of the implementation to use. This MUST be set to org.apache.catalina.valves.RemoteAddrValve.

allow

A comma-separated list of regular expression patterns that the remote client's IP address is compared to. If this attribute is specified, the remote address MUST match for this request to be accepted. If this attribute is not specified, all requests will be accepted UNLESS the remote address matches a deny pattern.

deny

A comma-separated list of regular expression patterns that the remote client's IP address is compared to. If this attribute is specified, the remote address MUST NOT match for this request to be accepted. If this attribute is not specified, request acceptance is governed solely by the accept attribute.

Remote Host Filter
Introduction

The Remote Host Filter allows you to compare the hostname of the client that submitted this request against one or more regular expressions, and either allow the request to continue or refuse to process the request from this client. A Remote Host Filter can be associated with any Catalina container (Engine, Host, or Context), and must accept any request presented to this container for processing before it will be passed on.

The syntax for regular expressions is different than that for 'standard' wildcard matching. Tomcat uses the Jakarta Regexp library. Please consult the Regexp documentation for details of the expressions supported.

Attributes

Remote Host Filter 支持下列配置属性:

AttributeDescription
className

Java class name of the implementation to use. This MUST be set to org.apache.catalina.valves.RemoteHostValve.

allow

A comma-separated list of regular expression patterns that the remote client's hostname is compared to. If this attribute is specified, the remote hostname MUST match for this request to be accepted. If this attribute is not specified, all requests will be accepted UNLESS the remote hostname matches a deny pattern.

deny

A comma-separated list of regular expression patterns that the remote client's hostname is compared to. If this attribute is specified, the remote hostname MUST NOT match for this request to be accepted. If this attribute is not specified, request acceptance is governed solely by the accept attribute.

Request Dumper Valve
Introduction

The Request Dumper Valve is a useful tool in debugging interactions with a client application (or browser) that is sending HTTP requests to your Tomcat-based server. When configured, it causes details about each request processed by its associated Engine, Host, or Context to be logged according to the logging configuration for that container.

WARNING: Using this valve has side-effects. The output from this valve includes any parameters included with the request. The parameters will be decoded using the default platform encoding. Any subsequent calls to request.setCharacterEncoding() within the web application will have no effect.

Attributes

Request Dumper Valve 支持下列配置属性:

AttributeDescription
className

Java class name of the implementation to use. This MUST be set to org.apache.catalina.valves.RequestDumperValve.

Single Sign On Valve
Introduction

The Single Sign On Vale is utilized when you wish to give users the ability to sign on to any one of the web applications associated with your virtual host, and then have their identity recognized by all other web applications on the same virtual host.

See the Single Sign On special feature on the Host element for more information.

Attributes

Single Sign On Valve 支持下列配置属性:

AttributeDescription
className

Java class name of the implementation to use. This MUST be set to org.apache.catalina.authenticator.SingleSignOn.

requireReauthentication

Default false. Flag to determine whether each request needs to be reauthenticated to the security Realm. If "true", this Valve uses cached security credentials (username and password) to reauthenticate to the Realm each request associated with an SSO session. If "false", the Valve can itself authenticate requests based on the presence of a valid SSO cookie, without rechecking with the Realm.

Form Authenticator Valve
Introduction

The Form Authenticator Valve is automatically added to any Context that is configured to use FORM authentication.

If any non-default settings are required, the valve may be configured within Context element with the required values.

Attributes

The Form Authenticator Valve supports the following configuration attributes:

AttributeDescription
className

Java class name of the implementation to use. This MUST be set to org.apache.catalina.authenticator.FormAuthenticator.

characterEncoding

Character encoding to use to read the username and password parameters from the request. If not set, the encoding of the request body will be used.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值