Apache Tomcat 5.5 Servlet/JSP 容器 - Apache可移植运行库 与 Tomcat

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

         Jaxmao Logo

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Apache可移植运行库 与 Tomcat

 Printer Friendly Version
print-friendly
version
简介

Tomcat can use the Apache可移植运行库 to provide superior scalability, 性能, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).

These features allows making Tomcat a general purpose webserver, will enable much better integration with other native web technologies, and overall make Java much more viable as a full fledged webserver platform rather than simply a backend focused technology.

安装

安装好以下三个主要的本地组件方可支持 APR :

  • APR库
  • 供Tomcat使用APR的JNI包装器 (libtcnative)
  • OpenSSL库

Windows

Windows 二进制 are provided for tcnative-1, which is a statically compiled .dll which includes OpenSSL and APR. It can be downloaded from here as 32bit or AMD x86-64 binaries. In security conscious production environments, it is recommended to use separate shared dlls for OpenSSL, APR, and libtcnative-1, and update them as needed according to security bulletins. Windows OpenSSL binaries are linked from the Official OpenSSL website (see related/binaries).

Linux

Most Linux distributions will ship packages for APR and OpenSSL. The JNI wrapper (libtcnative) will then have to be compiled. It depends on APR, OpenSSL, and the Java headers.

Requirements:

  • APR 1.2+ development headers (libapr1-dev package)
  • OpenSSL 0.9.7+ development headers (libssl-dev package)
  • JNI headers from Java compatible JDK 1.4+
  • GNU development environment (gcc, make)

The wrapper library sources are located in the Tomcat binary bundle, in the bin/tomcat-native.tar.gz archive. Once the build environment is installed and the source archive is extracted, the wrapper library can be compiled using (from the folder containing the configure script):

./configure && make && make install

APR 组件

一旦这些组件正确的安装并且可供java调用 (如果加载失败, 库文件路径将被显示在控制台), Tomcat 连接器将自动使用 APR 功能. APR连接器的配置与普通连接器的配置基本相同， 但是提供了一些扩展的属性供APR组件使用。 注意:默认值已经适用于大多数的应用场景， 额外的调整不是必须的。

当APR可用之后, 以下特性将在Tomcat中可用:

  • Secure session ID generation by default on all platforms (platforms other than Linux required random number generation using a configured entropy)
  • Tomcat进程的内存占用率和CPU占用率将被 status servlet 显示。

APR连接器配置
HTTP

当APR可用之后, HTTP 连接器 will use sendfile for hadling large static files (all such files will be sent ansychronously using high performance kernel level calls), and will use a socket poller for keepalive, increasing scalability of the server.

The following attributes are supported in the HTTP APR connector in addition to the ones supported in the regular HTTP connector:

Attribute Description
firstReadTimeout

The first read of a request will be made using the specified timeout. If no data is available after the specified time, the socket will be placed in the poller. The value of this attribute is in ms. Setting this value to 0 or -1 will increase scalability by always using a poller to handle keepalive, but will have a minor impact on latency (see the related pollTime attribute). The difference is that with 0, the first read of a request will be made using a short timeout, while with -1, the first read will be made using the regular socket timeout that is configured on the connector. Setting this to -2 will cause the connector to not use the poller for keepalive in most situations, emulating the behavior of the java.io HTTP connector. The default value is -1. Note: on Windows, the actual value of firstReadTimeout will be 500 + the specified value, if the specified value is strictly positive.

pollTime

Duration of a poll call. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (5ms).

pollerSize

Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keepalive connections.

useSendfile

Use kernel level sendfile for certain static files. The default value is true.

sendfileSize

Amount of sockets that the poller responsible for sending static files asynchronously can hold at a given time. Extra connections will be closed right away without any data being sent (resulting in a zero length file on the client side). Note that in most cases, sendfile is a call that will return right away (being taken care of "synchonously" by the kernel), and the sendfile poller will not be used, so the amount of static files which can be sent concurrently is much larger than the specified amount. The default value is 1024.

HTTPS

When APR is enabled, the HTTPS connector will use a socket poller for keepalive, increasing scalability of the server. It also uses OpenSSL, which may be more optimized than JSSE depending on the processor being used, and can be complemented with many commercial accelerator components. Unlike the HTTP connector, the HTTPS connector cannot use sendfile to optimize static file processing.

The HTTPS APR connector has the same basic attributes than the HTTP APR connector, but adds OpenSSL specific ones. For the full details on using OpenSSL, please refer to OpenSSL documentations and the many books available for it (见 OpenSSL官方站点). The SSL specific attributes for the connector are:

Attribute Description
SSLEngine

将使用的 SSL引擎名字. off: 不使用 SSL, on: 使用 SSL 但没有指定的引擎. 默认值是 off.

SSLProtocol

Protocol which may be used for communicating with clients. 默认是 "all", 支持的 其它可用值有 "SSLv2", "SSLv3", "TLSv1", and "SSLv2+SSLv3".

SSLCipherSuite

Ciphers which may be used for communicating with clients. The default is "ALL", with other acceptable values being a list of ciphers, with ":" used as the delimiter (see OpenSSL documentation for the list of ciphers supported).

SSLCertificateFile

包含有服务器证书的文件路径。 格式是 PEM-encoded.

SSLCertificateKeyFile

Name of the file that contains the server private key. The format is PEM-encoded. The default value is the value of "SSLCertificateFile" and in this case both certificate and private key have to be in this file (NOT RECOMMENDED).

SSLPassword

Pass phrase for the encrypted private key. If "SSLPassword" is not provided, the callback fonction should prompt for the pass phrase.

SSLVerifyClient

Ask client for certificate. 默认为 "none", meaning the client will not have the opportunity to submit a certificate. Other acceptable values include "optional", "require" and "optionalNoCA".

SSLVerifyDepth

Maximum verification depth for client certificates. 默认为 "10".

SSLCACertificateFile

见 mod_ssl相关文档.

SSLCACertificatePath

见 mod_ssl相关文档.

SSLCertificateChainFile

见 mod_ssl相关文档.

SSLCARevocationFile

见 mod_ssl相关文档.

SSLCARevocationPath

见 mod_ssl相关文档.

下面是SSL连接器定义的一个范例:

    <Connector port="443" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" scheme="https" secure="true"
               SSLEngine="on"
               SSLCertificateFile="${catalina.base}/conf/localhost.crt"
               SSLCertificateKeyFile="${catalina.base}/conf/localhost.key" />

AJP

When APR is enabled, the AJP connector will use a socket poller for keepalive, increasing scalability of the server. As AJP is designed around a pool of persistent (or almost persistent) connections, this will reduce significantly the amount of processing threads needed by Tomcat. Unlike the HTTP connector, the AJP connector cannot use sendfile to optimize static file processing.

The following attributes are supported in the AJP APR connector in addition to the ones supported in the regular AJP connector:

Attribute Description
firstReadTimeout

The first read of a request will be made using the specified timeout. If no data is available after the specified time, the socket will be placed in the poller. The value of this attribute is in ms. Setting this value to 0 or -1 will increase scalability by always using a poller to handle keepalive, but will have a minor impact on latency (see the related pollTime attribute). The difference is that with 0, the first read of a request will be made using a short timeout, while with -1, the first read will be made using the regular socket timeout that is configured on the connector. Setting this to -2 will cause the connector to not use the poller for keepalive in most situations, emulating the behavior of the java.io HTTP connector. The default value is -1. Note: on Windows, the actual value of firstReadTimeout will be 500 + the specified value, if the specified value is strictly positive.

pollTime

Duration of a poll call. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (5ms).

pollerSize

Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keepalive connections.

Copyright © 1999-2006, Apache Software Foundation


Apache Tomcat 5.5 Servlet/JSP 容器 - 怎样配置负载均衡

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

怎样配置负载均衡

 Printer Friendly Version
print-friendly
version
目录

使用JK 1.2.x 本地连接器
使用 Apache HTTP Server 2.x 和 mod_proxy
使用具有均衡功能的web应用

使用JK 1.2.x 本地连接器
请参考 JK 1.2.x 相关文档.
使用 Apache HTTP Server 2.x 和 mod_proxy
请参考 Apache HTTP Server 2.2.x的mod_proxy有关文档. 它支持 HTTP 或者 AJP 方式的负载均衡. 新版的 mod_proxy 在 Apache HTTP Server 2.0业可以使用, 但 mod_proxy 是从Apache HTTP Server 2.2中分离编译出来的。
使用具有均衡功能的web应用
概要

Tomcat 5.0.15 及以后版本均带有叫做balancer的web应用。这是一个基于规则的负载均衡的简单实现。 它不是设计用来代替其它用于高流量环境的装载均衡机制。相反，它是个简单的，纯Java，易扩展，在多个服务器之间是分担负载的简便方式。

尽管Tomcat自带带均衡器，但它不是Tomcat特有的，它不需要任何修改就能在其他容器上运行。 如果你想通过过滤器来重定向客户端请求，该web应用需要支持Servlet 2.3或其后版本的容器。 如果你想通过servlet来重定向客户端请求，你可以使用任意的servlet容器。

配置范例

默认的均衡器安装使用一个单独的过滤器，BalancerFilter，用来映射所有的请求(url-pattern /*)。 过滤器从web应用部署描述文件(web.xml)里指定的规则文件中读取规则。默认的规则有：

  • URL里含有"News"的请求转向www.cnn.com
  • 把一个带有paramName的参数，参数值是paramValue的请求转向www.yahoo.com。
  • 把所有其它请求转向jakarta.apache.org。
因此，当你安装并启动好tomcat之后，在浏览器中访问http://localhost:8080/balancer，将被转向到http://jakarta.apache.org。 如果浏览器访问http://localhost:8080/balancer/News，将被转向到http://www.cnn.com。 一个http://localhost:8080/balancer/BlahBlah?paramName=paramValue的请求会被转向到http://www.yahoo.com。

负载均衡规则

均衡器系统的规则是一个请求匹配条件，以及相匹配请求的URL重定向的组合。这些规则实现org.apache.webapp.balancer.Rule接口。

均衡器发布包自带许多有用的规则。这个框架被设计成很方便扩展，这样你可以快速编写你自己的规则。 规则必须是标准的JavaBean (公有的无参数构造方法， 属性具有公有的setter 方法，比如 属性xxx的setXXX ), 就象它们被Jakarta Commons Digester实例化那样。关于规则的可使用性或怎样把你的规则包含到发布包中去，请到tomcat-user邮件列表上询问。

规则被组装在RuleChains里边。每个BalancerFilter (或者 Servlet/JSP)在做转向的决定时参考一个RuleChain。 注意，你不是象范例配置里那样被限制只有一个对应于/*的过滤器。你可以使用Servlet Specification里定义的full filter mapping可能性，随意配置多少你想要的过滤器。每个过滤器有它自己的RuleChain。

它是怎么工作的

  1. 首先编写一个包含各种匹配规则和重定向的配置文件。
  2. 在web.xml文件中定义均衡器过滤器，将它映射到你想要的url(通常都是 /*) ，并通过配置文件里的规则来配置。
  3. 服务器启动，初始化过滤器。
  4. 请求传入服务器。过滤器匹配规则链来决定把这个请求转向哪里。规则是按照规则配置文件里定义的顺序来进行匹配的。 找到第一个匹配上的规则后，不再继续匹配，这个请求马上被重定向。

备注

请将问题，评论，建议等发往tomcat-user邮件列表。谢谢。


Apache Tomcat 5.5 Servlet/JSP 容器 - Building Tomcat

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Building Tomcat

 Printer Friendly Version
print-friendly
version
Introduction

Building Tomcat from SVN is very easy, and is the first step to contributing to Tomcat. The following is a step by step TODO list.

Download and install a Java Development Kit 1.4.x or later

The default distribution of Tomcat 5.5.x requires a 5.0 or later JDK. Tomcat can be built using a 1.4.x JDK but you will need to copy the contents of the compat directory (created by the build process) to your build directory before Tomcat will start.

The Sun JDK can be downloaded here.

IMPORTANT: Set an environment variable JAVA_HOME to the pathname of the directory into which you installed the JDK release.

Install Apache Ant 1.6.2 or later

Download a binary distribution of Ant 1.6.2 or later from here.

Unpack the binary distribution into a convenient location so that the Ant release resides in its own directory (conventionally named "apache-ant-1.6.x"). For the purposes of the remainder of this document, the symbolic name "${ant.home}" is used to refer to the full pathname of the release directory.

Create an ANT_HOME environment variable to point the directory ${ant.home}, and modify the PATH environment variable to include directory "${ant.home}/bin" in its list. This makes the "ant" command line script available, which will be used to actually perform the build.

Building Tomcat

Download the main build.xml script from here.

Create a new directory, and copy the newly download build.xml to it. This directory will be referred to as the ${tomcat.source} directory in the rest of this document.

Go to that directory, and do:
cd ${tomcat.source}
ant

NOTE: Users accessing the Internet through a proxy must use a properties file to indicate to Ant the proxy configuration. Read below.

WARNING: Running this command will checkout the Tomcat 5 sources from SVN, as well as download binaries to the /usr/share/java directory. Make sure this is appropriate to do so on your computer. On Windows, this usually corresponds to the C:\usr\share\java directory, unless Cygwin is used. Read below to customize the directory used to download the binaries.

The build can be controlled by creating a ${tomcat.source}/build.properties file, and adding the following content to it:
# ----- Proxy setup -----
# Uncomment if using a proxy server.
#proxy.host=proxy.domain
#proxy.port=8080
#proxy.use=on

# ----- Default Base Path for Dependent Packages -----
# Replace this path with the directory path where
# dependencies binaries should be downloaded.
base.path=/usr/share/java

Updating and rebuilding Tomcat sources

It is recommended to regularly update the downloaded Tomcat 5 sources. To do this, execute the following commands:
cd ${tomcat.source}
ant checkout

For a quick rebuild of only modified code you can use:
cd ${tomcat.source}
ant build

Building with Eclipse

Important: This is not a supported means of building Tomcat; this information is provided without warranty :-). The only supported means of building Tomcat is with the "ant build" described above. However, some developers like to work on Java code with a Java IDE, and the following steps have been used by some developers.

Note that you must complete all the above steps to fetch the repositories and build some JAR files the first time. After you have completed the above steps, you can set up a series of Eclipse 4 projects. Note that this will not let you build everything under Eclipse; the build process requires use of Ant for the many stages that aren't simple Java compilations. However, it will allow you to view and edit the Java code, get warnings, reformat code, perform refactorings, run Tomcat under the IDE, and so on.

Use Windows->Preferences and then Java->Build Path->Classpath Variables to add two new Classpath variables:

TOMCAT_LIBS_BASE | the base path where the binary dependencies have been downloaded
ANT_HOME | the base path of Ant 1.6.2 or later

Use File->New Project to create a new Java project for each of the binaries repository (e.g., /usr/share/java), container, connectors, jasper, servletapi. Unless you thought ahead to make the ${tomcat.source} directory be under your Workspace folder, tell Eclipse the external location using "Import/Export...", General->Existing Project into Workspace.

Eclipse .project and .classpath files are provided in each of these directories so Eclipse should find all source trees and jars, and hopefully compile without problems. Note that these files assume you are using Eclipse with a 5.0 or later JDK; also, the connectors module must be built with a compiler compliance level of 5.0.

To run Tomcat without a special IDE plug-in, you can simply use Run->Run... enter "org.apache.catalina.startup.Catalina" as the main class, "start" as program arguments, and "-Dcatalina.home=..." (with the name of your build directory) as VM arguments.

Note also that due to the way the Tomcat source is assembled from several SVN projects, you may not be able to use the Eclipse SVN client to update (nor to commit, if you are a committer). Use the external SVN client of your choice, then use the Eclipse PackageExplorer or Navigator "Refresh" context menu item to tell Eclipse that you've updated the files.

Building with other IDEs

The same caveats apply as for Eclipse, above.

The same general idea should work in most IDEs; it has been reported to work in Idea, for example.


Apache Tomcat 5.5 Servlet/JSP 容器 - 怎样使用CGI

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

怎样使用CGI

 Printer Friendly Version
print-friendly
version
简介

CGI (通用网关接口)定义了让web服务器与外部内容生成程序交互的一种方式，也就是通常所说的CGI程序或CGI脚本。

当你使用Tomcat作为你的HTTP服务器，并要求提供CGI支持，你就可以把CGI支持添加到Tomcat里。通常在你还不想要运行一个象Apache httpd这样的web服务器的开发过程中它就已经被实现了。Tomcat的CGI支持在很大程度上与Apache httpd's相兼容，但是存在一定局限(例如，只有一个cgi-bin 目录)。

CGI支持是通过使用servlet类org.apache.catalina.servlets.CGIServlet 来实现的。习惯上，这个servlet与URL映射 "/cgi-bin/*"相对映。

在Tomcat默认不支持CGI。

安装

警告——CGI脚本可以用于执行Tomcat的java虚拟机外部的程序。如果你在使用Java SecurityManager，它可以绕过你在catalina.policy里配置的安全策略。

将$CATALINA_BASE/server/lib/servlets-cgi.renametojar 改名为 $CATALINA_BASE/server/lib/servlets-cgi.jar

将$CATALINA_BASE/conf/web.xml 文件中CGI servlet 和servlet-mapping 配置周围的XML注释去除掉。

配置

以下几个servlet初始化参数可以用来配置CGI servlet的行为。

  • cgiPathPrefix - CGI搜寻路径从web应用程序的根目录 + 文件分割符 + 路径前缀 开始。默认的cgiPathPrefix是/WEB-INF/cgi 。
  • debug - servlet日志信息的调试级别。默认是0。
  • executable - 用来运行script的可执行程序名。默认是perl。
  • parameterEncoding - 与GCI servlet一起使用的参数编码名称。 默认是System.getProperty("file.encoding","UTF-8") 。
  • passShellEnvironment - 是否将shell的环境变量 (任意) 传给 CGI 脚本? 默认为 false.


Apache Tomcat 5.5 Servlet/JSP 容器 - 修订记录

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

修订记录

 Printer Friendly Version
print-friendly
version
Tomcat 5.5.21 (fhanik)
Catalina
fix | 29727: If env-entry values in web.xml are changed then ensure new values are applied when context is reloaded. (markt)
fix | 34956: Ensure request and response objects passed to a RequestDispatcher meet the requirements of SRV.8.2 and SRV.14.2.5.1. This is disabled by default. The Java option -Dorg.apache.catalina.STRICT_SERVLET_COMPLIANCE=true is required to enable this test. (markt)
fix | 36274: When including static content with the DefaultServlet also treat content types ending in xml as text. (markt)
fix | 37439: Update documentation for Engine component to add the requirement that the name must be unique. (markt)
fix | 37458: Add syncs to the WebappClassloader to address rare issues when multiple threads attempt to load the same class concurrently. (markt)
fix | 39436: Correct MIME type for SVG. (markt)
fix | 39724: Removing the last valve from a pipeline did not return the pipeline to the original state. Patch provided by David Gagon. (markt)
fix | 36976: Don't use CATALINA_OPTS when stopping Tomcat. This allows options for starting and stopping to be set on JAVA_OPTS and options for starting only to be set on CATALINA_OPTS. Without this fix, some startup options (eg the port for remote JMX) would cause stop to fail. Based on a fix suggested by Michael Vorburger. (markt)
fix | 37070: Update mbean name documentation to include the StandardWrapper. (markt)
fix | 40528: Add missing message localisations as provided by Ben Clifford. (markt)
fix | 40625: Stop CGIServlet swallowing the root cause of an exception. Patch provided by Takayoshi Kimura. (markt)
fix | 40723: Correct table creation example in JavaDoc for JDBCAccessLogValve. (markt)
fix | 40802: Add jsp-api.jar to fileset in catalina-tasks.xml as provided by Daniel Santos. (pero)
fix | 40817: Correct problem where CGI scripts in the root of the ROOT context threw a StringIndexOutOfBoundsException. (markt)
update | Set the SCRIPT_FILENAME environment variable required by PHP when using the CGIServlet to execute PHP.
fix | 40823: Update context doc to clarify use of ROOT.xml, multi-level context paths and to further discourage use of server.xml (markt)
Coyote
fix 40771: Fix implementation of SavedRequestInputFilter.doRead() so POST data may be read using a Valve or Filter. Patch provided by Michael Dufel. (markt)
Webapps
fix | 34952: Clarify that the Windows Installer always installs a Windows service. (markt)
fix | 35968: Make environment entry properties input a text area. Patch provided by Tristan Marly. (markt)
fix | 38048: Fix memory leak assoaciated with use of expression language in JSPs. Patch provided by Taras Tielkes. (markt)
fix | 40633: Remove references to the DefaultContext from the documentation. (markt)
Cluster
add Add better recovery at FastAsyncQueueSender. Made the startegy more robust for temporary connection problems (pero)
Tomcat 5.5.20 (fhanik)
Catalina
fix | Fix logic error in UserDatbaseRealm.getprincipal() that caused user roles assigned via groups to be ignored. (markt)
fix | 40518: Use correct message when a RuntimeException is thrown from the requestInitialized or requestDestroyed method of a listener that implements ServletRequestListener. (markt)
Jasper
fix | 31804: Unnested tags within a tag file are now configured with the Tag represented by the containing tag file as their parent tag. (markt)
fix | 33356: Tag attributes that contained $ followed by 1 or more non-special characters and then a { character caused an exception. (markt)
fix | 33407: The string \$ in template text was reduced to $ when the isELIgnored page directive was set to true. (markt)
fix | 34509: Tag names may now use the full range of characters permitted by xsd:nmtoken. (markt)
Webapps
fix 34399: Disable undeploy for applications that have not been deployed such as those defined in server.xml (markt)
Tomcat 5.5.19 (fhanik)
General
update Add multi attribute setting to jmx:set JMX remote ant task. Patch contributed by Didier Donsez (pero)
Catalina
fix | 30762: Re-fix this bug that was re-introduced by the fix to 37264. (markt)
fix | 37588: Fix JNDI realm creation through JMX. Patch contributed by TerryZhou (fhanik)
fix | 39704: The use of custom classloaders failed when the context was specified in server.xml. Correction of the fault will require setting the new loader attribute useSystemClassLoaderAsParent to false. (markt)
Coyote
fix 40418: APR Endpoint socket evaluation (remm)
Webapps
fix 31339: Admin app threw exceptions if a name other than Catalina was configured for the Engine. Patch based on a suggestion from Amila Suriarachchi. (markt)
Tomcat 5.5.18 (yoavs)
General
update Change MD5 release signature files to have md5 (小写) extension instead of MD5 (大写), 来自 Henk Penning 和 specified 在 ASF 发行出版指导. (yoavs)
Catalina
fix | Fix that ManagerBase increment expireSessions counter at background task two times. (pero)
fix | 39406: 修正StandardSession#getLastAccessedTime()方法使用正确的异常信息, 该建议来自 Takayoshi Kimura. (pero)
add | 39661: 新增关于JULI FileHandler properties的文档. (yoavs)
add | 39657: 如果JSP API 存在于web应用的类加载路径中将提示警告信息 (不再加载该jar) , 该建议来自David Sanchez Crespillo. (yoavs)
add | 39674: 在 service.bat 脚本中支持 JRockit JVM, 该建议来自 lizongbo . (yoavs)
fix | 39711: 更新加载器配置文档, 该建议来自 Stephane Bailliez. (yoavs)
fix | 39865: 新增Open Office的mime类型到conf/web.xml. (markt)
fix | 38814: Align CGI handling of indexed queries, parameters and POST content with other CGI providers. The changes: only provide parameters on the command line for indexed queries; always provide the query string via the QUERY_STRING environment variable; provide POST content unmodified to stdin; and never call getParameters(). (markt)
fix | 34801: Partial fix that adds handling of IOExceptions during long running CGI requests. Based on a patch by Chris Davey. (markt)
fix | 39689: Allow single quotes (') and backticks (`) as well as double quotes (") to be used to delimit SSI attribute values. (markt)
fix | 40053: Correct application deployment documentation so it agrees with the classloader documentation regarding shared lib and CATALINA_BASE. (markt)
fix | 39592: Stop HEAD requests for resources handled by SSI servlet or filter generating stack traces in the logs. (markt)
fix | Improve handling of the ';' character in the URL so that it is now allowed if properly %xx encoded. (remm)
Coyote
fix Fix APR endpoint so that the acceptor thread now only processes socket accepts. (remm)
Webapps
fix | 39813: Correct handling of new line characters in JMX attributes. Patch provided by R Bramley. (markt)
fix | 37781: Make sure that StoreConfig save external referenced war files at context.xml correct. (pero)
fix | 39791: Use correct default for useNaming within a Context. (markt)
fix | Correctly generate re-direct for admin app index.jsp to prevent login page being displayed twice when cookies are disabled. (markt)
Cluster
fix 39473: 集群环境中，Session 超时远小于web.xml 中的配置,该建议来自 Jin Jiang. (pero)
Tomcat 5.5.17 (yoavs)
General
update | 更新至 Xerces 2.8.0 (remm)
update | 更新至 tcnative 1.1.3 (remm)
Catalina
fix | Fix SingleSignOn Valve and add Session.getLastAccessTimeInternal() without session invalidation test. (pero)
fix | 38814: CGIServlet 正确处理 Shift_JIS 输出. (markt)
fix | 新增遗漏的环境变量“REQUEST_URI” 到 CGI 环境中. (markt)
fix | 27617: Sync existing mime types with httpd. (keith)
fix | 38761: Handle relative symlinks to shell scripts as suggested by Adam Murray (keith)
fix | 38795: Associate more closely bind with a finally unbind in StandardContext start and stop, based on a patch by Darryl Miles (remm)
fix | Improve undeployment robustness (remm)
update | Expand the semaphore valve (remm)
fix | 39021: Add back support for authentication only, submitted by Scott Stark (remm)
fix | Revert fix for 38113, which does not seem a legitimate problem, and causes regressions (remm)
fix | 当重新加载web应用时正确的重置监听器(remm)
fix | 38194: Don't fail silently if -force is used without CATALINA_PID, submitted by Matthew Buckett. (yoavs)
fix | 38154: 在web应用取消部署避免FileDirContext中的NPE错误 , 该报告来自 Jamie Maher. (yoavs)
fix | 38217: Added cautionary note about keystore password to SSL HowTo,该建议来自 Ralf Hauser. (yoavs)
fix | 38262: Cleared ambiguity in host documentation,该建议来自 Jeffrey Bennett. (yoavs)
fix | 38476: 修改对空的TLD流的检测,该建议来自 Fabrizio Giustina. (yoavs)
fix | 38052: 使用 userName 作为默认的用户字段名. "User" 在很多数据库中是保留关键字 , 该建议来自 rik. (pero)
fix | 修正对"if-range"头信息不存在的处理 (remm)
fix | 37848: Only output catalina.sh diagnostic messages if we have a TTY, submitted by David Shaw. (yoavs)
fix | 38596: Minor performance optimization in DataSourceRealm, suggested by Sandy McArthur. (yoavs)
Coyote
fix | Make the default cipher suites available for SSL the same as the set of cipher suites enabled by default rather than the set of all cipher suites. This prevents ciphers suites that do not provide confidentiality protection and/or server authentication being used by default. (markt)
fix | Move AprEndpoint.getWorkerThread inside the try/catch for the main accept loop, to guard about an OOM (which would most likely doom the server anyway) (remm)
fix | As exhibited in the ASF's JIRA installation, it seems EINTR is a status code that should be ignored as a result to a poll call (remm)
update | New APR connectors defaults (remm)
update | Add multiple threads for APR pollers, to work around Windows limitations (performance degrades very rapidly if poller sizes over 1024 are allowed when compiling APR) (remm)
update | New modes for firstReadTimeout (-1 being the new default) (remm)
update | 在APR 端点中使用一个简单的数组来替代 java.util.Stack (remm)
fix | tcnative jnilib.c now report correct compile flags for runtime Library.java checks like sendfile support default true/false (pero)
Jasper
fix | 38015: Remove misleading warnings logged in TagLibraryInfoImpl,该建议来自 Andrew Houghton. (yoavs)
fix | 38376: Make sure body content stack is always properly aligned, as submitted by Tony Deigh. (yoavs)
fix | 兼容 JDT 3.2 (remm)
Webapps
fix | 39292: 更新 catalina.policy at demo balancer app. 由 Kerry Sainsbury 提供修正(pero)
fix | 36847: Fixed the manager app copy function to not overwrite fileA with fileB when fileA==fileB. Fix provided by Haroon Rafique (fhanik)
fix | 38508: Several enhancements to Host Manager application, including configurable manager app support and dialog box enhancements. Thanks to George Sexton for the patch. (yoavs)
fix | 37781: 确认上下文配置文件为可写属性, 该建议来自 George Sexton. (yoavs,pero)
Cluster
update | Add at PooledSocketSender the jmx attributes inPoolSize and inUsePoolSize. (pero)
fix | DeltaManager 使用备份方式设置session创建时间. (pero)
update | Add JvmRouteBinderValve documentation at cluster-howto.xml. (pero)
add | JvmRouteBinderValve now supports now sessionid's from request and cookies. Thanks to Brian Stansberry for reporting it. (pero)
fix | 38779 Fix wrong jmx message arg at SimpleTcpCluster at o.a.c.cluster.tcp.mbeans-descriptors.xml, submitted by Pawel Tucholski (pero)
fix | Fix that not after every "Keep Alive Socket close" a log warning is generated at TcpReplicationThread (pero)
fix | 39178: Now ROOT.war deployment with FarmWarDeployer is possible (pero)
fix | ReplicationValve not set primarySession flag when all backup nodes gone (pero)
update | Add DeltaSession.getLastAccessTimeInternal() without session invalidation test. (pero)
Tomcat 5.5.16 (yoavs)
General
update | Updated / enhanced docs to remove old FIXME references. (yoavs)
update | Required tcnative library version upgraded to 1.1.2 (remm)
update | Update to Eclipse JDT 3.1.2 (remm)
Catalina
fix | 23950: Context.listBindings() should return objects not references. (markt)
fix | 38124: Add support for Windows 20xx when reading environment variables in CGIServlet. (markt)
fix | 29214: response.containsHeader() now returns the correct value for Content-Type and Content-Length headers. (markt)
fix | Allow using a custom ContextConfig when using JMX embedding of Tomcat, as is done by the regular deployer. (remm)
add | Add JMX serverInfo attribute to Server MBean, that we can identify the tomcat release remotely. (pero)
fix | Fix the JMX MBeanFactory.createStandardHost signature at mbean-descriptors.xml (pero)
fix | Fix some cases (for example with realm usage) where the container logger for a context would be retrieved using the wrong classloader (remm)
fix | HttpSession.getId will no longer throw an ISE when the session is invalid (remm)
fix | More detailed errors for naming issues (remm)
docs | Add documentation for the Transaction element (remm)
update | Add getContextPath to the internal servlet context implementation (remm)
fix | Only null instances loaded by the webapp CL, submitted by Matt Jensen (remm)
update | Deploy folders which don't have a WEB-INF, and return an error when a context file does not contain a Context element (remm)
fix | 38653: Fix property name (remm)
fix | Slightly modify the timing of the manager start, so that it is not started by a listener (remm)
fix | Refresh loggers used by the digester (remm)
fix | Use sendError instead of setStatus to send the 401 code. (billbarker)
fix | Don't append the port for an SSL redirect if it is the default port. (billbarker)
Coyote
fix | Log errors when setting socket options with debug priority rather than error. (remm)
fix | 38100: Make certain that a valid Host name is set, or none at all. (billbarker)
fix | 38485: Fix minor regression setting connection timeout (as well as linger and no delay) where the default value was always used when using the regular HTTP connector (remm)
update | Pass along more of the SSL related fields to OpenSSL (remm)
update | CharChunk now implements CharSequence (remm)
fix | Fix coding error which could cause a rare crash when a poller error occurred and sockets where pending being added to the keepalive poller (remm)
fix | Fix potential sync issues when restarting a poller (remm)
fix | Update APR error reports, including the error codes (remm)
fix | 38726: Remove duplicate request group field causing blank statistics for the HTTP connector (remm)
fix | Fix invalid length used by some AJP packets for the AJP APR connector, which could cause corruption, submitted by Rudiger Plum (jim)
fix | 38346: Fix problems with request.getReader().readLine(). Patch by Rainer Jung (billbarker)
update | Local address reuse for APR Endpoints (via APR_SO_REUSEADDR) now enabled (jim)
fix | Don't write out the shutdown secret file if shutdown is disabled (the default) (billbarker)
fix | Fix NPE when no sink is supplied. (billbarker)
update | APR Endpoints now IPv6 aware (jim)
update | Downgrade "Response already committed" logging entry to DEBUG. (billbarker)
fix | 38113: Return the empty String for an empty query-string instead of null. (billbarker)
Jasper
fix | 38389: Set correct JDT Compiler option to java 1.5 compliance. Patch from Olivier Thomann and Paul Hamer (pero)
update | Add some useful hints to jasper-howto. (pero).
fix | 38776: Fix source file attribute, submitted by Olivier Thomann (remm)
Cluster
fix | Update DeltaManager session access stats (pero)
fix | DeltaSession getId will no longer throw an ISE when the session is invalid (pero)
update | Resurrected the "suspect" property so that the logs don't fill up with errors when member disappears or a connection is lost. Only useful for pooled mode (fhanik)
add | 35710: Add session replication for cross context session changes. The portlet api need this support, see refactored ReplicationValve. (pero)
update | ReplicationValve reset DeltaSession when cluster node has no backup node. (pero)
update | DataSender close connection and throw exception also even if waitForAck is false. (pero)
fix | Active cluster junit test again. (pero)
Webapps
fix | Fix some XSS issues in the JSP examples. (markt)
fix | Fix logos in the manager webapp (remm)
Tomcat 5.5.15 (yoavs)
General
fix 32081: Remove the JDK requirement from the Win32 scripts. (keith)
Catalina
fix | 37852: Fix regression where the magic role '*' was denying all access. Patch by xrcat (billbarker)
fix | 37934: Don't ask for authentication if deny-from-all is in effect. (billbarker)
fix | 15570: auth-constraint of * was interpretted as all authenticated users rather than as all roles defined in web.xml. (markt)
fix | Remove leftover static logger which was used to log application level messages in ApplicationContextFacade (remm)
fix | 38012: Where a CGI script sets a response code, use it. (markt)
fix | 37854: Extension-List checking was too strict. (markt)
Coyote
fix | Report binding errors in the APR endpoint as strings rather than platform specific status codes (remm)
fix | 37934: Don't ask for authentication if deny-from-all is in effect. (billbarker)
fix | 38047: Handle the case where the Servlet attempts to read the Request body from the AJP/1.3 Connector, in the case that no body was sent. (billbarker)
fix | 38030: Unconditionally return EOS for an attempt to read the body of any request that doesn't send CL or TE. (remm, billbarker).
Jasper
fix | 35351: Fix problem using an inner class for a <jsp:useBean />. (kinman).
fix | 37929: Don't stop on the generic attribute methods just because the session is invalid. Patch by Pierre Delisle. (billbarker)
update | Add system properties org.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER and org.apache.jasper.runtime.JspFactoryImpl.USE_POOL to allow configuring Jasper memory usage (remm)
fix | 37933: Restrict <jsp:getAttribute /> to only look in PAGE_SCOPE. (billbarker)
Cluster
fix | 37808: Fix ArrayIndexOutOfBoundsException inside XByteBuffer. Reported by Dietmar Mueller (pero)
update | 37896DataSender starts new Socket after IOException. (pero)
update | Reduce memory usage at membership service. (pero)
Tomcat 5.5.14 (yoavs)
General
update | Update optional native APR connector version to 1.1.1. (mturk)
update | Update build.properties.default to get native connector from new location. (yoavs)
Catalina
fix 13040: Fix getContext() when used to obtain a context that is a sub-context of the current context. Ported from TC4. (markt)
Jasper
fix 37746: Remove extra space from StringTokenizer pattern in JspC,该建议来自 Eric Hedstrom. (yoavs)
Coyote
fix | 36863: Strip quotes when parsing Cookie values, even for v0 Cookies. (billbarker)
fix | 37803: Don't claim that we have a string value in MessageBytes until we actually do. Patch by Doug Rand (billbarker)
Tomcat 5.5.13 (yoavs)
General
fix | 36711: Unused line of code. (yoavs)
update | Removed unused SAXPath, Jaxen dependencies. (yoavs)
update | Update log4j dependency to version 1.2.12, Struts to 1.2.7. (yoavs)
update | Removed JDBC 2.0 StdExt dependency (only class from there is javax.sql.XADataSource, which is present in JDK 1.4 and later. (yoavs)
fix | 37039: typo on JK Quick configuration how-to. (yoavs)
add | 37035: Add a placeholder file in the temp directory for WinZip tar.gz handling. (yoavs)
update | Update JAF dependency to 1.0.2, JTA to 1.0.1b and JavaMail to 1.3.3_01. (markt)
add | Added Eclipse .project, .classpath, and associated files to make building Tomcat from Eclipse significantly easier. (markt)
add | 37284: Guess JSE 5.0 location on Mac OS X, patch by Stepan Koltsov. (yoavs)
fix | : Wrong class name in antlib.xml for JkStatusUpdateTask. (yoavs)
Catalina
fix | 36802: Fix problem of double-init when JMX-deploying a Context into a started Host. (billbarker)
fix | 36840: Provide information as to which web.xml is being processed on startup to help debug parsing errors. (yoavs)
add | 34724: Ability to set domain for Single-Sign-On cookie. Patch by Oliver Rossmueller. (yoavs)
fix | 37044: RealmBase.hasResourcePermission needs to access the GenericPrincipal as set by the realm unless hasRole is overriden, which was no longer being done properly for the JAAS realm (remm)
fix | 37264: JNDI resources were no longer available when stopping listeners, submitted by Bogdan Calmac (remm)
fix | 37150: Turn off directory listing by default and add a warning regarding enabling listing of directories with many entries. (markt)
update | Add configurability for the amount of time that the container will wait for requests to complete when unloading servlets, using the unloadDelay property. (remm)
update | Add code to set to null fields in loaded classes when stopping a web application, as a possible workaround for suspicious garbage collection behavior. (remm)
update | Update messages and stack traces for classloading errors which may occur when removing a web application, and for stopped web applications. (remm)
fix | 37319: Fix catalina.bat reference to CATALINA_BASE for logging.properties. Thanks to Pierre-Yves Benzaken. (yoavs)
fix | 36852: Custom classloaders don't honor Contet privileged attribute. Thanks to Matt Brinkley for the analysis and patch. (yoavs)
fix | Fix for a couple of (mostly silly) edge-cases in testing auth. Thanks to Nam T. Nguyen for the report. (billbarker)
fix | 37060: Actually copy the Request headers when replaying after Form auth. (billbarker)
fix | 37591: Typo in Engine configuration reference. (yoavs)
fix | 37668: Added note about JSP recompilation to Context configuration documentation. (yoavs)
fix | 37132: Have DigestAuthenticator Handle user names with commas. Thanks to Robert Wille for the patch. (yoavs)
fix | 37212: Better error reporting in Connector.java. Thanks to Ralf Hauser for the patch. (yoavs)
Coyote
fix | Gracefully handle the case where some Socket options are disabled at the OS level for the AJP/1.3 Connector. (billbarker)
fix | 36366: Use rewritten deployer-howto page by Allistair Crossley. (remm)
add | 36630: Added extra log output for class instantiation failure. (yoavs)
fix | 37121: Sendfile always needs to be given the length of data to write, which fixes ranged requests. (remm)
fix | Optimized direct byte buffers association with the socket for APR connectors. (mturk)
fix | Fix hidden NPEs when using the APR connectors and there's no host header. (pero, remm)
fix | Http11Protocol now register RequestProcessor at JMX and show current usage inside manager app. (pero)
add | JkStatus Ant tasks for mod_jk 1.2.15. (pero)
update | Connection Timeout is normal, so reduce logging to DEBUG (billbarker)
fix | Fix crash which could occur with the HTTP APR connector when accessing request JMX objects outside of the processing of the said request (remm)
fix | 37627: Fix buffering issue in the HTTP APR connector when a large buffer size was used for servlets (remm)
fix | 37673: Fix implementation of getLocalPort and getLocalAddr in the HTTP APR connector (remm)
Jasper
fix | 35252: Jasper PageDataImpl outputs malformed XML. Patch by Rahul Akolkar. (yoavs)
add | 37062: Helpful JSP exception message containing file, line numbers. Patch by Tim Fennell at http://www.tfenne.com/jasper/. (yoavs)
fix | 37407: File descriptor leak in JspReader. Thanks to Fred for the patch. I also did some minor cleanup in the class. (yoavs)
add | 37612: Add file location to JSP Validator error message. Thanks to Renaud Bruyeron for the patch. (yoavs)
Cluster
fix | Fix that session replace messages are logged after node recovery get all session from master node. (pero)
fix | 37896 Fix that sendMessage signature at all DataSender subclasses must be changed. Now pooled and async modes working as expected. (pero)
fix | Fix that socket at o.a.c.cluster.tcp.FastAsyncSocketSender can be disconnect/connect. (pero)
fix | Fix cluster module build.xml script for new svn repository structure (pero)
fix | Fix closed socket exceptions at normal server shutdown, reported by Olve Hansen (pero)
fix | Fix closed socket exceptions inside async message transfer modes (pero)
fix | 34984: HttpSessionBindingEvent.getValue() get correct value (pero)
fix | 35916: send sessionCreated to SessionListener after cluster node recovery (pero)
fix | 36541: Used also Hashtable at DeltaSession (pero)
fix | Better support cluster at engine level. (pero)
fix | 36866: Correct attribute name in conf/server.xml documentation for Cluster element. (yoavs)
fix | 37261: Allow xerces to know where the web.xml file is so that relative entities can be resolved.
fix | 37529: Fixed race condition in ReplicationLister#stopListening. Thanks to Chris Walker for the patch. (yoavs)
Webapps
fix | Remove obsolete TagPlugin file from JSP examples (billbarker)
fix | 36019: Made clear the Host-Manager HowTo is coming soon, not ready yet. (yoavs)
fix | 36336: Check WAR extension in both upper and lower case,该建议来自 A. Grasoff. (yoavs)
fix | 35982: Can't delete mail sessions in admin webapp. (yoavs)
fix | 36673: Similar to the one above, for data sources. (yoavs)
Tomcat 5.5.12 (yoavs)
General
fix | Remove uneeded files in conf. (remm)
update | Change distribution file names from jakarta-* to apache-*. (remm)
Catalina
add | Add JMX Remote create and unregister ant tasks (pero)
fix | 36343: Only normalize out backslash on Windows platforms. (billbarker)
fix | Allow configuring standard stream redirection. (remm)
add | 36088: Add RUNNING.txt and RELEASE-NOTES.txt to fulldocs distro. (yoavs)
fix | 36534: fix equals for URLs returned by ServletContext.getResource() (luehe)
fix | 36558: Clear IntrospectionUtils cache when stopping a webapp, as it could leak to keeping a reference to the classloader (remm)
fix | 36113: Session persistence for objects with primitive types could fail in some rare cases (remm)
fix | 36541: Full synchronization for session objects attributes collections (remm)
fix | 35609: service.bat echo command when wrong arguments given [patch by Robert Longson] (yoavs)
fix | 34749: jsessionid dropped on trailing slash (/) redirect (remm)
Coyote
update Add support for secret for AJP APR (remm)
Jasper
fix | Fix NPE with an error message when no Java compiler is available (remm)
fix | Restrict System err stream capture to the Ant compiler, as the Eclipse compiler does not need it (remm)
update | JSP compilation speed improvement using tag library information caching, submitted by Xingbo Gao (remm)
add | Initial contribution of JSTL tag plugins supporting the core tag library of JSTL, submitted by Jing Li (remm)
Cluster
fix | 36541: Sync all session attribute access (read and write) at DeltaSession (pero)
fix | 36518: Classname typos for senders, submitted by Christoph Bachhuber-Haller (remm)
add | 35613: Added FAQ question and answer about tcpListenAddress="auto" and /etc/hosts (yoavs)
update | Moved FAQ section for Clustering from Clustering HowTo page to its own FAQ page. (yoavs)
Webapps
docs | 36319: Fix broken link to DBCP docs, submitted by Xavier Poinsard (remm)
docs | Brand new deployer specs, submitted by Allistair Crossley (remm)
Tomcat 5.5.11 (yoavs)
General
update | Update to Xerces 2.7.1 (remm)
add | Add ready to build bin/tomcat-native.tar.gz for the APR JNI wrapper library (remm)
fix | 35930: Bad logging config used by the Tomcat Windows service (remm)
add | 33261: Windows installer now checks the user type and warns non-admins as needed. (yoavs)
update | The Windows installer will now optionally download a (32bit) Windows .dll for Tomcat native from HEAnet (remm)
fix | Declaration of jspc Ant task to fix the deployer package (remm)
Catalina
add | Add concurrency control valve (o.a.c.valves.SemaphoreValve). As the Tomcat distribution is not built for Java 5, the valve will have to be compiled from the sources using Java 5 (remm)
fix | 35880: Ignore JSSE15SocketFactory when generating JavaDoc, as it breaks the JDK 1.4 JavaDoc tool. (yoavs)
fix | 35865: setclasspath.sh cannot be excutive under cygwin. (funkman)
fix | 33267: Set working path in service installer,该建议来自 Dominik Drzewiecki. (yoavs)
update | 34794: Update connector documentation to include clientAuth attribute. (yoavs)
fix | 35894, 36228: Fix CNFE when starting in a sandbox. (billbarker, remm)
fix | Add version check for Tomcat native so that incompatible API changes are detected early (remm)
fix | 36020: Allow MemoryUserDatabase to work better on write protected mediums, submitted by Rainer Jung (remm)
fix | 35978: Bad handling of single range requests greater than 2GB in the DefaultServlet (remm)
fix | 35984: Client abort exceptions will now use getCause (remm)
fix | Fix handling of non-file based includes with SSI, submitted by David Becker (markt)
Coyote
fix | Fix default ports for http and https which are set in the request when the parsed hostname does not specify the port, and which were inverted (https was set as 80 and http as 443). (remm)
fix | Add missing tomcatAuthentication attribute to the AJP APR implementation. (remm)
fix | Check filename sendfile attribute only if sendfile is enabled. (remm)
fix | Fix output buffering for APR AJP implementation. (remm)
fix | 35941: Fix getRemoteAddr for APR AJP implementation. (remm)
fix | 35942: Fix NPE retriving cipher suite attribute when no certificate was submitted (for example with no SSL). (remm)
fix | Internationalization and code cleanups for APR AJP implementation. (remm)
fix | Security exception in APR AJP implementation when running with the security manager enabled. (remm)
fix | 36173: Add missing sync in FastHttpDateFormat.formatDate, submitted by Alexei Krainiouk (remm)
fix | Disable HTTP compression when sendfile is used for a resource (remm)
fix | AJP secret attribute report only at trace level. (pero)
Jasper
fix 36127: Validation compatibility with Xerces 2.7.1, submitted by Florent Benoit (remm)
Cluster
fix | Fix NPE when cluster stops (pero)
fix | 36218: MemoryRealm now support also GenericPrincipal, but JAASRealm with cluster replication still has a problem, detected by Dirk Dekok (pero)
Webapps
Tomcat 5.5.10 (yoavs)
General
add | Add JMX remote ant task to control tomcat MBeanserver via ant scripts. Ant lib is included at "server/lib/catalina-ant-jmx.jar" and documentation is added to Monitoring and Managing Tomcat How-To (pero)
fix | 34361: Integrate better antlib and import support for catalina manager tasks [Modified patch from Daniel Santos] (pero)
fix | StoreConfig save now the Connector.sslProtocol attribute. (pero)
update | Change log dir at service.bat to "$CATALINA_BASE/logs" for better multi instance support. (pero)
update | 34237: Added note and links to context and host configuration references in JNDI DataSources HowTo to aid the clueless. (yoavs)
update | 34248: Update JavaMail download instructions to include JAF. (yoavs)
update | Update to JDT from Eclipse 3.1, with support for Java 5 (remm)
update | Refactoring, redesign and extend the cluster module - Cluster can be configured as subelement from Engine and Host. - Optimized performance and reduce memory usage - Better JMX support - add a lot of JMX stats attribute for better monitoring - add a single element default cluster configuration - more config options LifecycleListener ClusterListener more than one cluster valves - better subclass support - change a lot of existing cluster API's (pero)
add | Add Apache Portable Runtime JNI wrapper and helper API (mturk)
update | Update JULI to provide support for taking over java.util.logging bootstrap configuration, and move the default properties file to ${catalina.base}/conf/logging.properties (remm)
fix | 34746: Updated catalina.properties instructions per Bill Edwards' suggestion. (yoavs)
fix | 35090: Minor documentation typo fix. (yoavs)
fix | 34931: Rewrote ROOT/index.jsp to be XHTML strict compliant, per Richard Beton's patch. (yoavs)
Catalina
fix | 20380: Access log timestamps now take account of Daylight Saving Time (DST). (markt)
add | 34220: Provide better error message when server.xml can't be located. [Modified patch from Ralf Hauser] (yoavs)
add | Add MessageListener and LifecylceListener cluster saving to storeconfig module (<Cluster ... ><ClusterListener className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" >) (pero)
fix | 33743: Add additional synchronization in webapp classloader to avoid possible race condition when defining a class (remm)
fix | 33711: Add events on passivate and activate to cleanup SSO, and recycle session objects when removing them from a manager (so that anyone keeping references to it would leak a minimal amount of memory) (remm)
update | Re-add patch causing Session.getId to throw an ISE, and make all internal components use a safe getIdInternal method (remm)
update | Store principal to be exposed for Request.getUserPrincipal inside the GenericPrincipal, to remove hacks from the JAAS realm (remm)
fix | 10385: SSI Servlet now includes better support for files that use character encodings other than the platform default.(markt)
fix | Remove CopyParentClassLoader rule, which doesn't seem to be doing anything useful anymore. (remm)
add | Provide an ServletFilter implementation of Server Side Includes (SSI). This was submitted by David Becker under 33106. (markt)
add | Add sendfile support to default servlet, with a sendfileSize configuration attribute. (remm)
update | If APR as well as Tomcat's JNI wrapper for APR are present, use APRized protocol handlers instead of the regular ones (remm)
fix | 22617: When used with an EJB container and a realm that supports the concept of an unauthenticated user (J2EE.3.4.3) BASIC authentication was always authenticating users as the unauthenticated user without giving them a chance to supply a username and password. (markt)
fix | Prevent facade objects cloning (remm)
update | Add missing CGI variables to SSI servlet. Patch submitted by Fritz Schneider. (markt)
fix | 34578: Updated JNDIRealm comment. (yoavs)
fix | 34273: Better Bootstrap warning message. [Path from Ralf Hauser] (yoavs)
update | 34675: Updated Proxy-HowTo page with Servlet API calls. (yoavs)
fix | 34546: Fix problem where the "first" Valve couldn't be removed from a Pipeline. (billbarker)
fix | Fix NPE when POST size exceeds limit defined by maxPostSize. (markt)
fix | Fix FORM authentication so POSTed parameters are not assumed to be encoded with platform default encoding. A side effect of this fix is that the bodies of POST requests that require FORM authentication are now buffered and made available after a sucessful login. (markt)
fix | 34840: Better handling of external WARs redeployment, and ignore docBase specified in context file if within the Host appBase (remm)
fix | Fix handling of symbolic links when the DefaultServlet is generating directory listings. (markt)
fix | 35769: Correct implementation of javax.naming.Context.composeName( Name, Name) in multiple places. Patch provided by Laurent Simon. (markt)
add | 34805: Add warning for suspicious security patterns,该建议来自 Ralf Hauser. (yoavs)
fix | 35819: Use getWorkPath for deleting work directory on context destroy, as suggested by Rob Steele. (yoavs)
Coyote
update | Add support for using "Smart Cards" as trust/keyStore. (billbarker)
update | Add some Mbean attributes and operations to ChannelSocket (pero)
add | Apache Portable Runtime based HTTP/1.1 protocol handler, with SSL support (remm)
add | Add support for simple file-based CRLs under JDK 1.5 (billbarker)
add | Add experimental NIO-Socket channel for the AJP/1.3 Connector (billbarker)
add | 34648: Add configuration option to enable IP-based Virtual Hosts. (billbarker)
update | Refactor the AJP/1.3 Connector to be able to handle more advanced Actions. (billbarker)
fix | Fix connector initialisation so sslProtocol is not required for SSL. (markt)
add | Add bufferSize option to the AJP/1.3 Java connector to control output buffering. (billbarker)
add | Apache Portable Runtime based AJP/1.3 protocol handler (remm)
fix | Delay reading the inital request body packet by default for the AJP/1.3 Java connector. (billbarker)
Jasper
fix | 18477: Allow symbolic links when precompiling JSPs (markt)
add | 34272: Allow specifying the Option class used by the Jasper engine, submitted by Scott Stark (remm)
add | Support for Java 5.0 in JSPs (remm)
update | Java 5 will be the source and target for JSPs when running on Java 5 (remm)
update | 34652: Add the ability to get SMAPs when precompiling, submitted by Daryl Robbins (remm)
fix | 34465: Jspc failure if there is no web.xml (remm)
fix | 35696: Make certain that release is called for custom tags when tag-pooling is disabled. (billbarker)
fix | 35386: Make useBean resources use consistent spelling, from Kurt Huwig. (yoavs)
update | 33522: Update jasper-howto to reflect use of javac switch. (yoavs)
add | 35114: Add failOnError flag to JspC, by ziweth. (yoavs)
fix | 35410: Fixed NPE in JspWriterImpl. (yoavs)
add | 35571: JspC resolved uriRoot relative to Ant project basedir, if any, as suggested by Jason Pettiss. (yoavs)
Cluster
add | Add that cluster can configure as Engine and Host element. (pero)
add | Add single cluster default configuration element - discussed at JAX 2005 conference Cluster Workshop. (pero)
fix | Fix resend GET_ALL_SESSIONS when wait ACK failed at receiver side (pero)
fix | ClusterValve now remove from container element when cluster stops and added with next start again. (pero)
add | Set timestamp only at first time inside SessionMessageImpl (pero)
add | Set timestamp from findsessions method call, when handling GET_ALL_SESSION to all SEND_SESSION_DATA and TRANSFER complete messages. (pero>
add | Drop all received message inside GET_ALL_SESSION message queue before state transfer message timestamp. (pero)
add | Cluster ping now transfer cluster domain information and DeltaManager only send and receive message from same domain members (pero)
add | JMX Support for McastService (Membership) (pero)
add | Redesign SimpleTcpCluster message receiving to ClusterReceiverBase (pero)
add | Cluster transfer all attributes to the generate session manager at addManager. Remove some unused attributes at SimpleTcpCluster and ReplicationTransmitter (pero)
update | Refactor DeltaManager: - createSession call now ManagerBase super class method - extract some long methods - send GET_ALL_SESSION with session blocks - don't sync sessions map when send all sessions (pero)
update | Add developer actions at to-do.txt (Proposal of changes) (pero)
update | Small refactorings at FastAsyncSocketSender (pero)
update | Redesign cluster message sending to lesser cpu and memory usage. Set at ReplicationTransmitter#compress=false as default. Change API from ClusterSender, ReplicaitonTransmitter, DataSender, SimpleTcpCluster (pero)
add | DeltaManager has now JMX expireAllLocalSessions and processExipre operation for better cluster node shutdown handling (usefull for testing only) (pero)
add | DataSender doWaitAckStats for better understanding wait ack problems (pero)
update | Refactor DeltaManager and add counter for cluster message send/receive message (pero)
fix | 34389:Porting Clustering fix pack to 5.5.10 code base. Remove synchonized from DataSender.pushMessage(). Very offen the complete cluster blocking after replicated a bulk of new session messages under heavy load. All cluster node standing for a lot of time and made nothing. Fix it for pooled, asynchronous and fastasyncqueue replication mode. Very bad thing, sorry! (pero)
add | Add notifySessionListenersOnReplication attribute to SimpleTcpCluster to stop notify event to SessionListener at backup nodes from create and destroy replicated session (pero)
add | Add compress attribute to ClusterSender and ClusterReceiver interface. Now compress config transfer from sender to receiver at SimpleTcpCluster. (pero)
add | Add ClusterValve interface and implement it as ReplicationValve and JvmRouteBinderValve. Now both Valves can be directly configured at server.xml Host/Cluster/Valve subelements. Also this configuration are correctly handled with the StoreConfig module. (pero)
update | Deactivate DataSender keepAliveMaxRequestCount change default to -1. Cluster replication sockets are fast and very stable! (pero)
update | Setup JvmRouteBinderValve as host valve instead context valve. Refactor the API a little bit. (pero)
fix | Don't increment open socket counter before socket is really open. Add socket open failures counter (pero)
add | Add MessageListener support to cluster server.xml element (ClusterListener) to register your own cluster message receiver (pero)
add | Add LifecycleListener support to cluster server.xml element (Listener) and notify those listener from start/stop cluster, add/remove session manager, sending fault and start/stop member (pero)
add | Add active backgroundProcess keepAlive timeout and request count socket close check at ReplicationTransmitter. Check frequency can be change with attribute processSenderFrequency (default 2). (pero)
add | Remove useless Jdk13ReplicationListener,Jdk13ObjectReader. Add SocketReplicationListener and SocketObjectReader to have nativ socket ClusterReceiver. Also extract ClusterReceiverBase superclass for SocketReplicationListener and ReplicationListener (pero)
update | Add and update some API and the cluster howto documentation (pero)
update | Refactor ReplicationValve for better understanding and small optimization (pero)
add | Starting a unit test suite for cluster module - very much todo (pero)
fix | Fix ant build.xml to direct compile at cluster module directory (pero)
fix | Fix some I18N messages, but a lot of work is waiting for fix (pero)
add | Add ReplicationValve Mbeans stats attribute getter and resetStatistics operation (pero)
Webapps
fix | 35758: Admin webapp mishandling digest attribute of JDBCDataSourceRealm. (yoavs)
add | 34250: Admin webapp Commit Changes button now asks for confirmation. (yoavs)
add | 34818: Alternating row for apps in HTML manager,该建议来自 Jeff Domeyer. (yoavs)
add | 35379: Added commons-logging to build path of manager and host-manager apps, to make them build with Jikes,该建议来自 Aaron Isotton. (yoavs)
Tomcat 5.5.9 (yoavs)
General
add | Add JULI, a java.util.logging implementation, used to provide sane defaults and configurability equivalent to Tomcat 4.0 for Tomcat 5.5 logging (remm)
docs | Add JULI documentation to the logging page (remm)
add | Add host manager webapp (remm)
add | Add ant JkStatusUpdateTask for remote status worker handling ( >=mod_jk 1.2.9) (pero)
add | 33739: Add reference to RUNNING.txt in setup.html. (yoavs)
fix | 33719: Update reference to Ant download page. (yoavs)
fix | 33883: Bad options in SSL-HowTo. (yoavs)
update | Update to MX4J 3.0.1 (pero)
update | 34139: Updated Realm-HowTo to specify JMX, Commons-Logging jars for RealmBase. (yoavs)
add | 33325: Added top-level clean target to Netbuild build.xml file. (yoavs)
update | 33755: Clarified Postgresql JNDI datasource example. [patch submitted by Tom Witmer] (yoavs)
Catalina
fix | Remove some instances of expanded folder removal (remm)
fix | Don't call mkdirs if we're not going to save the configuration in StandardContext (remm)
fix | Fix context classloader binding during loader initialization (it was set to null before) (remm)
fix | The webapp logger should only be retrieved when the context classloader is set to the webapp's classloader (remm)
fix | 34170: Add back retry logic in JDBC realm in case of a connection failure (remm)
fix | 22041: Support dynamic proxies as session objects. (markt)
fix | Fix logger names for wrappers (remm)
fix | 34006: If antiResourceLocking was used, HostConfig considered the path as external, and web application resources were not correctly removed or tacked; also simplify the code a lot (remm)
fix | 34016: Save and restore docBase when using antiResourceLocking, for compatibility with the admin webapp (remm)
add | 33636: Set lastModified attribute when expanding WAR files. (yoavs)
add | 32938: Allow Salted SHA (SSHA) passwords in JNDIRealm. (yoavs)
add | 31288: Allow SMTP authentication for JNDI MailSessionFactory. (yoavs)
update | Harmonize processing of the context.xml defaults with the way web.xml is processed (remm)
fix | Ignore ';' if it is in the query string (remm)
fix | private to protected for the webapp classloader (remm)
fix | Improve logging of filters and listeners startup errors (remm)
fix | 33774: Retry once in JNDI realm authenticate failure regardless of the exception message (remm)
fix | 33961: Don't encode '~' in context paths (remm)
fix | 32866: Propagate distributable property from context to manager (yoavs)
fix | 32867: Reset distributable attribute in context for clean reload handling (yoavs)
update | Fix some RealmBase/JNDIRealm log.isXXXEnabled (pero)
fix | 34161: Harmonize StandardContext.stop with ContainerBase.stop (remm)
Coyote
fix | 33971: Set remoteHost to null when Apache doesn't send one. (billbarker)
fix | Fix calculation of threadRatio for the ms thread pool, and fix setting the updated timeout value (remm)
update | Update the ms thread pool so that we allocate a worker before accepting a new socket, and wait a little if the pool is exhausted; this should make low maxThreads values work a lot better (remm)
update | 33857: Update information on automatic mod_jk configuration in Apache-HowTo (yoavs)
fix | Fix sync block placement in Mapper.addContext (remm)
fix | 32741: Fix spelling of "committed" [patch from Ben Souther] (yoavs)
fix | 34133: Make setHeader clear multi-valued headers (billbarker)
Jasper
fix | 34034: Jasper does not respect external entities (billbarker)
fix | 33810: Incorrect recycling of BodyContent if close is called (remm)
update | Per instance loggers in Jasper (remm)
Cluster
fix | Fix JvmRouteBinderValve primary failover attribute to org.apache.catalina.cluster.session.JvmRouteOrignalSessionID (pero)
fix | Change attribute name waitForAck to sendAck at ReplicationListener (pero)
add | Integrate new fastasyncqueue cluster sender mode. Support queue size limitation, get all queued objects and send it to the backup node, no queue thread lock contention under high replication load, submitted by Rainer Jung (pero)
add | Add compress attribute to Sender and Receiver to transfer data uncompressed. At high cluster load this option consume lesser cpu and memory. Implement the compress handling to ReplicationTransmitter, ReplicationListener, XByteBuffer and Jdk13ReplicationListener (pero)
add | Add doProcessingStats to synchronous, asynchronous and fastqueueasync sender modes to get min, avg, max processing times as IDataSender JMX MBeans (pero)
fix | TcpThreadPool use constant ACK byte array instead create new 3 byte buffer for every message ack (pero)
update | Refactor ReplicationTransmitter and ReplicationListener (pero)
update | add getCatalinaCluster() to ClusterReceiver and SimpleTcpCluster (pero)
update | Update the Api documentation (pero)
Webapps
update | Use the standard struts taglib URIs in admin JSPs. (billbarker)
add | Add more host parameters to create new host with host-manager (pero)
fix | 34033: Fix quoting related bugs (remm)
fix | 33713: Add Struts init code in frameset.jsp as well (remm)
Tomcat 5.5.8 (yoavs)
General
fix | 33204: Fixed SSL HowTo page. (yoavs)
fix | 33351: Fix silent uninstallation. (remm)
fix | 33489: Missing space in uninstaller message. (yoavs)
Catalina
fix | Unregister host mbean and all context mbeans at remove a host, s. StandardHost.destroy() and MBeanFactory.createStandardHost/removeHost(,) detected by Thorsten Kamann (pero)
fix | make it possible to restart connector, now serversocket recreated after stop,start (pero)
fix | change mbean names from Mapper and ProtocolHandler to connector naming style (pero)
update | Add some log.isXXXEnabled (pero)
fix | Deregister MapperListener after remove connector (pero)
fix | Remove host only at own domain with same name at all services, detected by Thorsten Kamann (pero)
fix | 33187: Remove any logging of the password in the JAAS realm, submitted by Andrew Jaquith (remm)
fix | 33033: Don't do anything to the response in the ErrorReportValve if data has already been written (remm)
update | Add charset support for the URLs used by the tasks, to remove deprecation (remm)
fix | 26135: Workaround for memory leak when reloading Struts based web applications by clearing the bean instrospector cache of the JVM on classloader stop, submitted by Tobias Lofstrand. (remm)
fix | Ensure that if CLASSPATH is declared on startup - it is not used. (funkman)
fix | Add back use of deployOnStartup in HostConfig (remm)
docs | Ant tasks docs patches, submitted by Gabriele Garuglieri. (remm)
update | Use NIO for the raw copying operation, as it is faster (a little under 30%), and decreases a little the impact of antiResourceLocking. (remm)
fix | 33357: Fix connection leaks with the DataSourceRealm, as well as improve efficiency, submitted by Dominik Drzewiecki. (remm)
update | Improve a little logging of servlet exceptions, which should all log the root cause. (remm)
update | Add new Manager.createSession(sessionId) method, allowing the client to "specify" the session id which should be used using a cookie when using emptySessionPath="true". This fixes session tracking in this case. (remm)
fix | 33368: Fix memory leak in swallowOutput feature which occurred when the thread pool size is reduced, submitted by Rainer Jung. (remm)
fix | StoreConfig: can't save cluster Membership element (pero)
add | StoreConfig: suppress default jkHome attribute at connector (pero)
add | StoreConfig: Save new dymanic properties from ReplicationTransmitter (pero)
fix | 33463: Remove attributes after context destroy. (remm)
fix | 33572: context.xml should be a redeploy resource, and add prioritization for redeploy resources. (remm)
Coyote
fix | PoolTcpEndpoint recreate ServerSocket after start,stop,start connector (pero)
update | Add some log.isXXXEnabled (pero)
add | JkMX: make log4j mbean configurable with attribute log4jEnabled (pero)
fix | When Tomcat runs on Windows and IE is uploading data to the server, the first read must be at least 8KB, otherwise upload speed is extremely low, submitted by Noel Rocher (remm)
Jasper
fix | 33223: pageContext.forward and jsp:include result in StringIndexOutOfBoundsException (luehe)
fix | 33373: Fix handling of context classloader in jspc (remm)
fix | 33538: Ignore example and tag-extension elements in TagLibraryInfoImpl. (yoavs)
fix | 33539: Better error message when an unknown element is encountered in the tag file. (yoavs)
fix | 33219: Minor JspServletWrapper code cleanup. (yoavs)
Cluster
fix | Add instance based ReplicationValve statistics to Mbean descriptor (pero)
fix | Better I18N support to cluster session and tcp classes (pero)
add | Support optional primaryIndicator at ReplicationValve to mark that request processing to existing session is at primary cluster node. Easy failover detection, when mark is not at configurable primaryIndicator attribute, submitted by Rainer Jung (pero)
update | Refactor all implementation from interface IDataSenders (pero)
add | Add some usefull attributes and operations to the all sender MBeans. (pero)
add | Add keepAlive and waitForAck handling to AsyncSocketSender and factor out a DataSender base class.(pero)
add | ReplicationTransmitter: Enable and Disable autoreconnect sender and waitForAck. (pero)
add | ReplicationTransmitter: transfer all properties to socket sender from server.xml configuration. (pero)
Webapps
fix Fix create and remove Host for Admin app. (pero)
Tomcat 5.5.7 (remm)
General
add | Add installer for mod_jk on IIS. (mturk)
add New store config module for better server.xml saving support.
Add <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener" /> to your server.xml (pero)
update | 32081: Remove the JDK requirement from the Unix scripts, submitted by Ben Souther (remm)
fix | 32953: SERVLETAPI: XSS Issues, submitted by Mark Thomas (jfarcand)
update | Update to commons-digester 1.6, JDT 3.0.1, MX4J 2.1.0, Struts 1.2.6 (remm)
Catalina
update | First integration at StoreConfig to StandardServer (pero)
fix | 32714 : Don't make the AccessLogValve final (funkman)
fix | 32694: Fix bad code to make docBase path aboslute in antiLocking method. (remm)
fix | 32713: Fix resource-env-ref handling. (remm)
fix | 31201: Improve i18n support in DefaultServlet. This was causing problems with JSP include actions and static files. (markt)
fix | Add some log.isXXXEnabled to o.a.c.core.StandardHost StandardEngine, StandardService (pero)
add | Feature addition to add Redirector and failOnError support for all Catalina Ant tasks, submitted by Gabriele Garuglieri (remm)
fix | 31198: Fix FORM and DIGEST authentication for non-ASCII usernames and passwords. (markt)
fix | Reimplement charset mapper (remm)
fix | Add logging of exception which could occur when retrieving the password in JDBCRealm (remm)
fix | 25889: Don't execute queries twice, submitted by Tom Anderson (remm)
fix | 32832: request.getSession(false) fails to return null (luehe)
fix | 28222: request.getRequestURL() in forwarded jsp/servlet returns original url rather than new url as per SRV8.4 (markt)
fix | 33157: Fix handling of the buffer length for basic authentication parsing (remm)
Coyote
fix | 32708: Better handling of bad encoding with the string cache. (remm)
fix | 32781: Fix bad initialization of the "scheme" field of the request object, which would cause getScheme to return "http" for the first request. (remm)
fix | Content length should be ignored if there is chunking (remm)
fix | Remove most deprecation problems for the AJP connector (remm)
Jasper
fix 32746: Avoid JAR locking when loading classes and improve loading performance by taking advantage of caching, submitted by Dominik Drzewiecki. (remm)
Cluster
fix | correct JvmRouteSessionIDBinderListener MBean name to <domain>:type=Listener,name=JvmRouteSessionIDBinderListener,host=<host> (pero)
add | JMX support to SimpleTcpCluster, ReplicationTransmitter and all senders (pero)
Webapps
fix | Fix the webDAV servlet so it can be used via any arbitrary mapping (eg /webdav/*) to edit the contents of a web application. (markt)
fix | 32729: Stop is optional and may fail, so it needs to be in a separate try/catch (remm)
update | Remove the remove method of the manager servlet, and use the undeploy method instead (remm)
fix | 32777: Fail if application isn't configured properly, submitted by Gabriele Garuglieri (remm)
fix | 32771: Cannot undeploy/deploy misconfigured app after tomcat startup, submitted by Gabriele Garuglieri (remm)
fix | 28867: Correct manager documentation to document correct way to reference the ROOT context. Submitted by Stephane Bailliez. (markt)
fix | 33085: Add support for setting privileged attribute of context to admin webapp. (markt)
fix | 33117: Fix Open bugs link broken on default homepage. Patch supplied by Sander Temme. (markt)
fix | Improve javadoc generation for Catalina. (remm)
Tomcat 5.5.6 (yoavs)
General
update | 32532: updated logging documentation. (yoavs)
update | 32382: Index page and packaed WAR for sample webapp. (yoavs)
fix | 32603: Updated host.xml to reflect appBase resolution. (yoavs)
Catalina
fix | Add child to the map of the parent before starting it. (remm)
fix | Decouple usage of the scheme and secure attributes from enabling SSL. (remm)
fix | 32502: memory leak in DigestAuthenticator. (yoavs)
fix | 28709: javax.servlet.http.HttpServletRequest.isRequestedSessionIdValid() returns true for an invalidated session. (luehe)
fix | 32137: Possible thread-safety issue in RealmBase. (yoavs)
Coyote
fix | 32585: Better handling for content length greater than Integer.MAX_VALUE in response. (markt)
update | Allow ApacheConfig and friends to live under an Engine. (billbarker)
update | Syncronize access to the Jk Request registration count. (billbarker)
update | Speed the MsgContext on its way to GC. (billbarker)
fix | Keep correct thread counts in Thread pool when thread ends in an exception (billbarker)
Jasper
update Updated Jasper-HowTo section on using Jikes, changed conf/web.xml JSPServlet to refer people to Jasper-HowTo so that we don't have these instructions in two places. (yoavs)
Webapps
fix 32505: Fix handling of an empty context parameter (which occurred every time the HTML manager was used to deploy a local war without specifying also a context file). (remm)
Tomcat 5.5.5 (yoavs)
General
update | 32235: Sync conf/web.xml MIME types with Apache httpd. (yoavs)
fix | 31132: Better -x/-r support for OS/400 in startup scripts. (yoavs)
update | 22679: Added misc note on accessing session ID to SSL-HowTo. (yoavs)
update | 32249: Updated logging documentation. (yoavs)
update | 32282: Modify Windows Uninstaller to only remove webapps/ROOT and webapps if user asks to remove everything. (yoavs)
fix | 32371: outdated introduction.xml page. (yoavs)
fix | 32373: outdated installation.xml page. (yoavs)
update | 32454: amended JNDI documentation for JavaMail/JavaActivationFramework usage. (yoavs)
Catalina
fix | 32130: Add safety check to FileStore#keys method. (yoavs)
update | 32276: Add developer info to Realm How-To. (yoavs)
fix | 32082: Added protected getPrincipals method to MemoryRealm for easier extension. (yoavs)
fix | 32023: CGIServlet fails to handle post message with multipart/form data. (yoavs)
fix | 32269: JNDIRealm fails with InvalidNameException to authenticate users if LDAP distinguished name (DN) contains slash or double quote character(s). (yoavs)
fix | Move processExpiresFrequency check to ManagerBase and reflect change to all subclasses (StandardManager, PersientManagerBase, DeltaManager). (pero)
update | Add DIGEST authentication support to the JDBC and DataSource realms. Supports both digested and cleartext passwords. (markt)
fix | 32429: CGIServlet calculates number of lines received on stderr incorrectly. (markt)
fix | 32431: Fix typo in code that passes data to CGI script. (markt)
fix | 32430: Class cast exception in toString() method within CGI servlet. (markt)
fix | Add some log.isXXXEnabled checks at StandardContext and HostConfig (pero)
fix | Remove the last DefaultContext artifacts (pero)
fix | 32031: using createConnector with "http" protocol (remm)
fix | Add configFile attribute in JMX descriptors (remm)
fix | Fix autodeployer handling of a war which includes a /META-INF/context.xml, so that it is correctly registered and can be reloaded correctly (remm)
fix | 32137: Use of MessageDigest should be synced in DIGEST (remm)
fix | Add info log when the autodeployer reloads a context (remm)
Coyote
update | Small HTTP/1.1 optimizations: replace usage of Strings with constant byte arrays, and simplify the code converting Strings to bytes (remm)
update | Greatly reduce the amount of recycle method calls on the buffers (remm)
fix | Add null OName check for Request unregistration in Jk, to remove exception under JDK 1.5. (billbarker)
fix | 32292: Don't send keep-alive header when the protocol can't be parsed. (billbarker)
Jasper
update | Updated JspC usage messages to include recently added configurable parameters. (yoavs)
fix | 32330: JspC changes context classloader. (yoavs)
Cluster
add | JvmRouteBinderValve/JvmRouteSessionIDBinderListener to bind cluster session after primary node failure at first calling backup node. This was an option to have session stickyness after cluster node crashed. Work only with JESSIONID cookies. (pero)
add | Better log support to DeltaManager to see detail information at debug level. (pero)
fix | Fix FarmWarDeployer based on new HostConfig deployer. (pero)
fix | FarmWarDeployer controlled WarWatcher with engine backgroundProcess call. Added processDeployFrequency attribute to Deployer server.xml element. (pero)
Webapps
update | 32019: Remove maxlength=64 restriction on env entry values in admin webapp. (yoavs)
fix | Fix various problems in realm docs, submitted by Phil Mocek. (remm)
update | Add log4j docs submitted by Allistair Crossley. (remm)
fix | 32381: Fix problem where EL expression is used as a place holder in the admin webapp. Submitted by Allistair Crossley. (billbarker)
Tomcat 5.5.4 (yoavs)
General
update | 31671: Update web.xml files to 2.4 schema where applicable. (yoavs)
update | 31912: Add PNG and CSS file types to replication filter default. (yoavs)
Catalina
fix | Add processExpiresFrequency to PersistentManagerBase and made some small JDBCStore optimizations (pero)
fix | Register JSP monitoring mbean for each servlet that declares a jsp-file in web.xml. (luehe)
fix | 31578: Update Manager configuration documentation. (yoavs)
fix | 31273: Add support for derefaliases in JNDIRealm. (markt)
fix | 31623: Better OS400 support in setclasspath.sh. (yoavs)
add | Extend background processing to most container components. (remm)
fix | Remove all MX4J related code. (remm)
fix | Update JAR list in TldConfig. (remm)
add | Register datasources with JMX. With DBCP, this is enough to provide JMX management and monitoring. It might work well with many other data sources which might not register themselves in JMX but do expose their stuff in a java bean fashion. (remm)
update | Add the ability to force session cookies to be set to the root path "/". This should not be used on large servers, otherwise tons of cookies may be sent. (remm)
fix | Workaround for client socket exceptions occurring while running a CGI, which could cause the external process to hang. (remm)
update | Optimize session cookie IDs conversion to String, since this is an unavoidable and uncacheable operation. (remm)
fix | Add explicit error message if temp dir does not exist, and remove useless calls to initDirs. (remm)
add | Add an optimized access log valve, supporting hardcoded support for the common and combined patterns, and doing a majority of its write-to-logfile operations asynchronously. (remm)
update | Register an MBean to monitor and manage the StringCache, and allow invoking the reset operation. (remm)
fix | 31677: Log warning if work dir for context can't be determined. (yoavs)
fix | 31903: Fix condition which seems to not have been properly updated after adding entry.binaryContent = null a little below, submitted by Joe Zhou. (remm)
fix | Prevent silent NPEs during StandardContext.start dealing with JMX registration of realm, submitted by Keith Wannamaker. (remm)
fix | 31592: Support other encodings for digests. (yoavs)
update | 31739: Minor realm-howto and AJP connector doc updates. (yoavs)
fix | 31753: Minor inconsistency between JDBC and DataSourceRealm#authenticate. (yoavs)
update | 31683: Minor clarifications to realm documentation. (yoavs)
Coyote
fix | Improve i18n in TCP endpoint, and add a better error message when an exception occurs in setSocketOptions. (remm)
fix | 31663: Use interval field as the delay for monitor thread. (remm)
fix | Remove bad shutdown logic for ms pool strategy. (remm)
fix | Sync with Cookie, by adding ' ' as a special char. If a special char is present, the string will be quoted. If the client doesn't support it, the String will no be quoted anyway and no IAE will be thrown. (remm)
add | Add an optional String cache for ByteChunk.toString and CharChunk.toString. The cache is unsynchronized during most of its operation, and is static after a training period. An operation is provided to allow resetting the cache. (remm)
update | String caching is enabled by default for ByteChunk. (remm)
fix | 31090: Use a URL encoded path when setting session cookies. (remm)
add | Add getAttributeName() to ProtocolHandler to get all attributes at runtime (pero)
Jasper
update Exposed compilerSourceVM and compilerTargetVM options to JspC. (yoavs)
Cluster
fix | DeltaManager and SimpleTcpReplicationManager generate double jvmRoute (pero)
add | Add some missing Getters and log.isXXXEnableds (pero)
Webapps
fix | 31707: Broken JavaScript confirmation in HTML manager. (yoavs)
fix | Remove hard-coded admin context path from admin's banner.jsp. (yoavs)
update | Major connector docs update. (remm)
fix | 31732: Fix Japanese localization of Manager's list output. (yoavs)
Tomcat 5.5.3 (yoavs)
General
fix | 30568: Incomplete setup.html documentation for launching jsvc. (yoavs)
update | Repackage naming features. (remm)
fix | Fix deployer packaging. (remm)
fix | Fix embed packaging. (remm)
Catalina
fix | Fix memory leak when Security Manager is turned on. (jfarcand)
fix | When checking status codes for error handling, only check if Response.isError() is true. This way, users may use setStatus() to set their own error status without having the error page invoked. (in which case, the user should've use sendError()) (funkman)
update | Remove Digester code for Xerces workaround. (jfarcand)
fix | Give proper permission to the balancer app when running under the security manager. (jfarcand)
fix | 30869: Make sure JAAS realm name is legal. (yoavs)
update | md5Helper, md5Encoder, and normalize are used by WebdavServlet, not DefaultServelt so move them into WebdavServlet.
fix | 31277: Clarified automatic application deployment section of Host configuration page. (yoavs)
fix | 28631: JAASRealm enhancements to support custom user and role classes use Commons-Logging. (yoavs)
fix | 31364: Missing resource in org.apache.catalina.core.LocalString.properties. (yoavs)
fix | 31362: Missing -Xdebug in catalina.bat when launching with JPDA and Security. (yoavs)
fix | 31356: Duplicates not counted in session generation. (yoavs)
fix | 30949: Make sure ApplicationDispatcher unwraps request/response even if include error occurs. (yoavs)
fix | Fixed StandardContext.getStartTime() to return actual start time/date instead of time (startupTime) it took to start context. (luehe)
update | getRequest/getResponse should return the most relevant interface, to avoid casts. (remm)
update | Add check for directory before considering something is a compressed WAR. (remm)
docs | Update the connector documentation. (remm)
fix | When parsing a context file, ignore the "path" attribute: the only place where it is acceptable is in server.xml. (remm)
fix | Digester handling fixes: always call reset in a finally block after using a digester. (remm)
update | Remove many fields from Connector, and tie the creation of the Connector to the creation of the protocol handler. (remm)
update | Remove package triggers from the classloader, which seem useless when using Java 5. (remm)
fix | Realms will now use set attribute to set themselves in their container when using JMX. (remm)
fix | Fix JMX related operations with the Connector. (remm)
fix | Fix save-to-XML for naming resources. (remm)
fix | Remove authenticator "debug" attributes from the descriptors. (remm)
update | Refactor org.apache.catalina.deploy.ContextXXX to use new super class ResourceBase. (pero)
fix | Enable Connector.findLifecycleListener that we can listen start/stop Connector events and save the listener to xml. (pero)
update | Remove Watchdog references, as it is no longer used. (yoavs)
fix | 31511: Don't call setenv.bat if not found, in *using-launcher scripts. (yoavs)
fix | 31549: Add name to WebappClassLoader's stopped message. (yoavs)
Coyote
update | Allow customized server header for Standalone. (funkman)
fix | Digester.reset now removes the error handler, the root and calls clear, to prevent any memory leak. (remm)
update | Remove useless stuff in digester. (remm)
update | In HTTP, add a utility method to convert strings to byte arrays, and output the server header directly as bytes. (remm)
add | Add a master slave thread pool based on the code from Tomcat 4.0. It is less exotic than the default one, and might fare better on some picky systems, such as Redhat 9. The two threadpools will likely be removed once we use the Java 5 API, although more investigation is needed. (remm)
fix | Fix issue with getProperty in IntrospectionUtils. (remm)
update | Remove attribute translation for SSL in the HTTP protocol handler: it will now be done in the Catalina Connector class. (remm)
fix | Fix handling of the "timeout" attribute of the HTTP protocol handler. (remm)
Jasper
fix | 31171: Wrap to avoid ClassCastException in PageContextImpl. (yoavs)
fix | 31257: Added specification of endorsed dirs if forking. Note that this is fairly useless for now in 5.5 since it uses JDT and not javac by default. (yoavs)
docs | Document new Jasper defaults, and update the production configuration. (remm)
fix | Copied XML encoding detection logic into JASPER, so we're no longer dependent on Xerces. (luehe)
fix | Fix cosmetic issue where extra CRLF would be inserted during each precompilation in web.xml. (remm)
update | Allow configuring the interval following a compilation during which a JSP will not be checked for modifications. (remm)
fix | 31465: Ensure that the compiler reads the .java file using the same encoding as that with which it was written. (markt)
fix | 31510: Null out response in JspWriterImpl#recycle to aid in JBoss memory leak. (yoavs)
Cluster
update | Added flag to the cluster (notifyListenersOnReplication) to enable/disable the notifications of attribute/context listeners upon replication of a session delta Works only with the DeltaManager (fhanik)
update | Added flag to the cluster (Cluster/Sender/ackTimeout) to set the timeout in milliseconds for a synchronous request to go through, defaults to 15000ms (fhanik)
Webapps
fix | 29485: I broke the HTML manager when adding JavaScript confirmation, fixed now ;) (yoavs)
fix | 31058: Ensure StatusTransformer escapes query string for XML. (yoavs)
update | Added contexts' start time (available from 'startTime' MBean attribute of StandardContext) to status page (luehe)
fix | 31264: the deploy task should now behave correctly. (remm)
update | Refactor the manager servlet to make calls to the deployer more robust. (remm)
fix | Use the more robust String.valueOf in the form edit action of the connector. (remm)
Tomcat 5.5.2 (yoavs)
General
fix The installer will now use the system's JRE. (remm)
Catalina
fix | Fix URL generation for classloaders on Windows, causing common/classes and shared/classes to be unusable (remm)
fix | 31110: Fix resource packaging bug for servlets (remm)
fix | Fix 5.5 regression where going through the authenticator would create a session each time. (remm)
fix | Fix classname of the connector in Embedded, and remove the socket factory. (remm)
Coyote
fix | Redo server header handling again. (remm)
update | Cleanup a little access to the headers using a local variable and use setValue for Server and Date headers. (remm)
Jasper
fix | Remove maxTagNesting and curTagNesting since they are unused. (funkman)
fix | Fix tag files handling with JDT, which were ususable, and refactor the lifecycle handling of the page loader. (remm)
Cluster
Webapps
Tomcat 5.5.1 (yoavs)
General
update | Tomcat 5.5 可通过 JDK 5.0.构建 (yoavs)
fix | 完善Windows 安装版本. (mladen, remm)
update | 移除对Jakarta regexp的依赖 . (remm)
Catalina
fix | 允许重载默认的上下文环境文件位置,类似默认的web.xml. (remm)
update | Backport if-else logic for SSI servlet from 4.1 (funkman)
fix | 移除digester 规则中的 DefaultContext元素. (remm)
fix | 修正对 ResourceLink 的处理. (remm)
fix | Modify the auto deployer to get along with contexts which are statically defined in server.xml. (remm)
fix | Externalize constant strings defining the location of deployment related resources. (remm)
fix | 31052: BeanFactory swallows root cause of exception. (yoavs)
fix | Allow using deploy Ant task with just config attribute, submitted by Michael Schuerig. (remm)
add | Added longest time an expired session had been alive to set of monitorable session manager attributes. (luehe)
add | Added average time an expired session had been alive to set of monitorable session manager attributes. (luehe)
fix | Clear a reference in the digester where a context would be referenced for more time than it needed, until the next context deployment operation. (remm)
Coyote
fix 31018: Race condition in SystemLogHandler. (yoavs)
Jasper
fix | 使用 "compiler" 参数允许指定Ant可使用的编译器. (remm)
fix | 忽略 JDT 编译器的警告. (remm)
add | 新增 compilerTargetVM 选项, "1.4" 为默认值. (yoavs)
Cluster
fix 修正新增的集群阀, 实现真正的 session 复制. (fhanik)
Webapps
update | Major documentation update with current Tomcat 5.5 changes. (remm)
update | Added JavaScript confirmation dialog to "dangerous" Manager servler links. (yoavs)
Tomcat 5.5.0 (yoavs)
General
update | 大量的更新和修正JavaDocs. (yoavs)
update | 在J2SE 5.0 (aka JDK 1.5)上设计并测试Tomcat. (everyone)
update | 绑定 Eclipse JDT (新的依赖) 允许 Tomcat 只在 JRE 上即可运行, 也就是说. JDK 不再是必需的. (remm)
update | Repackage commons-dbcp and its dependencies as a sigle smaller WAR, with renamed packages. (remm)
update | Removed dependencies on commons-digester, commons-beanutils, and commons-collections. The relevant digester functionality is now merged in tomcat-util. (remm)
Catalina
update | 移除 org.apache.catalina.Logger 的使用, 全面增加commons-logging 的使用. (remm)
update | 重构类加载器的代码来更好的处理JAR和一般资源锁定. (remm)
update | Written JMX-related code to play nicely with J2SE 5.0 built-in JMX abilities. (remm, costin)
update | Extensively profiled and optimized the server startup performance as well as the request mapping and processing pipeline. (remm)
update | The container will now always process a /META-INF/context.xml resource, unless the webapp has a specified external context file. (remm)
update | New default configuration mechanism for web applications, replacing DefaultContext. This uses a shared context file located in conf/context.xml. (remm)
update | Revamped deployer, alloying full hotdeploy (note: on Windows, this requires the anti file locking features). (remm)
update | Remove verbosity from the JNDI resources configuration, by allowing arbitrary attributes on the Resource element. (remm)
update | 更简单的 阀 接口, to allow smaller stack traces and reducing the amount of method calls. (remm)
Coyote
Jasper
update | Eclipse JDT 现在作为Jasper 默认的 Java 编译器 . 源代码依赖现在通过容器的类加载器进行载入, 编译速度提高了. (remm)
update | Jasper 的开发模式 现在对大量访问的页面提供了可接受的性能优化. 预编译 JSPs 十分高效快速. (remm)
Cluster
Webapps


Apache Tomcat 5.5 Servlet/JSP 容器 - Class Loader HOW-TO

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Class Loader HOW-TO

 Printer Friendly Version
print-friendly
version
Quick Start

程序开发员和部署员要决定在哪里放置类和资源文件以便它们可以被网络程序使用, 95%的这些决定由下面的这些条例覆盖:

  • 对于某个网络程序所特有的类和资源,把这些未包装的类和资源放置在你的网络程序档案/WEB-INF/classes目录下面，或者把包含这些类和资源的JAR文件放置在你的网络程序档案/WEB-INF/lib目录下面。
  • 对于必须被所有网络程序所共享的类和资源，把未包装的这些类和资源放置在$CATALINA_BASE/shared/classes下面，或者把包含这些类和资源的JAR文件放置在$CATALINA_BASE/shared/lib下面。
Overview

象许多服务器程序一样，Tomcat 5安装各种不同类型的类loaders(那就是，实现java.lang.ClassLoader的类)来允许容器的不同部分，以及运行在容器上的网络程序，可以访问不同贮存部分的类和资源。这个机制是用来提供Servlet Specification, 2.4版——特别是9.4 和 9.6章节里定义的功能。

In a J2SE 2 (that is, J2SE 1.2 or later) environment, class loaders are arranged in a parent-child tree. Normally, when a class loader is asked to load a particular class or resource, it delegates the request to a parent class loader first, and then looks in its own repositories only if the parent class loader(s) cannot find the requested class or resource. The model for web application class loaders differs slightly from this, as discussed below, but the main principles are the same.

当Tomcat 5启动后，它产生一组类装载器，这些类装载器被组织成如下的父子关系，父类装载器在子类装载器之上：

Bootstrap
|
System
|
Common
/ \
Catalina Shared
/ \
Webapp1 Webapp2 ...

每一个类装载器的特征，包括可被使用的类和资源的来源，在下面的章节有详细讨论。

Class Loader Definitions

如上面的图表显示，Tomcat 5在它启动时产生如下的类装载器：

  • Bootstrap - 这个类装载器包含Java虚拟器提供的基本的运行时间类，加上在System Extensions 目录( $JAVA_HOME/jre/lib/ext )里的JAR文件中所有的类。注意——有些Java虚拟器(JVMs)也许把它作为不止一个类装载器用，或者作为一个类装载器用。
  • System - 这个类装载器通常是以CLASSPATH环境变量的内容为基础来初始化的。所有的这些类既可被Tomcat内部classes使用，又可被网络程序使用。不过，标准的Tomcat 5启动脚本( $CATALINA_HOME/bin/catalina.sh or %CATALINA_HOME%\bin\catalina.bat )完全忽略了CLASSPATH环境变量自身的内容，相反从下面的贮藏室去建造系统类装载器：
    • $CATALINA_HOME/bin/bootstrap.jar - 包含用来初始化Tomcat 5服务器的main()方法，以及它所依赖的类装载器执行类。
    • $JAVA_HOME/lib/tools.jar - 包含用来把JSP页面转换成servlet类的"javac"编译器。
    • $CATALINA_HOME/bin/commons-logging-api.jar - Jakarta commons 记录应用程序界面。
    • $CATALINA_HOME/bin/commons-daemon.jar - Jakarta commons daemon API.
    • jmx.jar - JMX 1.2 执行。
  • Common - This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications. Normally, application classes should NOT be placed here. All unpacked classes and resources in $CATALINA_HOME/common/classes, as well as classes and resources in JAR files under the $CATALINA_HOME/commons/endorsed, $CATALINA_HOME/commons/i18n and $CATALINA_HOME/common/lib directories, are made visible through this class loader. By default, that includes the following:
    • commons-el.jar - Jakarta commons el, 执行Jasper使用的表达语言。
    • jasper-compiler.jar - The JSP 2.0 编译器。
    • jasper-compiler-jdt.jar - The Eclipse JDT Java compiler.
    • jasper-runtime.jar - The JSP 2.0 运行时间。
    • jsp-api.jar - The JSP 2.0 应用编程界面(API)。
    • naming-common.jar - 被Tomcat 5用来代表in-memory命名contexts的JNDI实现。
    • naming-factory.jar - 被Tomcat 5用来决定企业资源索引(EJB, connection pools)的JNDI实现。
    • naming-factory-dbcp.jar - Jakarta commons DBCP, providing a JDBC connection pool to web applications. The classes have been moved out of their default org.apache.commons package.
    • naming-java.jar - Handler for the java: namespace.
    • naming-resources.jar - The specialized JNDI naming context implementation used to represent the static resources of a web application. This is not related to the support of the J2EE ENC, and cannot be removed.
    • servlet-api.jar - The Servlet 2.4 API.
    • tomcat-i18n-**.jar - Optional JARs containing resource bundles for other languages. As default bundles are also included in each individual JAR, they can be safely removed if no internationalization of messages is needed.
  • Catalina - 这个类装载器被初始化后包含执行Tomcat 5自身必须的所有类和资源。这些类和资源完全可被网络程序使用。所有的在$CATALINA_HOME/server/classes里未包装的类和资源，以及$CATALINA_HOME/server/lib下JAR文件里的类和资源，通过这个类装载器可被使用。在默认的情况下，有下面的这些：
    • catalina.jar - Tomcat 5的执行Catalina servlet容器部分。
    • catalina-ant.jar - Some Ant tasks which can be used to manage Tomcat using the manager web application.
    • catalina-optional.jar - Some optional components of Catalina.
    • commons-modeler.jar - A model MBeans implementation used by Tomcat to expose its internal objects through JMX.
    • servlets-xxxxx.jar - 与每个内部servlet相关联的类，这些内部servlet提供一部分Tomcat的功能。它们是分离开的，这样一来，如果相应的服务不需要的话，它们就可以完全被删除，或者它们需要特别的安全管理员许可。
    • tomcat-coyote.jar - Coyote API.
    • tomcat-http11.jar - 独立的Java HTTP/1.1 连接器。
    • tomcat-ajp.jar - Classes for the Java portion of the AJP web server connector, which allows Tomcat to run behind web servers such as Apache and iPlanet iAS and iWS.
    • tomcat-util.jar - 一些Tomcat必需的Utility类。
  • Shared - 这个类装载器是放置被所有网络程序共享的类和资源的地方(除非Tomcat内部classes也需要访问它们，要是这样，你就得把它们放在Common这个类装载器)。所有的在$CATALINA_BASE/shared/classes 里未包装的类和资源，以及$CATALINA_BASE/shared/lib 下JAR文件里的类和资源，通过这个类装载器可被使用。如果多个Tomcat实例使用同样的$CATALINA_BASE环境变量运行，那么这个类装载器的储藏室就和$CATALINA_BASE有关，而不是和$CATALINA_HOME有关。
  • WebappX - 为在单个Tomcat 5实例中被部署的每一个网络程序所产生的类装载器。在你的网络程序档案/WEB-INF/classes目录里所有的未包装的类和资源，以及网络程序档案/WEB-INF/lib目录下JAR文件里的类和资源，可被这个Webapp里的程序使用，而不能其他程序使用。

As mentioned above, the web application class loader diverges from the default Java 2 delegation model (in accordance with the recommendations in the Servlet Specification, version 2.3, section 9.7.2 Web Application Classloader). When a request to load a class from the web application's WebappX class loader is processed, this class loader will look in the local repositories first, instead of delegating before looking. There are exceptions. Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in J2SE 1.4+), the J2SE 1.4 endorsed feature can be used (see the common classloader definition above). Last, any JAR containing servlet API classes will be ignored by the classloader. All other class loaders in Tomcat 5 follow the usual delegation pattern.

因此，从一个网络程序的角度来看，类和资源的装载以这样的顺序在下列贮藏室进行查找：

  • 你的JVM的Bootstrap类
  • 系统类装载器类(描述如上)
  • 你的网络程序的/WEB-INF/classes
  • 你的网络程序的/WEB-INF/lib/*.jar
  • $CATALINA_HOME/common/classes
  • $CATALINA_HOME/common/endorsed/*.jar
  • $CATALINA_HOME/common/i18n/*.jar
  • $CATALINA_HOME/common/lib/*.jar
  • $CATALINA_BASE/shared/classes
  • $CATALINA_BASE/shared/lib/*.jar
XML Parsers and J2SE 1.4

Among many other changes, the J2SE 1.4 release packages the JAXP APIs, and a version of Xerces, inside the JRE. This has impacts on applications that wish to use their own XML parser.

In previous versions of Tomcat 5, you could simply replace the XML parser in the $CATALINA_HOME/common/lib directory to change the parser used by all web applications. However, this technique will not be effective when you are running on J2SE 1.4, because the usual class loader delegation process will always choose the implementation inside the JDK in preference to this one.

JDK 1.4支持被称为"Endorsed Standards Override Mechanism" 的机制，来允许替代在JCP以外产生的APIs(例如DOM 和W3C里的SAX)。也可以使用它来更新XML语法分析式执行。更多信息，请参看 http://java.sun.com/j2se/1.4/docs/guide/standards/index.html 。

Tomcat通过在启动容器的命令行里加入系统属性设置-Djava.endorsed.dirs=$CATALINA_HOME/common/endorsed 来利用这个机制。因此，你可以取代安装在这个目录里的语法分析式，它甚至可以在JDK 1.4系统上使用。

Running under a security manager

当在一个安全管理者下面运行时，从什么地方来的类可以被装载依赖于你的政策文件的具体内容。更多信息请参看Security Manager HOW-TO。


Apache Tomcat 5.5 Servlet/JSP 容器 - 怎样配制集群/Session复制

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

怎样配制集群/Session复制

 Printer Friendly Version
print-friendly
version
快速入门

要在Tomcat 5.5容器里进行session复制，必须完成下列步骤：

  • 你的所有会话属性值必须实现java.io.Serializable
  • 把server.xml文件里的群集(Cluster)元素的注释取消(Uncomment)
  • 把server.xml文件里的Valve(ReplicationValve)元素注释取消(Uncomment)
  • 如果有多个Tomcat实例在一台机器上运行，确保每个实例的tcpListenPort属性值是不冲突的。
  • 确定 web.xml 中含有 <distributable/> 元素， 或者设置 <Context distributable="true" />
  • 确定设置好Engine元素的 jvmRoute 的属性值： <Engine name="Catalina" jvmRoute="node01" >
  • 确定所有节点拥有相同的时间， 并且通过网络时间服务(NTP)同步操作系统的时间！
  • 确定负载均衡器已经配置为黏性会话模式.

负载均衡可以有很多种方式实现，请参考负载均衡章节。

注意：记住你的会话状态是被一个cookie跟踪的，所以你的URL从外面看必须是相同的，否则一个新的session就会被产生。

注意：集群支持目前需要JDK 1.4或其后版本。

概要

要在Tomcat里实现会话session复制，下面三种方法都可以实现相同效果：

  1. 使用session 持久化, 并将 session 保存到一个共享的文件系统(持久管理器 + 文件存储)(PersistenceManager + FileStore)
  2. 使用session 持久化, 并将 session 保存到一个共享的 数据库 (持久管理器 + JDBC存储) (PersistenceManager + JDBCStore)
  3. 使用in-memory-replication，使用和Tomcat 5自带的SimpleTcpCluster(server/lib/catalina-cluster.jar)

In this release of session replication, Tomcat performs an all-to-all replication of session state. This is an algorithm that is only efficient when the clusters are small. For large clusters, the next release will support a primary-secondary session replication where the session will only be stored at one or maybe two backup servers. Currently you can use the domain worker attribute (mod_jk > 1.2.8) to build cluster partitions with the potential of very scaleable cluster solution. In order to keep the network traffic down in an all-to-all environment, you can split your cluster into smaller groups. This can be easily achieved by using different multicast addresses for the different groups. A very simple setup would look like this:

DNS 轮询
|
负载均衡器
/ \
集群1  集群2
/ \ / \
Tomcat1 Tomcat2 Tomcat3 Tomcat4

What is important to mention here, is that session replication is only the beginning of clustering. Another popular concept used to implement clusters is farming, ie, you deploy your apps only to one server, and the cluster will distribute the deployments across the entire cluster. This is all capabilities that can go into with the FarmWarDeployer (s. cluster example at server.xml)

下一章将深入讨论session复制是怎样实现的，以及怎样配置它。

它是怎样工作的

为了便于理解集群是怎样工作的,我们将用一系列的场景来描述. 在这个场景中，我们只计划使用两个tomcat 实例 TomcatA 和 TomcatB. 我们将覆盖下面连续的事件:

  1. TomcatA 启动
  2. TomcatB 启动 (等待TomcatA 启动完成)
  3. TomcatA 接受一个请求，session S1 被产生。
  4. TomcatA 崩溃停止
  5. TomcatB 接受一个session S1的请求
  6. TomcatA 启动
  7. TomcatA 接受一个请求，session ( S1 )失效。
  8. TomcatB 接受一个新的session ( S2 )的请求。
  9. TomcatA 因为没有活动session S2过期失效。

好了, 现在我们有了一个很好的顺序,我们将告诉你在session复制代码里发生的所有事情

  1. TomcatA 启动

    Tomcat 标准方式启动. 当 Host 对象被创建之后, 一个 cluster 对象与它关联. 当上下文被解析完, 如果 web.xml中有distributable元素， Tomcat 通过 Cluster class (in this case SimpleTcpCluster)为支持复制的上下文创建一个管理器. 因此通过设置web.xml中的distributable来启用集群。 Tomcat 将为上下文创建 DeltaManager莱取代 StandardManager. cluster class 将启动 a membership service (multicast) 和 a replication service (tcp unicast). More on the architecture further down in this document.

  2. TomcatB 启动

    当TomcatB启动时，除了一个例外以外，它按照TomcatA一样的顺序启动。群集被启用，并将建立一组会员(TomcatA,TomcatB)。TomcatB现在将要request已经存在于群集里的服务器的会话状态，在这里这个服务器是TomcatA。TomcatA回应TomcatB的请求，并且在TomcatB开始为HTTP requests监听之前，这个状态已经由TomcatA传递给TomcatB了。在TomcatA不回应的情况下，TomcatB在60秒后中断，并发出一个日志记录。对于每个已经分布在web.xml里的web应用程序，会话状态会被转移。注意：要有效地使用会话复制，你的所有tomcat实例要配置成一样的。

  3. TomcatA 接受一个请求，session S1 被产生。

    TomcatA对待传递来的请求与对待没有会话复制一样。当请求完成以后，活动就开始了，ReplicationValve在回应被返回到用户那里之前会截断这个请求。在这时，它发现会话被修改过，它就用TCP把这个会话复制给TomcatB。一旦这个分段的数据被递交给操作系统TCP logic，请求就通过valve pipeline返回给用户。对于每个请求，整个会话都被复制，这允许在不调用setAttribute 或 removeAttribute情况下，在会话中修改属性的代码被复制。配置参数useDirtyFlag可以被用来优化会话复制的次数。

  4. TomcatA 崩溃停止

    当TomcatA崩溃时，TomcatB会收到通知说TomcatA已经退出群集。TomcatB把TomcatA从它的会员列单中删除掉，TomcatB里有任何更改也不会再通知TomcatA。装载均衡器会把对TomcatA的请求引向TomcatB以及所有当前活动会话。

  5. TomcatB 接受一个session S1的请求

    TomcatB像处理其他任何请求一样处理这个请求。

  6. TomcatA 启动

    TomcatA启动时，在它接受新的请求以及让它自己可被使用之前，它要按照上面 1) 2)中所描述的顺序进行启动。它会加入群集，与TomcatB联系，了解所有会话的当前状态。一旦它接受到会话状态，它就完成装载并打开它的HTTP/mod_jk ports。所以在TomcatA接受到来自TomcatB的会话状态之前，不会对它发出请求。

  7. TomcatA 接受一个请求，session ( S1 )失效。

    失效的呼叫被拦截，这个会话就加入到失效的会话行列。在这个请求完成以后，它向TomcatB发出一个"expire"信息，TomcatB也把这个会话变为失效。

  8. TomcatB 接受一个新的session ( S2 )的请求。

    与步骤3)情形一样。

  9. TomcatA 因为没有活动session S2过期失效。

    就如一个会话由用户让它无效一样，invalidate呼叫被拦截到，这个会话就加入失效的会话行列。这一点上，除非另一个请求通过系统来检查失效行列，会话失效不会在其他地方重复。

Phuuuhh! :)

Membership Clustering membership可以通过使用非常简单的multicast pings被建立。每个Tomcat实例定期会发出multicast ping，在ping message里，这个实例会散布它的IP 及 TCP 监听端口以用于复制。如果一个实例在所给的时间范围内还没有收到这样的ping，这个会员就被认为是不存在了。很简单，也很有效。当然，你需要在你的系统上让multicasting可被使用。

TCP Replication，在收到一个multicast ping以后，会员就被添加到群集里。在下一个复制请求时，发出请求的实例将使用host和port信息来建立一个TCP socket。通过使用这个socket，它把分段的数据发送过去。我选择TCP sockets 的原因是它具备有流量控制，并确保发送到位。因此，我知道，当我发送数据时，这个数据就会被送到。

Distributed locking and pages using frames： Tomcat 并没有让会话实例在群集之间保持一致。这个逻辑的实现需要太大空间，也会带来很多问题。如果你的客户使用多个请求同时访问同一个会话，那么最后一个请求会覆盖群集里的其它会话。

Cluster Architecture

组件层次：

         Server
           |
         Service
           |
         Engine
           |  \
           |  --- Cluster --*
           |
         Host
           |
         ------
        /      \
     Cluster    Context(1-N)
        |             \
        |             -- Manager
        |                   \
        |                   -- DeltaManager
        |
     -----------------------------
     |          |         |       \
   Receiver    Sender   Membership  \
     \                               -- Valve
     -- SocketReplicationListener    |      \
     -- ReplicationListener          |       -- ReplicationValve
                                     |       -- JvmRouteBinderValve
                                     |
                                     -- LifecycleListener
                                     |
                                     -- ClusterListener
                                     |      \
                                     |       -- ClusterSessionListener
                                     |       -- JvmRouteSessionIDBinderListener
                                     |
                                     -- Deployer
                                            \
                                             -- FarmWarDeployer

   Sender
    \
    -- ReplicationTransmitter
             |
             ---------
                      \
                   IDataSender
                          \
                          |
                          --- (sync)
                          |  \
                          |   -- PooledSocketSender   (pooled)
                          |   -- SockerSender         (synchronous)
                          |
                          --- (async)
                             \
                              -- AsyncSocketSender     (asynchronous)
                              -- FastAsyncSocketSender (fastasyncqueue)

Cluster Configuration

群集配置在样品server.xml 文件里有描述。需要指出的是以mcastXXX开头的是关于会员成分multicast ping的属性，以tcpXXX开头的是关于TCP replication的属性。

会员成分是通过在相同的multicast IP 和 port上的所有tomcat实例建立的。TCP listen port是从其他会员那里来的会话复制在这它里被接收到的端口。

复制阀被用来发现请求什么时候被完成，并启动复制。

One of the most important performance considerations is the synchronous (pooled or not pooled) versus asynchronous replication mode. In a synchronous replication mode the request doesn't return until the replicated session has been sent over the wire and reinstantiated on all the other cluster nodes. There are two settings for synchronous replication. Pooled or not pooled. Not pooled (ie replicationMode="fastasnycqueue" or "synchronous") means that all the replication request are sent over a single socket. Using synchronous mode can potentially becomes a bottleneck when a lot of messages generated, You can overcome this bottleneck by setting replicationMode="pooled" but then you worker threads blocks with replication . What is recommended here is to increase the number of threads that handle incoming replication request. This is the tcpThreadCount property in the cluster section of server.xml. The pooled setting means that we are using multiple sockets, hence increases the performance. Asynchronous replication, should be used if you have sticky sessions until fail over, then your replicated data is not time crucial, but the request time is, at this time leave the tcpThreadCount to be number-of-nodes-1. During async replication, the request is returned before the data has been replicated. async replication yields shorter request times, and synchronous replication guarantees the session to be replicated before the request returns.

The parameter "replicationMode" has four different settings: "pooled", "synchronous", "asynchronous" and "fastasyncqueue"

Simple Cluster Configuration

Simple one line configuration

   <Server                 port="8011"
                       shutdown="SHUTDOWN" >
    <GlobalNamingResources>
    <Resource              name="UserDatabase" auth="Container"
                           type="org.apache.catalina.UserDatabase"
                    description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
    <Service              name="Catalina">
        <Connector        port="9012"
                      protocol="AJP/1.3"
        <Connector         port="9013"
                     maxThreads="100"
                minSpareThreads="4"
                maxSpareThreads="4"
        />
        <Engine            name="Catalina"
                   defaultHost="localhost"
                        jvmRoute="node01">
        <Realm        className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase" />
            <Host          name="localhost"
                        appBase="webapps">
             <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"/>
            </Host>
        </Engine>
    </Service>
</Server>

The default mode configuration setup a fastasyncqueue mode cluster configuration with following parameters:
  • Open Membership receiver at 228.0.0.4 and send to multicast udp port 8012
  • Send membership every 1 sec and drop member after 30sec.
  • Open message receiver at default ip interface at first free port between 8015 and 8019.
  • Receiver message with SocketReplicationListener
  • Configure a ReplicationTransmitter with fastasyncqueue sender mode.
  • Add ClusterSessionListener and ReplicationValve.

NOTE: Use this configuration when you need very quick a test cluster with at your developer machine. You can change the default attributes from cluster sub elements. Use following cluster attribute prefixes sender., receiver., service., manager., valve. and listener..
Example configure cluster at windows laptop with network connection and change receiver port range

<Cluster                 className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
          service.mcastBindAddress="127.0.0.1"
            receiver.tcpListenPort="9070"
         receiver.tcpListenMaxPort="9075" />

WARNING: When you add you sub elements, there overwrite the defaults complete.
Example configure cluster with cluster failover jsessionid support. In this case you need also the defaultmode Cluster listener ClusterSessionListener and ReplicationValve.
<Cluster                 className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
          service.mcastBindAddress="127.0.0.1"
            receiver.tcpListenPort="9070"
         receiver.tcpListenMaxPort="9075" >
       <ClusterListener  className="org.apache.catalina.cluster.session.ClusterSessionListener" />
       <ClusterListener  className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" />
       <Valve            className="org.apache.catalina.cluster.tcp.ReplicationValve"
                            filter=".*\.gif;.*\.js;.*\.css;.*\.png;.*\.jpeg;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"
                  primaryIndicator="true" />
       <Valve            className="org.apache.catalina.cluster.session.JvmRouteBinderValve"
                          enabled="true"  />
<Cluster/>

Simple Engine Cluster Configuration for all hosts

Simple one line engine configuration

   <Server                 port="8011"
                       shutdown="SHUTDOWN" >
    <GlobalNamingResources>
    <Resource              name="UserDatabase" auth="Container"
                           type="org.apache.catalina.UserDatabase"
                    description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
    <Service              name="Catalina">
        <Connector        port="9012"
                      protocol="AJP/1.3"
        <Connector         port="9013"
                     maxThreads="100"
                minSpareThreads="4"
                maxSpareThreads="4"
        />
        <Engine            name="Catalina"
                   defaultHost="localhost"
                        jvmRoute="node01">
        <Realm        className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase" />
        <Cluster      className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"/>
            <Host          name="localhost"
                        appBase="webapps"/>
        </Engine>
    </Service>
</Server>

See default mode configuration description as simple host cluster example before.

Complex Cluster Configuration

Example Configure cluster with complete sub elements. Activate this node as master farm delopyer. Message receiver is NIO based ReplicationListener with six parallel worker threads.

       <Server                 port="8011"
                       shutdown="SHUTDOWN" >
    <GlobalNamingResources>
    <Resource              name="UserDatabase" auth="Container"
                           type="org.apache.catalina.UserDatabase"
                    description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
    <Service              name="Catalina">
        <Connector        port="9012"
                      protocol="AJP/1.3"
        <Connector         port="9013"
                     maxThreads="100"
                minSpareThreads="4"
                maxSpareThreads="4"
        />
        <Engine            name="Catalina"
                   defaultHost="localhost"
                        jvmRoute="node01">
        <Realm        className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase" />
            <Host          name="localhost"
                        appBase="webapps">
                <Cluster                  className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
                                       doClusterLog="true"
                                     clusterLogName="clusterlog"
                                  manager.className="org.apache.catalina.cluster.session.DeltaManager"
                   manager.expireSessionsOnShutdown="false"
               manager.notifyListenersOnReplication="false"
        manager.notifySessionListenersOnReplication="false"
                            manager.sendAllSessions="false"
                        manager.sendAllSessionsSize="500"
                    manager.sendAllSessionsWaitTime="20">
                  <Membership
                                          className="org.apache.catalina.cluster.mcast.McastService"
                                          mcastAddr="228.0.0.4"
                                   mcastBindAddress="127.0.0.1"
                                 mcastClusterDomain="d10"
                                          mcastPort="45564"
                                     mcastFrequency="1000"
                                      mcastDropTime="30000"/>
                  <Receiver
                                           className="org.apache.catalina.cluster.tcp.ReplicationListener"
                                    tcpListenAddress="auto"
                                       tcpListenPort="9015"
                                  tcpSelectorTimeout="100"
                                      tcpThreadCount="6"
                  <Sender
                                           className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
                                     replicationMode="fastasyncqueue"
                                      recoverTimeout="5000"
                                      recoverCounter="6"
                        doTransmitterProcessingStats="true"
                                   doProcessingStats="true"
                                      doWaitAckStats="true"
                                       queueTimeWait="true"
                                        queueDoStats="true"
                                      queueCheckLock="true"
                                          ackTimeout="15000"
                                          waitForAck="true"
                                    keepAliveTimeout="80000"
                            keepAliveMaxRequestCount="-1"/>
                  <Valve                   className="org.apache.catalina.cluster.tcp.ReplicationValve"
                                              filter=".*\.gif;.*\.js;.*\.css;.*\.png;.*\.jpeg;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"
                                    primaryIndicator="true" />
                  <Valve                    className="org.apache.catalina.cluster.session.JvmRouteBinderValve"
                                             enabled="true" />
                  <ClusterListener         className="org.apache.catalina.cluster.session.ClusterSessionListener" />
                  <ClusterListener         className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" />
                  <Deployer                className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
                                            tempDir="${catalina.base}/war-temp"
                                          deployDir="${catalina.base}/war-deploy/"
                                           watchDir="${catalina.base}/war-listen/"
                                       watchEnabled="true"/>
                  </Cluster>
            </Host>
        </Engine>
    </Service>
</Server>

Cluster Configuration for ReplicationTransmitter

List of Attributes
属性 | 描述 | Default value
replicationMode | replication mode (synchronous, pooled, asynchronous or fastasyncqueue) | pooled
processSenderFrequency | Control the sender keepalive status and drop sender socket connection after timeout is reached. Check every processSenderFrequency value engine background ticks. | 2
compress | compress bytes before sending (consume memory, but reduce network traffic - GZIP) | false
ackTimeout | acknowledge timeout and only usefull it waitForAck is true | 15000 msec
waitForAck | Wait for ack after data send | false
autoConnect | is sender disabled, fork a new socket | false
doTransmitterProcessingStats | create processing time stats | false

Example to get statistic information, wait for ack at every message send and transfer at compressed mode

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="fastasyncqueue"
      compress="true"
      doTransmitterProcessingStats="true"
      ackTimeout="15000"
      waitForAck="true"
      autoConnect="false"/>

Cluster Configuration for ReplicationTransmitter (fastayncqueue - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
doProcessingStats | create Processing time stats | false
doWaitAckStats | create waitAck time stats | false
resend | resend message after failure, can overwrite at message | false
recoverTimeout | recover Timeout after push message failure | 5000 msec
recoverCounter | number of recover tries | 0
queueDoStats | activated queue stats | false
queueCheckLock | check to lost locks | false
queueAddWaitTimeout | queue add wait time (tomcat connector thread waits) | 10000 msec
queueRemoveWaitTimeout | queue remove wait time (queue thread waits) | 30000 msec
maxQueueLength | max queue length (default without limit) | -1
threadPriority | change queue thread priority (1-10 ; 5 is normal) | 5

Example to get a lot of statistic information, wait for ACK and recover after connection failure (wait 5 secs and 6 trails (==30 secs Mcast Timeout)

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="fastasyncqueue"
      recoverTimeout="5000"
      recoverCounter="6"
      doTransmitterProcessingStats="true"
      doProcessingStats="true"
      queueTimeWait="true"
      queueDoStats="true"
      queueCheckLock="true"
      waitForAck="true"
      autoConnect="false"
      keepAliveTimeout="320000"
      keepAliveMaxRequestCount="-1"/>

Cluster Configuration for ReplicationTransmitter ( asynchronous - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
doProcessingStats | create Processing time stats | false
doWaitAckStats | create waitAck time stats | false
resend | resend message after failure, can overwrite at message | false

Example to get a processing statistic information, resend after failure and wait for ACK

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="asynchronous"
      doProcessingStats="true"
      doWaitAckStats="true"
      waitForAck="true"
      ackTimeout="30000"
      resend="true"
      keepAliveTimeout="320000"
      keepAliveMaxRequestCount="-1"/>

Cluster Configuration for ReplicationTransmitter ( synchronous - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
doProcessingStats | create Processing time stats | false
doWaitAckStats | create waitAck time stats | true
resend | resend message after failure, can overwrite at message | false

Example to get a no processing statistic information, no wait for ACK, after 10000 request renew socket and autoconnect before first request is send.

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="synchronous"
      autoConnect="true"
      keepAliveTimeout="-1"
      keepAliveMaxRequestCount="100000"/>

Cluster Configuration for ReplicationTransmitter ( pooled - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
maxPoolSocketLimit | max pooled sockets (Sender Sockets) | 25
resend | resend message after failure, can overwrite at message | false

Example to get a no processing statistic information, wait for ACK, after 10000 request renew socket, only 10 SockerSender available and autoconnect before first request is send.

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="pooled"
      autoConnect="true"
      maxPoolSocketLimit="10"
      keepAliveTimeout="-1"
      keepAliveMaxRequestCount="10000"
      waitForAck="true" />

Cluster Configuration for ReplicationTransmitter ( DeltaManager Attribute)

List of Attributes
属性 | 描述 | Default value
expireSessionsOnShutdown | When server stopped, expire all sessions also at backup nodes (only for testing) | false
maxActiveSessions | Number of active sessions. (Default is no limit) | -1
notifyListenersOnReplication | Notify application session listener to session creation and expiring events at backup nodes | true
notifySessionListenersOnReplication | Notify application session listener to attribute changes at backup nodes | true
stateTransferTimeout | Timeout that session state transfer is complete. Is attribute stateTransferTimeout == -1 then application wait that other node send the complete session state | 60 sec
sendAllSessions | Flag to send sessions as splited blocks | true
sendAllSessionsSize | Number of serialize sessions inside a send block session message. Only useful when sendAllSessions==false | 1000
sendAllSessionsWaitTime | wait time between two session send blocks. | 2000 msec
sendClusterDomainOnly | Send all session messages only to member inside same cluster domain (value od Membership attribute mcastClusterDomain). Also don't handle session messages from other domains. | true
stateTimestampDrop | DeltaManager queued Sessions messages when send GET_ALL_SESSION to other node. with stateTimestampDrop all messages before state transfer message creation date (find session) are dropped. Only other GET_ALL_SESSION events are handle with date before state transfer message. | true

Example send all sessions at separate blocks. Serialize and send 100 session inside one block. Wait maximale two minutes before the complete backup sessions are loaded inside tomcat boot process. Between send blocks wait 5 secs to transfers the session block to other node. This save memory when you use the async modes with queues.

    <Cluster className="org.apache.catalina.tcp.SimpleTcpCluster"
      managerClassName="org.apache.catalina.cluster.session.DeltaManager"
      manager.stateTransferTimeout="120"
      manager.sendAllSessions="false"
      manager.sendAllSessionsSize="100"
      manager.sendAllSessionsWaitTime="5000"
      "/>

注意
As Cluster.defaultMode=true you can configure the manager attributes with prefix manager..
注意
With Cluster.setProperty(<String>,<String>) you can modify attributes for all register managers. The method exists as MBeans operation.

Bind session after crash to failover node

As you configure more then two nodes at same cluster for backup, most loadbalancer send don't all your requests after failover to the same node.

The JvmRouteBinderValve handle tomcat jvmRoute takeover using mod_jk module after node failure. After a node crashed the next request going to other cluster node. The JvmRouteBinderValve now detect the takeover and rewrite the jsessionid information to the backup cluster node. After the next response all client request goes direct to the backup node. The change sessionid send also to all other cluster nodes. Well, now the session stickyness work directly to the backup node, but traffic don't go back too restarted cluster nodes!
As jsessionid was created by cookie, the change JSESSIONID cookie resend with next response.

You must add JvmRouteBinderValve and the corresponding cluster message listener JvmRouteSessionIDBinderListener. As you add the new listener you must also add the default ClusterSessionListener that receiver the normal cluster messages.

<Cluster className="org.apache.catalina.tcp.SimpleTcpCluster" >
...
     <Valve className="org.apache.catalina.cluster.session.JvmRouteBinderValve"
               enabled="true" sessionIdAttribute="takeoverSessionid"/>
     <ClusterListener className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" />
     <ClusterListener className="org.apache.catalina.cluster.session.ClusterSessionListener" />
...
<Cluster>

Hint:
With attribute sessionIdAttribute you can change the request attribute name that included the old session id. Default attribuite name is org.apache.catalina.cluster.session.JvmRouteOrignalSessionID.

Trick:
You can enable this mod_jk turnover mode via JMX before you drop a node to all backup nodes! Set enable true on all JvmRouteBinderValve backups, disable worker at mod_jk and then drop node and restart it! Then enable mod_jk Worker and disable JvmRouteBinderValves again. This use case means that only requested session are migrated.

通过 JMX 监控集群

Monitoring is a very important question when you use a cluster. Some of the cluster objects are JMX MBeans

Add the following parameter to your startup script with Java 5:

set CATALINA_OPTS=\
-Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=%my.jmx.port% \
-Dcom.sun.management.jmxremote.ssl=false \
-Dcom.sun.management.jmxremote.authenticate=false

在 JDK 1.4中启用JMX:

  1. 安装 compat 包
  2. 安装 mx4j-tools.jar 到 common/lib (使用与tomcat发布版相同的mx4j版本)
  3. Configure a MX4J JMX HTTP Adaptor at your AJP Connector

    <Connector port="${AJP.PORT}"
   handler.list="mx"
   mx.enabled="true"
   mx.httpHost="${JMX.HOST}"
   mx.httpPort="${JMX.PORT}"
   protocol="AJP/1.3" />
  4. 启动Tomcat,然后再浏览器中访问 http://${JMX.HOST}:${JMX.PORT}
  5. 通过连接参数 mx.authMode="basic" mx.authUser="tomcat" mx.authPassword="strange"可以控制访问权限!

集群 Mbeans 列表
name(名称) | 描述 | MBean ObjectName - Engine | MBean ObjectName - Host
集群 | The complete cluster element | type=Cluster | type=Cluster,host=${HOST}
ClusterSender | Configuration and stats of the sender infrastructure | type=ClusterSender | type=ClusterSender,host=${HOST}
ClusterReceiver | Configuration and stats of the recevier infrastructure | type=ClusterReceiver | type=ClusterReceiver,host=${HOST}
ClusterMembership | Configuration and stats of the membership infrastructure | type=ClusterMembership | type=ClusterMembership,host=${HOST}
IDataSender For every cluster member it exist a sender mbeans. It exists speziall MBeans to all replication modes
type=IDataSender,
        senderAddress=${MEMBER.SENDER.IP},
        senderPort=${MEMBER.SENDER.PORT}

type=IDataSender,host=${HOST},
        senderAddress=${MEMBER.SENDER.IP},
        senderPort=${MEMBER.SENDER.PORT}
DeltaManager | This manager control the sessions and handle session replication | type=Manager,path=${APP.CONTEXT.PATH}, host=${HOST} | type=Manager,path=${APP.CONTEXT.PATH}, host=${HOST}
ReplicationValve | This valve control the replication to the backup nodes | type=Valve,name=ReplicationValve | type=Valve,name=ReplicationValve,host=${HOST}
JvmRouteBinderValve | This is a cluster fallback valve to change the Session ID to the current tomcat jvmroute. | type=Valve,name=JvmRouteBinderValve, path=${APP.CONTEXT.PATH} | type=Valve,name=JvmRouteBinderValve,host=${HOST}, path=${APP.CONTEXT.PATH}

常见问题

请参考 集群常见问题.


Apache Tomcat 5.5 Servlet/JSP 容器 - 配置连接

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

配置连接

 Printer Friendly Version
print-friendly
version
简介

Choosing a connector to use with Tomcat can be difficult. This page will list the connectors which are supported with this Tomcat release, and will hopefully help you make the right choice according to your needs.

HTTP

HTTP connector 是Tomcat默认设置的 , 可直接使用. This connector features the lowest latency and best overall performance.

为支持集群, a HTTP load balancer with support for web sessions stickiness must be installed to direct the traffic to the Tomcat servers. Tomcat 支持 mod_proxy (在 Apache HTTP Server 2.x 版本中可用, Apache HTTP Server 2.2 默认自带) 作为负载均衡器. It should be noted that the performance of HTTP proxying is usually lower than the performance of AJP, so AJP clustering is often preferable.

AJP

When using a single server, the performance when using a native webserver in front of the Tomcat instance is most of the time significantly worse than a standalone Tomcat with its default HTTP connector, even if a large part of the web application is made of static files. If integration with the native webserver is needed for any reason, an AJP connector will provide faster performance than proxied HTTP. AJP clustering is the most efficient from the Tomcat perspective. It is otherwise functionally equivalent to HTTP clustering.

支持Tomcat发行版的本地AJP连接器有:

  • JK 1.2.x 及其所支持的服务器
  • Apache HTTP Server 2.x 上的 mod_proxy (Apache HTTP Server 2.2 默认自带),并启用AJP支持

其它支持AJP的本地连接可能仍然能正常工作，但是不再被提供支持。


Apache Tomcat 5.5 Servlet/JSP 容器 - 默认 Servlet 参考手册

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

默认 Servlet 参考手册

 Printer Friendly Version
print-friendly
version
简介
这里讨论不同的操纵默认servlet的方法。讨论的话题有：
  • 什么是DefaultServlet?
  • 它在什么地方被声明的？
  • 我能做什么样的改变？
  • 我怎样定制目录列表？
  • 我怎样保护目录列表的安全性？
什么是DefaultServlet
默认的servlet是既服务于静态资源又服务于目录列表(如果允许目录列表的话)的servlet。
它在什么地方被声明的？
它在$CATALINA_HOME/conf/web.xml中被全局声明。默认形式的声明是这样的： $CATALINA_HOME/conf/web.xml
&lt;servlet&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;servlet-class&gt;
org.apache.catalina.servlets.DefaultServlet
&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;debug&lt;/param-name&gt;
&lt;param-value&gt;0&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;listings&lt;/param-name&gt;
&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

...

&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
因此在默认的情况下，默认servlet在webapp启动时被装载，目录列表可被使用，日志调试功能被关掉。 （翻译者备注：在Tomcat 5.5.13之后的版本，已经将listings默认设置为false,默认是禁止目录列表了 参见 http://issues.apache.org/bugzilla/show_bug.cgi?id=37150）
我能做什么样的改变？
DefaultServlet允许以下初始化参数：
debug | 日志级别。如果你不是tomcat开发人员，这对你没有什么用处。目前，有用的值是0, 1, 11, 1000。
listings 如果没有欢迎文件，要不要显示目录列表？值可以是true 或 false。
欢迎文件是servlet api的一部分。
警告:列表显示包含太多记录的目录是非常消耗服务性能的 . 大量请求访问大目录列表会吃掉服务器大部分的资源.
readmeFile | 如果允许目录列表，可能有一个readme文件和这个列表在一起。这个文件包含HTML被插入。默认值是null。
globalXsltFile | 如果你希望定制你的目录列表显示效果，你可以使用一个XSL转换(transformation)。这个值是一个可用于所有目录列表的绝对路径文件名。它可以被每个webapp 重新自定义使用，或者通过在你局部webapp的web.xml文件里声明默认servlet取消使用。这个xml文件的格式在下面有显示。
localXsltFile | 你还可以在每个目录通过配置localXsltFile定制你的目录列表。它应该是在产生列表的目录里的一个相对路径文件名。它覆盖globalXsltFile。如果这个值存在，但是文件不存在，那么就使用globalXsltFile。如果globalXsltFile也不存在，那么默认的目录列表就会被显示出来。
input | 在读取用于服务的资源时的输入缓冲容量(in bytes)。[2048]
output | 在读取用于服务的资源时的输出缓冲容量(in bytes)。[2048]
readonly | 这个上下文否"read only"，因此如PUT 和 DELETE的HTTP命令将被拒绝执行？ [true]
fileEncoding | 文件编码用于读取静态资源时. [平台默认值]
sendfileSize | 如果连接器支持 sendfile, 这个参数表示sendfile将用到的最小文件大小（以KB为单位） . 使用负数 可以禁止使用sendfile. [48]
我怎样定制目录列表？

你可以用你自己的实现(implementation)来覆盖DefaultServlet，并在你的web.xml声明里使用它。如果你能理解刚刚所讲的，我们假设你可以阅读DefaultServlet servlet的代码，并能做适当的调整(如果不行，这个方法对你不适用)。

你可以使用localXsltFile或globalXsltFile，DefaultServlet将会产生一个xml文件，并通过一个基于localXsltFile和globalXsltFile所提供的xsl转换来执行。首先检查localXsltFile，然后是globalXsltFile，再后是默认行为。

格式

&lt;listing&gt;
&lt;entries&gt;
&lt;entry type='file|dir' urlPath='aPath' size='###' date='gmt date'&gt;
fileName1
&lt;/entry&gt;
&lt;entry type='file|dir' urlPath='aPath' size='###' date='gmt date'&gt;
fileName2
&lt;/entry&gt;
...
&lt;/entries&gt;
&lt;readme&gt;&lt;/readme&gt;
&lt;/listing&gt;
  • 如果 type='dir' ，size将不存在
  • Readme是一个CDATA输入

下面的是一个xsl文件示例，它模拟默认的tomcat行为：
&lt;?xml version="1.0"?&gt;

&lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"&gt;

&lt;xsl:output method="xhtml" encoding="iso-8859-1" indent="no"/&gt;

&lt;xsl:template match="listing"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;
Sample Directory Listing For
&lt;xsl:value-of select="@directory"/&gt;
&lt;/title&gt;
&lt;style&gt;
h1{color : white;background-color : #0086b2;}
h3{color : white;background-color : #0086b2;}
body{font-family : sans-serif,Arial,Tahoma;
color : black;background-color : white;}
b{color : white;background-color : #0086b2;}
a{color : black;} HR{color : #0086b2;}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Sample Directory Listing For
&lt;xsl:value-of select="@directory"/&gt;
&lt;/h1&gt;
&lt;hr size="1" /&gt;
&lt;table cellspacing="0"
width="100%"
cellpadding="5"
align="center"&gt;
&lt;tr&gt;
&lt;th align="left"&gt;Filename&lt;/th&gt;
&lt;th align="center"&gt;Size&lt;/th&gt;
&lt;th align="right"&gt;Last Modified&lt;/th&gt;
&lt;/tr&gt;
&lt;xsl:apply-templates select="entries"/&gt;
&lt;/table&gt;
&lt;xsl:apply-templates select="readme"/&gt;
&lt;hr size="1" /&gt;
&lt;h3&gt;Apache Tomcat/5.0&lt;/h3&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="entries"&gt;
&lt;xsl:apply-templates select="entry"/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="readme"&gt;
&lt;hr size="1" /&gt;
&lt;pre&gt;&lt;xsl:apply-templates/&gt;&lt;/pre&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="entry"&gt;
&lt;tr&gt;
&lt;td align="left"&gt;
&lt;xsl:variable name="urlPath" select="@urlPath"/&gt;
&lt;a href="{$urlPath}"&gt;
&lt;tt&gt;&lt;xsl:apply-templates/&gt;&lt;/tt&gt;
&lt;/a&gt;
&lt;/td&gt;
&lt;td align="right"&gt;
&lt;tt&gt;&lt;xsl:value-of select="@size"/&gt;&lt;/tt&gt;
&lt;/td&gt;
&lt;td align="right"&gt;
&lt;tt&gt;&lt;xsl:value-of select="@date"/&gt;&lt;/tt&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;
我怎样保护目录列表的安全性？
在每一个webapp里使用web.xml 。参看Servlet 规范中关于安全的相关章节。


Apache Tomcat 5.5 Servlet/JSP 容器 - Tomcat Web Application Deployment

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Tomcat Web Application Deployment

 Printer Friendly Version
print-friendly
version
Table of Contents
  • 简介
  • 安 装
  • A word on Contexts
  • Deployment on Tomcat startup
  • 在运行的Tomcat服务器上部署（Deploying on a running Tomcat server ）
  • Deploying using the Tomcat Manager
  • Deploying using the Tomcat Client Deployer
Introduction

Deployment is the term used for the process of installing a web application (either a 3rd party WAR or your own custom web application) into the Tomcat server.

Web application deployment may be accomplished in a number of ways within the Tomcat server.

  • Statically; the web application is setup before Tomcat is started
  • Dynamically; in conjunction with the Tomcat Manager web application or manipulating already deployed web applications

The Tomcat Manager is a tool that allows URL-based web application deployment features. There is also a tool called the Client Deployer, which is a command shell based script that interacts with the Tomcat Manager but provides additional functionality such as compiling and validating web applications as well as packaging web application into web application resource (WAR) files.

Installation

There is no installation required for static deployment of web applications as this is provided out of the box by Tomcat. Nor is any installation required for deployment functions with the Tomcat Manager, although some configuration is required as detailed in the Tomcat Manager manual. An installation is however required if you wish to use the Tomcat Client Deployer (TCD).

The TCD is not packaged with the Tomcat core distribution, and must therefore be downloaded separately from the Downloads area. The download is usually labelled jakarta-tomcat-5.5.x-deployer.

TCD has prerequisites of Apache Ant 1.6.2+ and a Java installation. Your environment should define an ANT_HOME environment value pointing to the root of your Ant installation, and a JAVA_HOME value pointing to your Java installation. Additionally, you should ensure Ant's ant command, and the Java javac compiler command run from the command shell that your operating system provides.

  1. Download the TCD distribution
  2. The TCD package need not be extracted into any existing Tomcat installation, it can be extracted to any location.
  3. Read Using the Tomcat Client Deployer
A word on Contexts

In talking about deployment of web applications, the concept of a Context is required to be understood. A Context is what Tomcat calls a web application.

In order to configure a Context within Tomcat a Context Descriptor is required. A Context Descriptor is simply an XML file that contains Tomcat related configuration for a Context, e.g naming resources or session manager configuration. In earlier versions of Tomcat the content of a Context Descriptor configuration was often stored within Tomcat's primary configuration file server.xml but this is now discouraged (although it currently still works).

Context Descriptors not only help Tomcat to know how to configure Contexts but other tools such as the Tomcat Manager and TDC often use these Context Descriptors to perform their roles properly.

The locations for Context Descriptors are;

  1. $CATALINA_HOME/conf/[enginename]/[hostname]/context.xml
  2. $CATALINA_HOME/webapps/[webappname]/META-INF/context.xml
If a Context Descriptor is not provided for a Context, Tomcat automatically creates one and places it in (1) with a filename of [webappname].xml although if manually created, the filename need not match the web application name as Tomcat is concerned only with the Context configuration contained within the Context Descriptor file(s).

Deployment on Tomcat startup

If you are not interested in using the Tomcat Manager, or TCD, then you'll need to deploy your web applications statically to Tomcat, followed by a Tomcat startup. The location you deploy web applications to for this type of deployment is called the appBase which is specified per Host. You either copy a so-called exploded web application, i.e non-compressed, to this location, or a compressed web application resource .WAR file.

The web applications present in the location specified by the Host's (default Host is "localhost") appBase attribute (default appBase is "$CATALINA_HOME/webapps") will be deployed on Tomcat startup only if the Host's deployOnStartup attribute is "true".

The following deployment sequence will occur on Tomcat startup in that case:

  1. Any Context Descriptors will be deployed first.
  2. Exploded web applications not referenced by any Context Descriptor will then be deployed. If they have an associated .WAR file in the appBase and it is newer than the exploded web application, the exploded directory will be removed and the webapp will be redeployed from the .WAR
  3. 部署WAR文件

Note again that for each deployed web application, a Context Descriptor will be created unless one exists already.

Deploying on a running Tomcat server

It is possible to deploy web applications to a running Tomcat server.

If the Host autoDeploy attribute is "true", the Host will attempt to deploy and update web applications dynamically, as needed, for example if a new .WAR is dropped into the appBase. For this to work, the Host needs to have background processing enabled which is the default configuration.

autoDeploy set to "true" and a running Tomcat allows for:

  • Deployment of .WAR files copied into the Host appBase.
  • Deployment of exploded web applications which are copied into the Host appBase.
  • Re-deployment of a web application which has already been deployed from a .WAR when the new .WAR is provided. In this case the exploded web application is removed, and the .WAR is expanded again. Note that the explosion will not occur if the Host is configured so that .WARs are not exploded with a unpackWARs attribute set to "false", in which case the web application will be simply redeployed as a compressed archive.
  • Re-deployment of a web application if the /WEB-INF/web.xml file (or any other resource defined as a WatchedResource) is updated.
  • Re-deployment of a web application if the Context Descriptor file from which the web application has been deployed is updated.
  • Re-deployment of a web application if a Context Descriptor file (with a filename corresponding to the Context path of the previously deployed web application) is added to the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory.
  • Undeployment of a web application if its document base (docBase) is deleted. Note that on Windows, this assumes that anti-locking features (see Context configuration) are enabled, otherwise it is not possible to delete the resources of a running web application.

Note that web application reloading can also be configured in the loader, in which case loaded classes will be tracked for changes.

Deploying using the Tomcat Manager

The Tomcat Manager is covered in its own manual page.

Deploying using the Client Deployer Package

Finally, deployment of web application may be achieved using the Tomcat Client Deployer. This is a package which can be used to validate, compile, compress to .WAR, and deploy web applications to production or development Tomcat servers. It should be noted that this feature uses the Tomcat Manager and as such the target Tomcat server should be running.

It is assumed the user will be familar with Apache Ant for using the TCD. Apache Ant is a scripted build tool. The TCD comes pre-packaged with a build script to use. Only a modest understanding of Apache Ant is required (installation as listed earlier in this page, and familiarity with using the operating system command shell and configuring environment variables).

The TCD includes Ant tasks, the Jasper page compiler for JSP compilation before deployment, as well as a task which validates the web application Context Descriptor. The validator task (class org.apache.catalina.ant.ValidatorTask) allows only one parameter: the base path of an exploded web application.

The TCD uses an exploded web application as input (see the list of the properties used below). A web application that is programatically deployed with the deployer may include a Context Desciptor in /META-INF/context.xml.

The TCD includes a ready-to-use Ant script, with the following targets:

  • 编译(compile)(默认default)：编译并确认网络应用程序。这个目标可以单独使用，并不需要一个运行的Tomcat服务器。因为由Jasper产生的代码依赖于它的运行组件，这个被编译过的程序只能运行在相关的Tomcat 5.0.x发行版服务器上, 不能保证能在其他发行版服务器上运行。还须注意，这个目标还会自动 编译位于 /WEB-INF/classes 文件夹里的Java 源文件。
  • 部署(deploy)：把网络程序(编译过的或未编译过的)部署到Tomcat服务器上。
  • 反部署(undeploy)：反部署网络应用程序。
  • 启动(start)： 启动一个web程序。
  • 重新装载(reload)：重新装载web应用程序。
  • 停止(stop)：停止运行web应用程序。

In order for the deployment to be configured, create a file called deployer.properties in the TCD installation directory root. In this file, add the following name=value pairs per line:

Additionally, you will need to ensure that a user has been setup for the target Tomcat Manager (which TCD uses) otherwise the TCD will not authenticate with the Tomcat Manager and the deployment will fail. To do this, see the Tomcat Manager page.

  • 构造(build)：build文件夹可以以默认的形式${build}/webapp${path}使用。当编译(compile)目标执行完之后，WAR程序就被放置在${build}/webapp${path}.war。
  • webapp: The directory containing the exploded web application which will be compiled and validated. By default, the folder is myapp.
  • 路径(path)：被部署的网络程序的上下文路径，默认名称是/myapp 。
  • url: Absolute URL to the Tomcat Manager web application of a running Tomcat server, which will be used to deploy and undeploy the web application. By default, the deployer will attempt to access a Tomcat instance running on localhost, at http://localhost:8080/manager.
  • username: Tomcat Manager username (user should have a role of manager)
  • password: Tomcat Manager password.


Apache Tomcat 5.5 Servlet/JSP 容器 - Tomcat 开发人员

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Tomcat 开发人员

 Printer Friendly Version
print-friendly
version
当前开发人员

这个列表大致罗列了最有兴趣的开发者。被列到这个列表里是免费的 :) 这些 开发者的邮件地址是[login]@apache.org。 请 不要 直接联系这些开发者询问有官方支持的版本的问题 (请将问题发送到tomcat-users 邮件列表， 或者其他的资源; 一些组织和个人顾问也提供tomcat的技术支持, 部分列表 vendors page 在Jakarta的网页上).

  • Amy Roh (amyroh): Catalina, Admin webapp
  • Bill Barker (billbarker): Connectors
  • Costin Manolache (costin): Catalina, Connectors
  • Filip Hanik (fhanik): Clustering, Release Manager
  • Glenn Nielsen (glenn): Catalina, Connectors
  • Henri Gomez (hgomez): Connectors
  • Jan Luehe (luehe): Jasper
  • Jean-Francois Arcand (jfarcand): Catalina
  • Jean-Frederic Clere (jfclere): Connectors
  • Kin-Man Chung (kinman): Jasper
  • Mark Thomas (markt): CGI, SSI, WebDAV, bug fixing
  • Mladen Turk (mturk): Connectors
  • Peter Rossbach (pero): Catalina, Clustering, JMX
  • Rainer Jung (rjung): Catalina, Clustering, Connectors
  • Remy Maucherat (remm): Catalina, Connectors, Docs
  • Tim Funk (funkman): Catalina, Docs
  • Yoav Shapira (yoavs): Docs, JMX, Catalina, balancer
曾经参与过的开发人员


Apache Tomcat 5.5 Servlet/JSP 容器 - 文件目录

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

文件目录

 Printer Friendly Version
print-friendly
version
Introduction

这里是关于Apache Jakarta Tomcat/JSP容器的文件一个顶层进入点。 Tomcat 5.5版起用 了Java Community Process 的Servlet 2.4 和 Java Server Page (JSP) 2.0 版的规范，同时又添加了许多特性。 这使它成为一个十分 有用的开发和部署，网络应用和web服务的平台

你可从（左边的）目录中选择一个链接来查询详细的内容。下面的每个链接都有更为 详细的描述。

Apache Tomcat User Guide

下面的文件帮助你下载、安装Apache Tomcat 5，以及使用Apache Tomcat 的许多特性。

  1. 简介- 关于Apache Tomcat的 简短，高层位概貌。
  2. 安装 - 怎样在一系列不同的平台上 安装和运行Apache Tomcat 。
  3. 简单网络应用- 简单 介绍Servlet 2.3 规则里制定的关于网络应用的概念。覆盖面包括基本的网络应用 的资源树，网络应用存档结构，以及网络应用部署描述符的简介 （/WEB-INF/web.xml)。
  4. 部署者- 操作Apache Tomcat 部署者来部署,预编译, 和验证网络应用程序。
  5. 管理者- 在 Apache Tomcat 运行时，由管理员(manager)程序来部署， 取消部署（undeploy)， 再部署 (redeploy)各类应用程序。
  6. 域和访问控制： 描述 怎样配置域(用户，密码和相关功能的数据库)来使用关于容器管理安全 性的网络应用程序。
  7. 安全管理： 配置和使用Java安全管理器来支持对网络程序行为的细致控制。
  8. JNDI 资源：在每个 网络程序的JNDI命名上下文里的配置标准以及客户资源。
  9. JDBC数据源：用数据库的连接池来配置JNDI数据源。有许多 流行的数据库实例。
  10. (类加载)- 关于Apache Tomcat 5里类的加载信息，包括在什么地方放置类程序，使他们有效。
  11. JSPs - 关于Jasper配置和 JSP编译器的使用信息。
  12. SSL - 安装和配置SSL支持，这样 Apache Tomcat 就可以应用https协定来服务需求。
  13. SSI - Apache Tomcat里服务器端 的应用。
  14. CGI - 在Apache Tomcat里如何 使用公用网关接口CGI。
  15. Proxy Support - 配置 Apache Tomcat 5通过代理器(或者作为代理器的web服务器)提供服务。
  16. MBean描述符 - 配置客户部件的 MBean描述符文件。
  17. Default Servlet - 配置 缺省servlet以及自定义用户目录列表。
  18. Apache Tomcat 集群- 在Tomcat 环境里使session复制成为可能。
  19. 负载均衡器: 配置,使用, 扩充加载均衡器的应用程序。
  20. 链接器 - Apache Tomcat支持的 链接访问方式，和本地服务器搭配。
  21. 监视和管理 - 启动JMX远程支持，并且使用工具来监视和管理Apache Tomcat。
  22. 日志 - 配置Apache Tomcat的日志
Reference

下面的文献是针对负责安装，配置和操作Apache Tomcat 5服务器的系统管理员的。

  • 版本信息 - 了解Apache Tomcat的发行版本。
  • Apache Tomcat 服务器配置参考 - 记录了可能被放置在Apache Tomcat 5 conf/server.xml 文件里面所有 可被使用的元素和属性的参考手册。
  • JK 文档 -JK 本地web服务器的全面文档和指南，用于Apache Tomcat同其他服务器，例如： Apache HTTPd, IIS 等等的联合使用。
  • Servlet API Javadocs - The Servlet 2.4 API Javadocs.
  • JSP API Javadocs - The JSP 2.0 API Javadocs.
Apache Tomcat Developers

下面的文献是提供给那些希望参与开发Apache Tomcat 项目的Java程序员的。

  • 从源文件构建 - 列举了下载 Apache Tomcat 5 源程序（包括其他关联程序包）的下载，和如何从这些 源码中构建一个二进制版本。
  • 变更日志 - 详细列出Apache Tomcat 不同版本的变化情况。
  • 进程 - Apache Tomcat 的开发进程。
  • 开发者 - Apache Tomcat 的开发者们。.
  • 功能说明书 - Apache Tomcat 5所使用的 Catalina servlet容器的必需的功能说明。
  • Catalina Javadocs - Catalina servlet容器和其附属部件的Javadoc API文档。
  • Jasper Javadocs - Apache Tomcat 5所使用的 Jasper JSP 容器的Javadoc API 文档。
  • Apache Tomcat 体系结构 - Apache Tomcat 服务器的体系结构文档。


Apache Tomcat 5.5 Servlet/JSP 容器 - 简介

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

简介

 Printer Friendly Version
print-friendly
version
介绍

不管是系统管理员还是web开发人员， 在开始使用Tomcat之前要先熟悉一些重要的信息。 这里对Tomcat容器背后的一些概念和术语进行简单介绍。同时，也告诉你在需要时到 哪里去寻找帮助。

名词术语

在阅读本文的过程中，你会遇到一些名词， 有的是Tomcat 特有的，有的是 Servlet 和 JSP 规范(specifications)里 定义的。

  • context(上下文)--概括地说, a Context 就是一个网络应用程序。
  • Term2 - This is it.
  • Term3 - This is it!
Directories and Files

在整个文献中，你会注意到许多地方提到 $CATALINA_HOME。 它代表Tomcat安装(installation)的根目录。 当我们说“你可以在 $CATALINA_HOME/README.txt文件里找到这些信息"，我们是指去Tomcat安装根目录 读README.txt文件。

下面是一些关键的Tomcat目录, 它们都和$CATALINA_HOME有关系。

  • /bin -- 启动，关闭和其它脚本文件。以*.sh 结束 的文件(Unix系统)是与*.bat文件(Window 系统)功能相同的复本。因为 Win32 命令行缺少一些功能,这里附上一些额外的文件。
  • /conf --配置文件(configuration file) 和相关的 DTDs（文档类型定义）。 最重要的文件是server.xml。 这是tomcat里面最重要的配置文件。
  • / logs --Log文件默认存放目录。
  • /webapps--这里存放你的网络应用程序。
配置 Tomcat

这一部分使你熟悉一些在容器配置(configurations of the container)时需要的基本信息。

所有配置文件的信息都是在启动时加载的（read at startup), 这就是说任何对文件的 更改都需要重新启动这个容器才会生效。

在哪获得更多帮助信息？

尽管我们努力确保这些文档易读和易懂，但还是有可能疏漏了一些东西。 如果你遇到 问题，可参看下面提供的各种网址和邮件列表。

因为 Tomcat 5 是 Tomcat 的新发行版，所以有些问题和解答会与Tomcat 4.x 版有所 不同。 当你在网上查找时，有些文档是针对于3.x 和 4.x 版本，而不适用于 Tomcat 5。 把 3.x 和 4.x 版本的配置用在 Tomcat 5 上， 在大多数情况下会行不通， 因为（Tomcat 5）在很多地方同tomcat 3.x4.x不同，比如说 server.xml 文件。

  • 当前文章－－大部分疑难问题的文档都包含在此。一定要充分阅读相关的资料，这样会 节省你不少时间和劳力。什么都比不上搜遍整个网络去找一直摆在你面前的答案最让人 难受了。
  • Tomcat FAQ，由开发人员维护。
  • Tomcat WIKI
  • 在 jGuru上的Tomcat FAQ
  • Tomcat 邮件列表存档－　许多网站有Tomcat的邮件列表的存档。因为这些链接(links)经常改变， 可以点击 Google 去查找。
  • Tomcat 用户邮件列表- 可以从这里 申请。如果你没有得到回音，很有可能你的问题已经在存档或ＦＡＱ中得到解答。尽管 一些普通的程序问题会被问到，也会被解答，但是你的问题最好更加细致或特别一些。
  • Tomcat -开发人员邮件列表- 可以从这里 申请。这个列表是专门保留给开发Tomcat讨论用的。关于Tomcat配置 的问题，或者在运行程序中遇到问题，最好去TOMCAT用户邮件列表。

如果你认为有什么内容有必要列在这里，请尽可能在TOMCAT开发人员邮件列表让我们知道， 或者给任何一个文档作者发电子邮件。


Apache Tomcat 5.5 Servlet/JSP 容器 - Jasper 2 JSP Engine How To

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Jasper 2 JSP Engine How To

 Printer Friendly Version
print-friendly
version
Table of Contents

简介
配 置
生产配置
网络应用程序编译
使用 Jikes

Introduction

Tomcat 5.0使用Jasper 2 JSP Engine来实现 JavaServer Pages 2.0规范。

Jasper 2被重新设计后，它的性能比原来的Jasper有极大的改善。除了基本的代码改进 以外，还有下面这些变化：

  • JSP Custom Tag Pooling - Java对象例示的JSP客户自定义标签 (JSP Custom Tags)现在可以被汇集起来重新使用。这极大地提高了使用客户自定义 标签的JSP页面的性能。
  • Background JSP compilation - 如果你更改了已经被编译过的JSP 页面，Jasper 2可以在后台重新编译这个页面。先前编译过的JSP页面还是被用来提供 服务。一旦新的页面被编译好了，它就可以取代旧的页面。这有助于提高你的JSP页面 在生产服务器上的可使用性。
  • Recompile JSP when included page changes - Jasper 2现在可以 在编译时探测到什么时候JSP里的一个页面被更改过，并重新编译父JSP。
  • JDT used to compile JSP pages - Eclipse的JDT Java编译器现在 用来完成JSP中java源代码的编译工作。这个编译器加载源代码依赖于容器的类加载器。 Ant和javac依旧可以使用。

Jasper是通过使用servlet类org.apache.jasper.servlet.JspServlet来 实现的。

Configuration

默认的Jasper是被配置用来开发web应用程序的。关于使用于Tomcat生产服务器上的 Jasper配置信息，参看生产配置( Production Configuration)这一章。

用来实现Jasper的servlet是通过使用你的全局 $CATALINA_BASE/conf/web.xml文件里面的参数来配置的。

  • checkInterval - 如果development设置为false，reloading设置为 true，后台编译就可以实现了。checkInterval是检查一个JSP页面是否需要被重新编译 的秒数间隔。默认值是300秒。
  • compiler - 推荐使用Ant来编译JSP页面。具体信息请查阅Ant的 文档。如果没有被赋值，则默认的Eclipse JDT Java编译器将被用来代替Ant。 没有默认值。
  • classdebuginfo - 类文件在编译时是否显示排错(debugging)提示信息？ true 或false，默认是true。
  • classpath - 在编译产生的servlets时，应该使用什么class path呢？ 默认的classpath是基于当前web应用程序动态地产生的。
  • compilerSourceVM - 编译源文件时采用的JDK版本是什么？(默认是 JDK 1.4)
  • compilerTargetVM - 生成文件是采用的JDK版本是什么？(默认是 JDK1.4)
  • development - Jasper是否处于开发模式(将在每一次存取时检查JSP 是否被修改)？true 或 false，默认值是true 。
  • enablePooling - 确定标签处理池(tag handler pooling)是否可被 使用。true 或 false，默认值是true 。
  • engineOptionsClass - 允许指定的类来配置Jasper。如果没有指定， 则使用默认的Servlet内置参数(EmbeddedServletOptions)。
  • ieClassId - 当使用&lt;jsp:plugin&gt;标签时要发送给Internet Explorer的class-id值. 默认形式是clsid:8AD9C840-044E-11D1-B3E9-00805F499D93 。
  • fork - 是否让Ant把JSP页面编译进行分叉(fork)，这样一来编译就 可以在与Tomcat在不同的JVM里执行? true 或 false，默认值是true 。
  • javaEncoding - 用来产生java源文件的Java文件编码。默认是UTF8。
  • genStringAsCharArray - 是否把字符串转换为字符数组？在某些 情况下会用到。默认 false.
  • keepgenerated - 是否应该保留为每一页产生的Java源代码，而 不是把它删除掉？true 或 false , 默认值是true 。
  • mappedfile - 是否应该为每一行输入打印一个静态说明，来使排错 变得容易？true 或 false , 默认值是true 。
  • modificationTestInterval - Checks for modification for a given JSP file (and all its dependent files) will be performed only once every specified amount of seconds. Setting this to 0 will cause the JSP to be checked on every access. Default is 4 seconds.
  • reloading - Should Jasper check for modified JSPs? true or false, default false.
  • scratchdir - 在编译JSP页面的时候，应该使用什么scratch目录？默认的目录是当前web应用程序的工作目录。
  • trimSpaces - 样板本文里actions或指令之间的空白空间是否应该被修剪？默认值是false 。

The Java compiler from Eclipse JDT in included as the default compiler. It is an advanced Java compiler which will load all dependencies from the Tomcat class loader, which will help tremendously when compiling on large installations with tens of JARs. On fast servers, this will allow sub-second recompilation cycles for even large JSP pages. This new compiler will be updated to support the Java 5 syntax as soon as possible.

Apache Ant, which was used in previous Tomcat releases, can be used instead instead of the new compiler by simply removing the common/lib/jasper-compiler-jdt.jar file, and placing the ant.jar file from the latest Ant distribution in the common/lib folder. If you do this, you also need to use the "javac" argument to catalina.sh.

Production Configuration

The main JSP optimization which can be done is precompilation of JSPs. However, this might not be possible (for example, when using the jsp-property-group feature) or practical, in which case the configuration of the Jasper servlet becomes critical.

在生产Tomcat服务器里使用Jasper 2时，你应该考虑在默认的配置上进行下列修改。

  • development - To disable on access checks for JSP pages compilation set this to false.
  • genStringAsCharArray - To generate slightly more efficient char arrays, set this to true.
  • modificationTestInterval - If development has to be set to true for any reason (such as dynamic generation of JSPs), setting this to a high value will improve performance a lot.
  • trimSpaces - To remove useless bytes from the response, set this to true.

Web Application Compilation

Using Ant is the preferred way to compile web applications using JSPC. Use the script given below (a similar script is included in the "deployer" download) to precompile a webapp:

<project name="Webapp Precompilation" default="all" basedir=".">

  <target name="jspc">

    <taskdef classname="org.apache.jasper.JspC" name="jasper2" >
      <classpath id="jspc.classpath">
        <pathelement location="${java.home}/../lib/tools.jar"/>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/server/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
      </classpath>
    </taskdef>

    <jasper2
             validateXml="false"
             uriroot="${webapp.path}"
             webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
             outputDir="${webapp.path}/WEB-INF/src" />

  </target>

  <target name="compile">

    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    <mkdir dir="${webapp.path}/WEB-INF/lib"/>

    <javac destdir="${webapp.path}/WEB-INF/classes"
           optimize="off"
           debug="on" failonerror="false"
           srcdir="${webapp.path}/WEB-INF/src"
       excludes="**/*.smap">
      <classpath>
        <pathelement location="${webapp.path}/WEB-INF/classes"/>
        <fileset dir="${webapp.path}/WEB-INF/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/common/classes"/>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/shared/classes"/>
        <fileset dir="${tomcat.home}/shared/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
      </classpath>
      <include name="**" />
      <exclude name="tags/**" />
    </javac>

  </target>

  <target name="all" depends="jspc,compile">
  </target>

  <target name="cleanup">
      <delete>
        <fileset dir="${webapp.path}/WEB-INF/src"/>
        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
      </delete>
  </target>

</project>

下面的命令行可以用来运行这个script(用Tomcat基础路径和指向应该被预编译的webapp的路径来代替那些记号)。

$ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>

然后,对于在预编译过程中产生的servlets的声明和映射必须被加入到网络程序部署描述符里去。把${webapp.path}/WEB-INF/generated_web.xml插入到${webapp.path}/WEB-INF/web.xml文件应该被放置的地方。重新启动web程序(使用the manager)，并测试它以验证预编译过的servlets能正常运行。网络程序部署描述符里适当的标记(token)也可以被用来通过Ant过滤功能自动插入所产生servlets声明和映射。事实上这就是Tomcat发布的所有webapps作为build过程的一部分是怎样自动被编译的。

At the jasper2 task you can use the option addWebXmlMappings for automatic merge the ${webapp.path}/WEB-INF/generated_web.xml with the current web application deployment descriptor at ${webapp.path}/WEB-INF/web.xml. When you want to use Java 5 feature inside your jsp's, add the following javac compiler task attributes: source="1.5" target="1.5". For live application you can also compile with optimize="on" and without debug info debug="off".

When you don't want to stop the jsp generation at first jsp syntax error, use failOnError="false"and with showSuccess="true" all successfull jsp to java generation are printed out. Sometimes it is very helpfull, when you cleanup the generate java source files at ${webapp.path}/WEB-INF/src and the compile jsp servlet classes at ${webapp.path}/WEB-INF/classes/org/apache/jsp.

Hints:

  • When you switch to another tomcat release, then regenerate and recompile your jsp's with this version again!
  • Use java system property at server runtime to disable tag pooling org.apache.jasper.runtime.JspFactoryImpl.USE_POOL=false. and limit the buffering with org.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true. Note that changing from the defaults may affect performance, but depending on the application.

Using Jikes

如果你想要使用 Jikes来编译JSP页面：

  • From your Ant installation, copy ant.jar and (if it's available: Ant 1.5 and later) ant-launcher.jar to $CATALINA_BASE/common/lib.
  • 下载并安装jikes。jikes必须支持-encoding选项。执行jikes -help 来证实jikes被建造能支持-encoding。
  • 把init参数编译器设置为jikes 。
  • 在启动Tomcat时，定义属性-Dbuild.compiler.emacs=true， 把它加入到你的CATALINA_OPTS环境变量中。这改变了jikes输出错误信息的方式，使它与Jasper相兼容。
  • 如果你得到一个错误报告说jikes不能使用UTF8编码，去试试把init参数javaEncoding设置为ISO-8859-1。


Apache Tomcat 5.5 Servlet/JSP 容器 - JNDI Datasource HOW-TO

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

JNDI Datasource HOW-TO

 Printer Friendly Version
print-friendly
version
Table of Contents

简介
数据库连接池(DBCP)配置
非DBCP解决办法
Oracle 8i with OCI client
常见问题

Introduction

JNDI数据源配置在JNDI-Resources-HOWTO里面有详尽的说明，tomcat用户反馈回来的信息显示个别的特殊配置可能会很易出错。

这里为tomcat用户展示了一些通用数据库配置的例子，以及数据库使用的一些通常的提示。

因为这些注解是从tomcat用户反馈的配置信息派生而来，所以如果你有其他测试过的配置并且觉得能对更多其他用户会有用处，或者你觉得我们可以对这一部分有所改进，请让我们知道。

Please note that JNDI resource configuration has changed somewhat between Tomcat 5.0.x and Tomcat 5.5.x. You will most likely need to modify your JNDI resource configurations to match the syntax in the example below in order to make them work in Tomcat 5.5.x.

Also, please note that JNDI DataSource configuration in general, and this tutorial in particular, assumes that you have read and understood the Context and Host configuration references, including the section about Automatic Application Deployment in the latter reference.

Database Connection Pool (DBCP) Configurations

DBCP对JDBC 2.0提供支持。 使用1.4 JVM DBCP的系统会支持JDBC 3.0。如果你已经使用过1.4 JVM DBCP以及JDBC 3.0特性，请让我们知道。

See the DBCP documentation for a complete list of configuration parameters.

Installation

DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:

  • Jakarta-Commons DBCP 1.0
  • Jakarta-Commons Collections
  • Jakarta-Commons Pool
These libraries are located in a single JAR at $CATALINA_HOME/common/lib/naming-factory-dbcp.jar. However, only the classes needed for connection pooling have been included, and the packages have been renamed to avoid interfering with applications.

Preventing dB connection pool leaks

一个数据库连接池产生并管理一系列与数据库的连接。再回收和再利用现存的数据库连接比打开一个新的连接要有效率的多。

连接池也有一个问题。那就是网络程序必须专门关闭ResultSet's, Statement's, 和 Connection's 。 网络程序若没有关闭这些资源，会造成这些资源再也不能被重新使用，产生数据库连接池“泄露”的后果。如果没有别的连接可被使用，最终会造成你的网络程序数据库连接失败。

对于这个问题有一个解决办法。Jakarta-Commons DBCP可以被配置来追踪和修复这些被遗弃的数据库连接。它不仅可以修复它们，而且可以对那些打开这些资源但又从来没有关闭它们的代码展开一层层追踪。

To configure a DBCP DataSource so that abandoned dB connections are removed and recycled add the following attribute to the Resource configuration for your DBCP DataSource:

            removeAbandoned="true"
当可被利用的数据库连接降到很低，DBCP会修复并回收它能发现的被放弃的数据库连接。默认值是false 。

Use the removeAbandonedTimeout attribute to set the number of seconds a dB connection has been idle before it is considered abandoned.

            removeAbandonedTimeout="60"
删除被放弃的连接的默认时间是300秒。

The logAbandoned attribute can be set to true if you want DBCP to log a stack trace of the code which abandoned the dB connection resources.

            logAbandoned="true"
默认值是false 。

MySQL DBCP Example

简介

下面这些的MySQL和JDBC驱动的版本可以运作：

  • MySQL 3.23.47, MySQL 3.23.47 using InnoDB,, MySQL 3.23.58, MySQL 4.0.1alpha
  • Connector/J 3.0.11-stable (the official JDBC Driver)
  • mm.mysql 2.0.14 (an old 3rd party JDBC Driver)

在你开始之前，别忘记复制一份JDBC驱动的jar文件到$CATALINA_HOME/common/lib里面。

MySQL 配置

你一定要遵循这些指导说明，因为变动会产生问题。

产生一个新的测试用户，一个新的数据库和一个测试表格。你的MySQL用户必须要有个指派的密码。如果你试图用空密码连接，驱动会失败。

mysql&gt; GRANT ALL PRIVILEGES ON *.* TO javauser@localhost
-&gt; IDENTIFIED BY 'javadude' WITH GRANT OPTION;
mysql&gt; create database javatest;
mysql&gt; use javatest;
mysql&gt; create table testdata (
-&gt; id int not null auto_increment primary key,
-&gt; foo varchar(25),
-&gt; bar int);
注意：当测试完成以后，上面的用户应该被删除掉。

下一步，在testdata表格中加入一些测试数据。

mysql&gt; insert into testdata values(null, 'hello', 12345);
Query OK, 1 row affected (0.00 sec)

mysql&gt; select * from testdata;
+----+-------+-------+
| ID | FOO | BAR |
+----+-------+-------+
| 1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)

mysql&gt;

server.xml 配置

通过向$CATALINA_HOME/conf/server.xml里面加入一个声明来在Tomcat里配置JNDI DataSource。

Add this in between the </Context> tag of the examples context and the </Host> tag closing the localhost definition. If there is no such tag, you can add one as illustrated in the Context and Host configuration references, and repeated below for your convenience.

<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

    <!-- maxActive: Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to 0 for no limit.
         -->

    <!-- maxIdle: Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->

    <!-- maxWait: Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->

    <!-- username and password: MySQL dB username and password for dB connections  -->

    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
         -->

    <!-- url: The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->

  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/>

</Context>

web.xml 配置

现在为这个测试程序产生一个WEB-INF/web.xml 文件。

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

测试代码

现在产生一个简单的test.jsp页面供以后使用。

&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %&gt;
&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt;

&lt;sql:query var="rs" dataSource="jdbc/TestDB"&gt;
select id, foo, bar from testdata
&lt;/sql:query&gt;

&lt;html&gt;
&lt;head&gt;
&lt;title&gt;DB Test&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h2&gt;Results&lt;/h2&gt;

&lt;c:forEach var="row" items="${rs.rows}"&gt;
Foo ${row.foo}&lt;br/&gt;
Bar ${row.bar}&lt;br/&gt;
&lt;/c:forEach&gt;

&lt;/body&gt;
&lt;/html&gt;

JSP页面利用JSTL 's SQL 和 Core taglibs 。你可以从Sun's Java Web Services Developer Pack 得到它，或者从Jakarta Taglib Standard 1.1 project 得到它——确保你拿到的是1.1.x发行版。当你有了JSTL以后，把jstl.jar和standard.jar复制到你的网络程序的WEB-INF/lib目录里。

最后把你的网络程序作为DBTest.war的warfile形式，或以名叫DBTest的子目录形式部署到$CATALINA_HOME/webapps 里面。

当部署完成后，在一个浏览器里指向http://localhost:8080/DBTest/test.jsp就可以看到你辛勤劳动的成果了。

Oracle 8i, 9i & 10g

简介

Oracle requires minimal changes from the MySQL configuration except for the usual gotchas :-)

Drivers for older Oracle versions may be distributed as *.zip files rather than *.jar files. Tomcat will only use *.jar files installed in $CATALINA_HOME/common/lib. Therefore classes111.zip or classes12.zip will need to be renamed with a .jar extension. Since jarfiles are zipfiles, there is no need to unzip and jar these files - a simple rename will suffice.

Some early versions of Tomcat 4.0 when used with JDK 1.4 will not load classes12.zip unless you unzip the file, remove the javax.sql.* class heirarchy and rejar.

For Oracle 9i onwards you should use oracle.jdbc.OracleDriver rather than oracle.jdbc.driver.OracleDriver as Oracle have stated that oracle.jdbc.driver.OracleDriver is deprecated and support for this driver class will be discontinued in the next major release.

server.xml 配置

In a similar manner to the mysql config above, you will need to define your Datasource in your server.xml file. Here we define a Datasource called myoracle using the thin driver to connect as user scott, password tiger to the sid called mysid. (Note: with the thin driver this sid is not the same as the tnsname). The schema used will be the default schema for the user scott.

使用OCI驱动只需要在URL字串里简单地把thin改变成oci 。

<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>

web.xml 配置

你应该确保在产生web.xml文件时，尊重DTD定义的元素排列顺序。

&lt;resource-ref&gt;
&lt;description&gt;Oracle Datasource example&lt;/description&gt;
&lt;res-ref-name&gt;jdbc/myoracle&lt;/res-ref-name&gt;
&lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
&lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;

代码示例

你可以使用与上面相同的程序例子(假设你产生了必需的数据库实例，表格等)来代替Datasource代码，它可能象这样：

Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
//etc.
PostgreSQL

简介

PostgreSQL is configured in a similar manner to Oracle.

1. Required files

Copy the Postgres JDBC jar to $CATALINA_HOME/common/lib. As with Oracle, the jars need to be in this directory in order for DBCP's Classloader to find them. This has to be done regardless of which configuration step you take next.

2. Resource configuration

You have two choices here: define a datasource that is shared across all Tomcat applications, or define a datasource specifically for one application.

2a. Shared resource configuration

Use this option if you wish to define a datasource that is shared across multiple Tomcat applications, or if you just prefer defining your datasource in this file.

This author has not had success here, although others have reported so. Clarification would be appreciated here.

<Resource name="jdbc/postgres" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://127.0.0.1:5432/mydb"
          username="myuser" password="mypasswd" maxActive="20" maxIdle="10" maxWait="-1"/>

2b. Application-specific resource configuration

Use this option if you wish to define a datasource specific to your application, not visible to other Tomcat applications. This method is less invasive to your Tomcat installation.

Create a resource definition file for your application defining the datasource. This file must have the same name as your application, so if your application deploys as someApp.war, this filename must be someApp.xml. This file should look something like the following.

<Context path="/someApp" docBase="someApp"
   crossContext="true" reloadable="true" debug="1">

<Resource name="jdbc/postgres" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://127.0.0.1:5432/mydb"
          username="myuser" password="mypasswd" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>

web.xml 配置

&lt;resource-ref&gt;
&lt;description&gt;postgreSQL Datasource example&lt;/description&gt;
&lt;res-ref-name&gt;jdbc/postgres&lt;/res-ref-name&gt;
&lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
&lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;

4. Accessing the datasource

When accessing the datasource programmatically, remember to prepend java:/comp/env to your JNDI lookup, as in the following snippet of code. Note also that "jdbc/postgres" can be replaced with any value you prefer, provided you change it in the above resource definition file as well.

InitialContext cxt = new InitialContext();
if ( cxt == null ) {
   throw new Exception("Uh oh -- no context!");
}

DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );

if ( ds == null ) {
   throw new Exception("Data source not found!");
}
Non-DBCP Solutions

这些办法要么是利用单个数据库连接(建议仅作测试用，而不要作其它用处)，要么是其他pooling技术。

Oracle 8i with OCI client
Introduction

虽然没有严格强调使用OCI client来产生JNDI DataSource，这里的这些注解可以和上面所讲的Oracle and DBCP方法合在一起。

为了使用OCI驱动，你必须要安装一个Oracle client。你应该从cd安装Oracle8i(8.1.7) client ，然后再从otn.oracle.com下载相适宜的JDBC/OCI driver(Oracle8i 8.1.7.1 JDBC/OCI Driver)。

在把classes12.zip文件重新命名为classes12.jar以后，把它复制到Tomcat的$CATALINA_HOME/common/lib里面。根据你使用的Tomcat和JDK 版本，你还可能必须从这个文件删除javax.sql.* 类。

Putting it all together

确保在你的$PATH or LD_LIBRARY_PATH (possibly in $ORAHOME\bin ) 有ocijdbc8.dll or .so ，并且确定使用一个简单的测试程序System.loadLibrary("ocijdbc8")可以装载native library。

你下一步应该产生一个简单的测试servlet或jsp，要有下面这些关键行：

DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
conn =
DriverManager.getConnection("jdbc:oracle:oci8:@database","username","password");

这里数据库是host:port:SID的形式。现在如果你想试图访问你测试的servlet/jsp 的URL，你得到的是一个ServletException，造成它的根本原因在于java.lang.UnsatisfiedLinkError:get_env_handle 。

首先，这个UnsatisfiedLinkError表明你有下列问题：

  • JDBC类文件和Oracle client版本不相配。发给你的消息会说明是因为一个必须的library不能被找到。例如，你可能把Oracle Version 8.1.6里边的一个classes12.zip文件与与Version 8.1.5 Oracle client 一起使用。classeXXXs.zip文件与Oracle client软件的版本必须相配。
  • 一个$PATH , LD_LIBRARY_PATH 问题。
  • 据报道，忽略你从otn下载的驱动，使用$ORAHOME\jdbc\lib目录里的classes12.zip文件也行得通。

下一步，你可能会遇到错误ORA-06401 NETCMN: invalid driver designator

Oracle文件说明会说："Cause: The login (connect) string contains an invalid driver designator. Action: Correct the string and re-submit." 把数据库的连接字串( host:port:SID 的形式)改变成这个样：(description=(address=(host=myhost)(protocol=tcp)(port=1521))(connect_data=(sid=orcl)))

Ed. Hmm, I don't think this is really needed if you sort out your TNSNames - but I'm not an Oracle DBA :-)

Common Problems

这里是一些网络程序中使用数据库常常遇到的问题，以及怎样解决它们的提示。

Intermittent dB Connection Failures

Tomcat在一个JVM里运行。JVM定期地执行垃圾收集工作(GC)来删除不再被使用的对象。当JVM执行GC时，Tomcat暂停。如果配置的连接数据库的最长时间少于垃圾收集所花费的时间，你就可能得到一个数据库连接失败。

要收集关于垃圾收集所花费的时间，在启动Tomcat时，把-verbose:gc加入到你的CATALINA_OPTS环境变量中。当垃圾收集(gc)工作时，你的$CATALINA_BASE/logs/catalina.out日志文件会记录所有的关于垃圾收集的数据，包括垃圾收集需要多长时间。

当你的JVM调试正确率为99%时，垃圾收集工作花费的时间比一秒钟还少。收尾工作仅仅花几秒钟。垃圾收集很少用10秒钟以上的时间。

确保数据库连接时间设置为10-15秒。对于DBCP来说，用maxWait参数来设置。

Random Connection Closed Exceptions

当一个请求从连接池得到一个数据库连接，然后关闭它两次，就会产生这些异常。当使用一个连接池时，关闭连接仅仅是把它返回到池中再被另外的请求使用，而不时把这个连接断掉。Tomcat使用多线程来处理同时发生的请求。这里的例子是关于事件(events)顺序怎样在Tomcat里造成这类错误：

Request 1 running in Thread 1 gets a db connection.

Request 1 closes the db connection.

The JVM switches the running thread to Thread 2

Request 2 running in Thread 2 gets a db connection
(the same db connection just closed by Request 1).

The JVM switches the running thread back to Thread 1

Request 1 closes the db connection a second time in a finally block.

The JVM switches the running thread back to Thread 2

Request 2 Thread 2 tries to use the db connection but fails
because Request 1 closed it.
这里的例子是一个写得不错的关于使用从连接池获得的数据库连接的代码。
Connection conn = null;
Statement stmt = null; // Or PreparedStatement if needed
ResultSet rs = null;
try {
conn = ... get connection from connection pool ...
stmt = conn.createStatement("select ...");
rs = stmt.executeQuery();
... iterate through the result set ...
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
... deal with errors ...
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null) {
try { rs.close(); } catch (SQLException e) { ; }
rs = null;
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
}

Context versus GlobalNamingResources

请注意虽然在上面的说明中把JNDI声明放在一个Context元素里面，有可能，而且有时更需要把这些声明放在服务器配置文件的GlobalNamingResources区域。被放置在GlobalNamingResources区域的资源将会被服务器的Contexts共享。

JNDI Resource Naming and Realm Interaction

为了让Realms能运作，这个realm必须按照&lt;GlobalNamingResources&gt; 或 &lt;Context&gt; 章节定义的那样指向数据源，而不是指向用&lt;ResourceLink&gt;重新命名的数据源。


Apache Tomcat 5.5 Servlet/JSP 容器 - JNDI Resources HOW-TO

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

JNDI Resources HOW-TO

 Printer Friendly Version
print-friendly
version
Introduction

Tomcat 5以一个可与Java2企业版(J2EE)应用服务器相容的方式，提供给每个在它里面运行的网络程序一个JNDI InitialContext执行实例。J2EE标准在/WEB-INF/web.xml文件里提供了一系列标准元素，可用来查询资源；被这些元素索引的资源还需要根据不同的应用服务器来配置。

对Tomcat 5来说，每个网络应用的InitialContext是在<Context>元素中被配置的，而<Context>元素最好在该网络应用的上下文XML文件(或META-INF/context.xml)中被指定，或者在$CATALINA_HOME/conf/server.xml文件中被指定。

Tomcat 5还为整个服务器所使用的全球性资源提供一个单独的命名空间(namespace)。这些资源配置在$CATALINA_HOME/conf/server.xml文件的 <GlobalNameingResources>元素中。你可以通过<ResourceLink>元素把这些资源提供给各个网络程序。

在这些元素内定义的资源可以被你的程序部署描述符( /WEB-INF/web.xml )里的下列这些元素引用：

  • <env-entry> - 环境变量输入，这个单个值参数(single-value parameter)可以用来配置网络程序如何运行。
  • <resource-ref> - 资源引用名，它通常指向该资源的对象(object)工厂，如JDBC 数据源, a JavaMail Session，或者作为自己编写(custom)的对象工厂配置在Tomcat 5里边。
  • <resource-env-ref> - 资源环境索引，这是Servlet 2.4版本里新加入的资源引用(resource-ref)变量，对那些不要求用户认证的资源来说，这个变量比较容易配置。

InitialContext是在网络程序最初被部署到服务器上时配置的，并且所有的网络程序可以使用它(仅供只读访问)。所有配置的条目和资源都被放置在JNDI的java:comp/env 命名空间中。以下是以JDBC DataSource(数据源)为例来说明如何访问一个资源——它看起来象这样：

// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");

// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

参看下面两个规范，了解更多关于编码JNDI APIs的信息，以及Java2 企业版(J2EE)服务器所支持的相关性能：

  • Java Naming and Directory Interface (包括在JDK 1.4版内, 在这之前的版本需要另外下载)
  • J2EE Platform Specification (参看第五章Naming )
Configuring JNDI Resources

Each available JNDI Resource is configured based on inclusion of the following elements in the <Context> element:

  • <Environment> - 配置环境变量的名字和值,网络程序可通过JNDI InitialContext 来查询(相当于在网络程序部署描述符中包括一个<env-entry>元素)。
  • <Resource> - 配置程序可以使用的资源名字和数据类型(相当于 在网络程序部署描述符中包括一个<resource-ref>元素)。
  • <ResourceLink> - 为定义在全球性JNDI context内的资源加上一个链连。让网络程序可以使用这个链连访问定义在<GlobalNamingResources>里的资源，这个<GlobalNamingResources>是<Server>的子元素。
  • <Transaction> - Add a resource factory for instantiating the UserTransaction object instance that is available at java:comp/UserTransaction.

任何数目的上述元素都可以套嵌在<Context>元素里（这些元素必须是和某个特定的网络应用程序相关的）。

另外，包含在程序部署描述符(/WEB-INF/web.xml)里的所有<env-entry>元素的 名字和值也都会加入到initial context中，只有<Environment>元素 允许(通过把override属性设置为"true")的情况下，<env-entry>元素中 的值才会覆盖conf/server.xml 中相应的值。

全球性资源可以定义在全服务器的JNDI context，把上面描述的资源元素加到<Server>的子元素<GlobalNamingResources>中，并且用<ResourceLink>把它包括在每个网络程序的(per-web-application)上下文中。

Tomcat Standard Resource Factories

Tomcat 5包含了一系列标准资源工厂来为你的网络程序服务，但又给你配置适度的弹性(在 $CATALINA_HOME/conf/server.xml 里)而不需要修改网络程序或部署描述符。下列章节详细描述了如何配置和使用这些标准资源工厂。

关于怎样产生，安装，配置和使用你自己编写的资源工厂类，参看Adding Custom Resource Factories。

注意——在标准资源工厂当中，只有"JDBC Data Source" 和 "User Transaction" 是必须让所有执行Java2企业版(J2EE)规范的平台使用。其他的标准资源工厂，以及你自己写的资源工厂只对Tomcat有效，而不能假设可让其他容器使用。

Generic JavaBean Resources

简介

这个资源工厂可以用来产生任何遵守标准JavaBeans命名习惯的Java类的对象(例如，它具有一个没有变量的构造式，具有遵守setFoo()命名模式的属性设置方法)。每次lookup()输入，这个资源工厂就会产生一个新的相称的bean class实例。

使用这一设施的必需步骤如下：

产生你的JavaBean类

产生JavaBean类，让它每一次要查找资源工厂时就被实例化(instantiated)。在这个例子中，假设你产生一个叫做com.mycompany.MyBean的类，它看起来象这样：

package com.mycompany;

public class MyBean {

private String foo = "Default Foo";

public String getFoo() {
return (this.foo);
}

public void setFoo(String foo) {
this.foo = foo;
}

private int bar = 0;

public int getBar() {
return (this.bar);
}

public void setBar(int bar) {
this.bar = bar;
}

}

声明你的资源要求

下一步，修改你的网络程序部署描述符( /WEB-INF/web.xml ) 来声明JNDI名字，你将要求产生这个bean的新的实例在其名下。最简单的方法是象这样来使用<resource-env-ref>元素：

&lt;resource-env-ref&gt;
&lt;description&gt;
Object factory for MyBean instances.
&lt;/description&gt;
&lt;resource-env-ref-name&gt;
bean/MyBeanFactory
&lt;/resource-env-ref-name&gt;
&lt;resource-env-ref-type&gt;
com.mycompany.MyBean
&lt;/resource-env-ref-type&gt;
&lt;/resource-env-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

典型的使用这个资源环境索引的编码看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
bean.getBar());

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到$CATALINA_HOME/conf/server.xml文件中，并把它套嵌在这个网络应用程序的Context元素里。

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="org.apache.naming.factory.BeanFactory"
            bar="23"/>
  ...
</Context>

注意资源名称(这里是bean/MyBeanFactory)必须与网络程序部署描述符里指定的值相对映。我们也还要初始化bar property的值，这会在返回新的bean之前引起调用setBar(23)。因为我们没有初始化foo property(尽管我们也可以这样做)，bean会包含它的构造器设置的任何默认值。

JavaMail Sessions

简介

在许多网络应用中，发送电子邮件是系统功能必须的一部分。Java Mail API 使得这一处理过程相对直截了当，但是客户的应用程序必须要了解许多配置的详细情况(包括用来发送消息的SMTP主机名字)。

Tomcat 5包括一个产生javax.mail.Session实例的标准资源工厂，它已经与被server.xml配置过的SMTP服务器连接好了。通过这种办法，程序完全和电子邮件服务器配置环境中的变化分隔开了——在任何需要的时候，只要请求和接受一个预先配置过的session就行了。

这个过程必需的步骤概括如下：

声明你的资源要求

你要做的第一件事就是修改网络程序部署描述符(/WEB-INF/web.xml)来声明JNDI名称，你可在其名下查看预先配置过的sessions。根据习惯性，所有这样的名称都必须围绕着邮件的subcontext而派生(与标准的java:comp/env naming context 相关，这个naming context是所有的资源工厂的根)。 一个典型的web.xml看起来象这样：

&lt;resource-ref&gt;
&lt;description&gt;
Resource reference to a factory for javax.mail.Session
instances that may be used for sending electronic mail
messages, preconfigured to connect to the appropriate
SMTP server.
&lt;/description&gt;
&lt;res-ref-name&gt;
mail/Session
&lt;/res-ref-name&gt;
&lt;res-type&gt;
javax.mail.Session
&lt;/res-type&gt;
&lt;res-auth&gt;
Container
&lt;/res-auth&gt;
&lt;/resource-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

一个典型的使用这个资源索引的例子看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from"));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);

注意，这个程序使用的是与网络程序部署描述符里声明的资源索引相同的名字。这是与在$CATALINA_HOME/conf/server.xml 里配置的资源工厂相映射的，描述如下：

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到$CATALINA_HOME/conf/server.xml文件中，并把它套嵌在这个网络应用程序的Context元素里。

<Context ...>
  ...
  <Resource name="mail/Session" auth="Container"
            type="javax.mail.Session"
            mail.smtp.host="localhost"/>
  ...
</Context>

注意，资源的名字(这里是mail/Session)必须与网络程序部署描述符里指定的值相映射。客户化(自己指定)mail.smtp.host参数值，让它指向为你的网络(network)提供SMTP服务的服务器那里。

安装JavaMail libraries

Download the JavaMail API. The JavaMail API requires the Java Activation Framework (JAF) API as well. The Java Activation Framework can be downloaded from Sun's site.

This download includes 2 vital libraries for the configuration; activation.jar and mail.jar. Unpackage both distributions and place them into $CATALINA_HOME/common/lib so that they are available to Tomcat during the initialization of the mail Session Resource. Note: placing these jars in both common/lib and a web application's lib folder will cause an error, so ensure you have them in the $CATALINA_HOME/common/lib location only.

应用程序示例(Example Application)

这个Tomcat包含的/examples 程序里有一个利用这一资源工厂的例子。你可通过"JSP Examples"链连来访问。实际上发送邮件的这个servlet的源代码是在/WEB-INF/classes/SendMailServlet.java里面。

警告——默认的配置假设在局部主机的端口25(port 25)有一个SMTP服务器的列单。如果不是这样，去编辑一下$CATALINA_HOME/conf/server.xml文件，把mail.smtp.host的参数值修改成你的网络SMTP服务器的主机名字。

JDBC Data Sources

简介

许多网络程序需要通过JDBC驱动来访问数据库，从而来支持这个程序必需的功能。J2EE Platform Specification 要求J2EE应用服务器让数据源实施(DataSource implementation) 成为可能(那就是，让数据源实施作为JDBC连接的连接池)。Tomcat 5提供完全一样的支持，这样你在Tomcat上开发的基于数据库的(database-based)程序，要使用这个服务，可以在任何J2EE服务器上运行而不需任何更改。

关于JDBC的信息，你应该去参考下列链连：

  • http://java.sun.com/products/jdbc/ - 关于Java数据库连接信息的主 页。
  • http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html - The JDBC 2.1应用编程界面规范。
  • http://java.sun.com/products/jdbc/jdbc20.stdext.pdf - JDBC 2.0 标准扩展应用编程界面 (包括 javax.sql.DataSource API). 这个软件包就是现在的"JDBC Optional Package"。
  • http://java.sun.com/j2ee/download.html - J2EE 操作平台规范(涵盖所有J2EE操作平台必须提供给应用程序的JDBC设施).

注意——Tomcat里支持的默认数据源是基于Jakarta Commons分项目的DBCP连接池的。然而，也有可能通过使用其他实施javax.sql.DataSource的连接池来编写你自己的资源工厂，描述如下：

安装你的JDBC驱动

要使用JDBC Data Sources JNDI 资源工厂，你必须让适当的JDBC驱动既能被Tomcat内部的类使用，又能被你的网络程序使用。最容易的办法是在$CATALINA_HOME/common/lib目录里边安装驱动的JAR文件，这样就让这个驱动既能被资源工厂使用，又能被你的程序使用。

声明你的资源要求

下一步，修改网络程序部署描述符(/WEB-INF/web.xml)来声明JNDI名称。根据习惯性，所有这样的名称都必须围绕着jdbc subcontext 而派生(与标准的java:comp/env naming context 相关，这个naming context是所有的资源工厂的根)。 一个典型的web.xml看起来象这样：

&lt;resource-ref&gt;
&lt;description&gt;
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the server.xml file.
&lt;/description&gt;
&lt;res-ref-name&gt;
jdbc/EmployeeDB
&lt;/res-ref-name&gt;
&lt;res-type&gt;
javax.sql.DataSource
&lt;/res-type&gt;
&lt;res-auth&gt;
Container
&lt;/res-auth&gt;
&lt;/resource-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

一个典型的使用这个资源索引的例子看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

注意，这个程序使用的是与网络程序部署描述符里声明的资源索引相同的名字。这是与在$CATALINA_HOME/conf/server.xml 里配置的资源工厂相映射的，描述如下：

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到网络应用程序的/META-INF/context.xml 文件中。

<Context ...>
  ...
  <Resource name="jdbc/EmployeeDB" auth="Container"
            type="javax.sql.DataSource" username="dbusername" password="dbpassword"
            driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database"
            maxActive="8" maxIdle="4"/>
  ...
</Context>

注意，这个资源的名字(这里是jdbc/EmployeeDB )必须与网络程序部署描述符里指定的值相映射。

这个例子假设你使用HypersonicSQL数据库JDBC驱动。客户化(自己指定)driverClassName 和 driverName这两个参数，让它们与你实际使用的JDBC驱动和连接URL相映射。

Tomcat标准数据资源工厂(org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory)的配置属性如下：

  • driverClassName - 被使用的JDBC驱动的完全合格的Java类名。
  • maxActive - 可以同时从这个pool被分配的最大active实例数目。
  • maxIdle - 可以同时在这个pool闲滞的最大连接数目。
  • maxWait - 这个pool在抛出异常之前可以等待连接返回的最长milliseconds 。
  • password - 将要传递给JDBC驱动的数据库密码。
  • url - 将要传递给JDBC驱动的连接URL(因为向后兼容性，属性的driverName也被认可)。
  • user - 将要传递给JDBC驱动的数据库用户名。
  • validationQuery - 在连接被返回到程序之前，可以被这个pool用来验证连接用的SQL query 。 如被指定，这个query必须是一个SQL SELECT 指令，它至少有一行的返回说明。

更多详细信息，请参看commons-dbcp文档资料。

Adding Custom Resource Factories

如果任何标准资源工厂都不能满足你的要求，你可以编写你自己的资源工厂，并把它整合到Tomcat 5里面，再在conf/server.xml configuration文件里配置怎样使用它。在下面的例子里，你将要产生一个资源工厂，这个工厂仅仅知道怎样产生上面所描述的Generic JavaBean Resources例子里的com.mycompany.MyBean beans 。

编写一个资源工厂类

你必须编写一个实施JNDI服务供给者 javax.naming.spi.ObjectFactory 界面的类。每次你的程序在这个工厂绑定的context entry上调用lookup() ，这个getObjectInstance()方法就会被叫到，有以下这些参数：

  • Object obj - 包含地址或索引信息的对象(很可能是空值)，它可用于制造一个对象(object)。对Tomcat来说，这总是一个javax.naming.Reference类型的对象，它包括这个工厂类的类名，以及用来产生返回对象的配置属性(来自conf/server.xml)。
  • Name name - 这个工厂绑定的与nameCtx有关联的名字,如果没有名字被指定,它就是空值。
  • Context nameCtx - 名称参数相对于这个context被指定，如果名称是相对于默认的初始context，它就是空值。
  • Hashtable environment - 用来产生这个对象的环境(很可能是空值)。这通常在Tomcat对象工厂被忽略。

要制造一个知道怎样产生MyBean实例的资源工厂，你可能会产生一个象这样的类：

package com.mycompany;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {

  public Object getObjectInstance(Object obj,
      Name name, Context nameCtx, Hashtable environment)
      throws NamingException {

      // Acquire an instance of our specified bean class
      MyBean bean = new MyBean();

      // Customize the bean properties from our attributes
      Reference ref = (Reference) obj;
      Enumeration addrs = ref.getAll();
      while (addrs.hasMoreElements()) {
          RefAddr addr = (RefAddr) addrs.nextElement();
          String name = addr.getType();
          String value = (String) addr.getContent();
          if (name.equals("foo")) {
              bean.setFoo(value);
          } else if (name.equals("bar")) {
              try {
                  bean.setBar(Integer.parseInt(value));
              } catch (NumberFormatException e) {
                  throw new NamingException("Invalid 'bar' value " + value);
              }
          }
      }

      // Return the customized instance
      return (bean);

  }

}

在这个例子里，我们无条件地产生一个新的com.mycompany.MyBean类的实例，并且在&lt;ResourceParams&gt;元素所包含的参数基础上populating它的属性，而这个&lt;ResourceParams&gt;元素是配置这个工厂用的(参见下面)。你应该注意，必须跳过所有名字叫工厂的参数——这个参数是用来指定工厂类自身的名字(在这里的情况下是com.mycompany.MyBeanFactory)，而不是用来指定要被配置的bean的属性。

关于ObjectFactory的更多信息，请参看JNDI 1.2 Service Provider Interface (SPI) Specification 。

你需要对照一个包括所有$CATALINA_HOME/common/lib 和$CATALINA_HOME/server/lib目录里的JAR文件的class path来编译这个类。当你完成以后，把这个工厂类(以及相关的bean类)以未包装形式放在$CATALINA_HOME/common/classes下面，或者放在$CATALINA_HOME/common/lib里的一个JAR文件里。通过这种方式，所需要的类文件既可以被Catalina内部资源又可以被你的网络程序使用。

声明你的资源要求

下一步，修改你的网络程序部署描述符( /WEB-INF/web.xml ) 来声明JNDI名字，你将要求产生这个bean的新的实例在其名下。最简单的方法是象这样来使用<resource-env-ref>元素：

&lt;resource-env-ref&gt;
&lt;description&gt;
Object factory for MyBean instances.
&lt;/description&gt;
&lt;resource-env-ref-name&gt;
bean/MyBeanFactory
&lt;/resource-env-ref-name&gt;
&lt;resource-env-ref-type&gt;
com.mycompany.MyBean
&lt;/resource-env-ref-type&gt;
&lt;/resource-env-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

典型的使用这个资源环境索引的编码看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
bean.getBar());

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到$CATALINA_HOME/conf/server.xml文件中，并把它套嵌在这个网络应用程序的Context元素里。

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="com.mycompany.MyBeanFactory"
            bar="23"/>
  ...
</Context>

注意资源名称(这里是bean/MyBeanFactory)必须与网络程序部署描述符里指定的值相对映。我们也还要初始化bar property的值，这会在返回新的bean之前引起调用setBar(23)。因为我们没有初始化foo property(尽管我们也可以这样做)，bean会包含它的构造器设置的任何默认值。

你会注意到，从程序开发员的角度来看，对资源环境索引的声明，和用于请求新实例的编程，与Generic JavaBean Resources例子里使用的方法完全一样。这里举例说明了使用JNDI资源来封装功能(functionality)的一个优点——那就是，只要你保持相兼容的APIs，你可以改变下面的实施(underlying implementation)而不需要使用资源来修改程序。


Apache Tomcat 5.5 Servlet/JSP 容器 - Logging in Tomcat

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Logging in Tomcat

 Printer Friendly Version
print-friendly
version
Introduction

Tomcat 5.5 uses Commons Logging throughout its internal code allowing the developer to choose a logging configuration that suits their needs, e.g java.util.logging or Log4J. Commons Logging provides Tomcat the ability to log hierarchially across various log levels without needing to rely on a particular logging implementation.

An important consequence for Tomcat 5.5 is that the <Logger> element found in previous versions to create a localhost_log is no longer a valid nested element of <Context>. Instead, the default Tomcat configuration will use java.util.logging. If the developer wishes to collect detailed internal Tomcat logging (i.e what is happening within the Tomcat engine), then they should configure a logging system such as java.util.logging or log4j as detailed next.

log4j

Tomcat 5.5 has done away with localhost_log which you may be familiar with as the runtime exception/stack trace log. These types of error are usually thrown by uncaught exceptions, but are still valuable to the developer. They can now be found in the stdout log.

If you need to setup cross-context detailed logging from within Tomcat's code, then you can use a simple log4j configuration. Note that this logging van be very verbose depending on the log level you chose to use. Note also that a log4j logging configuration is not going to produce stack trace type logging: those stack traces are output to stdout as discussed above.

Follow the following steps to setup a file named tomcat.log that has internal Tomcat logging output to it:

  1. Create a file called log4j.properties with the following content and save it into common/classes.
                log4j.rootLogger=debug, R
            log4j.appender.R=org.apache.log4j.RollingFileAppender
            log4j.appender.R.File=${catalina.home}/logs/tomcat.log
            log4j.appender.R.MaxFileSize=10MB
            log4j.appender.R.MaxBackupIndex=10
            log4j.appender.R.layout=org.apache.log4j.PatternLayout
            log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
            log4j.logger.org.apache.catalina=DEBUG, R
  2. Download Log4J (v1.2 or later) and place the log4j jar in $CATALINA_HOME/common/lib.
  3. Download Commons Logging and place the commons-logging.jar (not commons-logging-api.jar) in $CATALINA_HOME/common/lib with the log4j jar.
  4. Start Tomcat

This log4j configuration sets up a file called tomcat.log in your Tomcat logs folder with a maximum file size of 10MB and up to 10 backups. DEBUG level is specified which will result in the most verbose output from Tomcat.

You can (and should) be more picky about which packages to include in the logging. Tomcat 5.5 uses defines loggers by Engine and Host names. For example, for a default Catalina localhost log, add this to the end of the log4j.properties above. Note that there are known issues with using this naming convention (with square brackets) in log4j XML based configuration files, so we recommend you use a properties file as described until a future version of log4j allows this convention.

  • log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=DEBUG, R
  • log4j.logger.org.apache.catalina.core=DEBUG, R
  • log4j.logger.org.apache.catalina.session=DEBUG, R
Be warned a level of DEBUG will produce megabytes of logging and slow startup of Tomcat. This level should be used sparingly when debugging of internal Tomcat operations is required.

Your web applications should certainly use their own log4j configuration. This is valid with the above configuration. You would place a similar log4j.properties file in your web application's WEB-INF/classes folder, and log4j1.2.8.jar into WEB-INF/lib. Then specify your package level logging. This is a basic setup of log4j which does *not* require Commons-Logging, and you should consult the log4j documentation for more options. This page is intended only as a bootstrapping guide.

java.util.logging

In order to configure JDK logging you should have JDK 1.4+. Tomcat 5.5 is intended for JDK 5.0 or later, but can be run on JDK 1.4 using a compatibility package.

The default implemenatation of java.util.logging provided in the JDK is too limited to be useful. A limitation of JDK Logging appears to be the inability to have per-web application logging, as the configuration is per-VM. As a result, Tomcat will, in the default configuration, replace the default LogManager implementation with a container friendly implementation called JULI, which addresses these shortcomings. It supports the same configuration mechanisms as the standard JDK java.util.logging, using either a programmatic approach, or properties files. The main difference is that per-classloader properties files can be set (which enables easy redeployment friendly webapp configuration), and the properties files support slightly extended constructs which allows more freedom for defining handlers and assigning them to loggers.

JULI is enabled by default in Tomcat 5.5, and supports per classloader configuration, in addition to the regular global java.util.logging configuration. This means that logging can be configured at the following layers:

  • In the JDK's logging.properties file. Check your JAVA_HOME environment setting to see which JDK Tomcat is using (or maybe JRE 5.0 as Tomcat can now run on a JRE from version 5.5). The file will be in $JAVA_HOME/jre/lib. Alternately, it can also use a global configuration file located elsewhere by using the system property java.util.logging.config.file, or programmatic configuration using java.util.logging.config.class.
  • In each classloader using a logging.properties file. This means that it is possible to have a configuration for the Tomcat core, as well as separate configurations for each webapps which will have the same lifecycle as the webapps.

The default logging.properties specifies a ConsoleHandler for routing logging to stdout and also a FileHandler. A handler's log level threshold can be set using SEVERE, CONFIG, INFO, WARN, FINE, FINEST or ALL. The logging.properties shipped with JDK is set to INFO. You can also target specific packages to collect logging from and specify a level. Here is how you would set debugging from Tomcat. You would need to ensure the ConsoleHandler's level is also set to collect this threshold, so FINEST or ALL should be set. Please refer to Sun's java.util.logging documentation for the complete details.

org.apache.catalina.level=FINEST

The configuration used by JULI is extremely similar, but uses a few extensions to allow better flexibility in assigning loggers. The main differences are:

  • A prefix may be added to handler names, so that multiple handlers of a single class may be instantiated. A prefix is a String which starts with a digit, and ends with '.'. For example, 22foobar. is a valid prefix.
  • As in Java 5.0, loggers can define a list of handlers using the loggerName.handlers property.
  • By default, loggers will not delegate to their parent if they have associated handlers. This may be changed per logger using the loggerName.useParentHandlers property, which accepts a boolean value.
  • The root logger can define its set of handlers using a .handlers property.
  • System property replacement for property values which start with ${sytstemPropertyName}.

Example logging.properties file to be placed in common/classes:

handlers = 1catalina.org.apache.juli.FileHandler, 2localhost.org.apache.juli.FileHandler, \
           3manager.org.apache.juli.FileHandler, 4admin.org.apache.juli.FileHandler, \
           java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.FileHandler.level = FINE
1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.FileHandler.prefix = catalina.

2localhost.org.apache.juli.FileHandler.level = FINE
2localhost.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.FileHandler.prefix = localhost.

3manager.org.apache.juli.FileHandler.level = FINE
3manager.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.FileHandler.prefix = manager.

4admin.org.apache.juli.FileHandler.level = FINE
4admin.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
4admin.org.apache.juli.FileHandler.prefix = admin.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
   2localhost.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = \
   3manager.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].handlers = \
   4admin.org.apache.juli.FileHandler

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Example logging.properties for the servlet-examples web application to be placed in WEB-INF/classes inside the web application:

handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = servlet-examples.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

Handler Properties

Tomcat's JULI implementation is not intended to be a fully-featured logging libary, only a simple bridge to those libraries. However, JULI does provide several properties for configuring the its handlers. These are listed below.

FileHandler
Attribute Description
directory

The directory where the log file will be written. The Tomcat server account should have write permissions to this directory. The default value of this property is logs.

prefix

The log file name prefix. This is the portion of the log file name before the date. The default value of this property is juli..

suffix

The log file name suffix. This is the portion of the log file name after the date. The default value of this property is .log.

level

The threshold level for this handler. It must be one of the levels in the java.util.logging.Level class. The default value of this property is ALL. Messages whose level is below the specified level will not be written to the file.

filter

The fully-qualified class name of a class that implements the java.util.logging.Filter interface. JULI will load this class and associate it with this handler to filter its messages. By default, there is no Filter associated with the handler.

formatter

The fully-qualified class name of a class that implements the java.util.logging.Formatter interface. JULI will load this class and associate it with this handler to format its messages. By default, there is no Formatter associated with the handler.


Apache Tomcat 5.5 Servlet/JSP 容器 - Manager App HOW-TO

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Manager App HOW-TO

 Printer Friendly Version
print-friendly
version
Table of Contents

简介
配置管理员程序存取( Configuring Manager Application Access)
被支持的管理员命令(Supported Manager Commands)

远程部署新的应用程序(Deploy A New Application Remotely)
从局部路径部署新的应用程序(Deploy A New Application from a Local Path)
列出当前被部署的应用程序（ List Currently Deployed Applications）
重新装载现有的应用程序(Reload An Existing Application)
列出OS和Java虚拟器(JVM)的属性(List OS and JVM Properties)
列出可用的全球性JNDI资源( List Available Global JNDI Resources)
列出可用的安全性功能(List Available Security Roles)
Session统计(Session Statistics)
启动一个现有的应用程序(Start an Existing Application)
停止运行一个现有的应用程序(Stop an Existing Application)
反部署一个现有的应用程序( Undeploy an Existing Application)
使用Ant执行管理员命令( Executing Manager Commands With Ant)
使用JMX代理Servlet( Using the JMX Proxy Servlet)
什么是JMX代理Servlet?(What is JMX Proxy Servlet?)
查询命令(Query command)
设置命令(Set command)

Introduction

在许多生产环境(production environments)里，这种能力很重要，那就是在不需要关闭和重新启动整个容器的情况下能够部署一个新的web程序，或者反部署一个现有的程序。另外, 你能要求一个现有应用程序再装载它自己，既使你还没有在Tomcat 5服务器配置文件里声明它是可以被重新装载的(reloadable)。

为了支持这种能力，Tomcat 5包含了一个web程序(默认安装在context path /manager上),它支持以下这些功能:

  • 从上载的(uploaded)WAR文件内，把新的web程序部署到指定的context path上去。
  • Deploy a new web application, on a specified context path, from the server file system.
  • 列出当前部署的web程序，以及这些web程序的活跃着的sessions。
  • 重新装载现有的web程序，以反映出/WEB-INF/classes 或 /WEB-INF/lib 里内容的更改。
  • 列出OS和Java虚拟器(JVM)属性值(property values)。
  • 列出可使用的全球性JNDI资源, 供给正在准备&lt;ResourceLink&gt；套嵌在&lt;Context&gt 的元素；部署描述的开发工具使用。
  • 列出用户数据库里定义的可用安全性功能。
  • 启动运行一个被停止了的程序(让它可再被使用)。
  • 停止一个现有的程序(这样它就变成不可被使用)，但是不undeploy它。
  • Undeploy a deployed web application and delete its document base directory (unless it was deployed from file system).

有两种方式来配置Manager网络应用程序Context：

  • 把manager.xml context配置文件安装在$CATALINA_HOME/conf/[enginename]/[hostname]文件夹里。
  • 在Tomcat server.xml 配置文件的主机配置(Host configuration)中来配置the Manager Context。下面是一个例子：
    &lt;Context path="/manager" debug="0" privileged="true"
docBase="/usr/local/kinetic/tomcat5/server/webapps/manager"&gt;
&lt;/Context&gt;

如果你把Tomcat配置成可支持多个网站，你就需要为每一个网站单独配置一个管理员(Manager)。

有三种方法来使用管理员(manager)网络应用程序：

  • 作为使用在浏览器上用户接口(user interface)的程序。下面是一个关于URL的例子，这里你可以用你的网站的名字来取代局部主机(localhost): http://localhost/manager/html/。
  • 作为一个使用HTTP(超文本传输协议)请求的小版本程序，它只适合系统管理员用于scripts设置。命令作为这个request URI的一部分给出，并且反应(responses)是那种容易被解析(parsed)和处理的简单文本的形式。更多信息参看被支持的管理员命令( Supported Manager Commands)。
  • 作为Ant(1.4以及其后版本)建造工具的一套简易的task定义。更多信息请参看Executing Manager Commands With ant 。

Tomcat 5的未来版本将包括下面这些形式的管理功能:

  • 作为网络服务，这样Tomcat管理就很容易地整合到远程/或者非Java的管理环境中去。
  • 作为一种具有较好user interface的网络程序(建立在网络服务过程的顶层)，可方便Tomcat通过web浏览器进行管理。

Configuring Manager Application Access

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

如果Tomcat里的默认设置允许互联网上的任何人在你的服务器上执行管理员程序(the Manager application)，那就相当不安全了。因此，管理员程序要求每一个使用它的人通过使用带有管理员(manager)角色的用户名称和密码证实它们自己的身份。更进一步，在默认的用户文件中($CATALINA_HOME/conf/tomcat-users.xml)没有用户名称被指派这个角色。因此，以默认的形式是完全不可能访问管理员程序的。

为了能进入管理员程序进行存取，你必须产生一个新的用户名称/密码组合，并把它们与管理员(manager)角色联系在一起，或者把管理员(manager)角色添加给现有的用户名称/密码组合。在什么确切的地方做上面这些工作依赖于你使用了哪个Realm implementation ：

  • MemoryRealm ——别如果你还没有客户化$CATALINA_HOME/conf/server.xml，就选择另外一个文件，Tomcat 5默认选用存放在$CATALINA_HOME/conf/tomcat-users.xml里的一个XML-格式的文件，它可以由任何文字编辑器(text editor)来编辑。这个文件为每一个用户包括了一个XML &lt;user&gt;，它看上去可能象这样：
    &lt;user name="craigmcc" password="secret" roles="standard,manager" /&gt;
    它定义了用于个人登录使用的用户名称和密码，以及他(她)们相关联的角色名称。你可以给现有的一个或多个用户添加“管理员(manager)”角色，或者产生具有管理员角色的新用户。
  • JDBCRealm —— 关于用户以及其角色的信息被存放在数据库里，通过JDBC(Java数据库连接)进行存取。按照你使用的工作环境里的标准手续来给一个或多个现有用户添加“管理员(manager)"职责，或者产生一个或多个具有管理员角色的新用户。
  • JNDIRealm —— 关于用户以及其角色的信息被存放在目录服务器上，通过LDAP进行存取。按照你使用的工作环境里的标准手续来给一个或多个现有用户添加“管理员(manager)”职责，或者产生一个或多个具有管理员角色的新用户。

当你第一次试图发布一个下个章节将要描述的Manager命令时，你会被要求用BASIC认证来登入。不管你输入什么用户名称和密码，只要它们是能被用户数据库识别的具有管理员(manager)角色的用户就行。

除了密码制约之外，在远程IP地址或主机上增加RemoteAddrValve或者RemoteHostValve也可以对管理员网络程序进行限制。下面的例子是通过IP地址对进出局部主机(localhost)进行限制:

&lt;Context path="/manager" debug="0" privileged="true"
docBase="/usr/local/kinetic/tomcat5/server/webapps/manager"&gt;
&lt;Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127.0.0.1"/&gt;
&lt;/Context&gt;

Supported Manager Commands

管理员程序的所有命令都是由象这样的单个request URI指定(它的格式如下):

http://{host}:{port}/manager/{command}?{parameters}

这里{host}和{port}代表主机名称和Tomcat运行的端口(port)数目，{command}代表你想要执行的管理员命令，{parameters}代表那个命令特有的查询参数。在下面的说明里，把主机和端口适当地客户化以便进行安装。

多数命令接受以下一个或多个查询参量:

  • 路径(path)——你将要处理的网络应用程序的上下文路径(包括前面的“/”)。要选择the ROOT网络应用程序，指定"/"。注意——不可能仅仅在管理员程序自身就能执行管理命令。
  • 网络应用程序档案(war)—— 网络应用程序档案文件的统一资源定位器(URL)，包含网络程序的目录的路径名称，或者是一个Context configuration ".xml" 文件。你可以以下面任何格式使用URLs:
    • file:/absolute/path/to/a/directory ——这是通向包含未包装版的网络程序目录的绝对路径。这个目录可以附加在你指定的context path上，而不需要任何改变。
    • file:/absolute/path/to/a/webapp.war —— 这是通向网络应用档案(WAR)文件的绝对路径。这仅仅对/deploy 命令有效，也是这个命令唯一被接受的格式。
    • jar:file:/absolute/path/to/a/warfile.war!/ —— 这是通向局部网络应用档案(WAR)文件的URL。你可以使用任何对JarURLConnection class有效的语法来代指一整个JAR文件。
    • file:/absolute/path/to/a/context.xml —— 这是通向网络应用上下文配置 ".xml"文件的绝对路径，这个".xml"文件包含有上下文配置元素。
    • directory (目录)—— 主机的应用基础目录中各种web程序内容的子目录名称。
    • webapp.war —— 这是网络程序war文件的名称，它被放置在主机的应用基础目录上。

每个命令都会产生一个text/plain 形式的反应(response)(例如，简单的ASCII而没有HTML修饰)，使它能容易地被人或机器阅读。反应(response)的第一行通常以OK(可以)或者FAIL(失败)开始，表明了这个请求命令被成功执行与否。如果出现失败，第一行的剩余部分会描述你所遇到的问题。下面将描述一些命令及其额外的信息。

Internationalization Note(国际化注意事项):管理员程序从资源束(resource bundles)里查看消息字串(message strings)，所以有可能这些字串已被翻译过以适用于你的工作平台。下面的例子显示的是英文版的消息(messages)。

警告：以前使用的命令 /install 和 /remove 不再被使用了。它们现在等同于/deploy 和 /undeploy命令，在以后的发行版中可能会被删除掉。

Deploy A New Application Remotely
http://localhost:8080/manager/deploy?path=/foo

上装(Upload)在HTTP PUT request里特指的WAR文件，然后把它安装在相应的虚拟主机(virtual host)的appBase目录上，在路径请求参数特指的context path 上启动运行。如果没有指定路径，那么目录名称或者不带有.war 扩展名的WAR文件名称就被当作路径。这个应用程序在以后可以通过使用/undeploy 被取消部署(相关的程序目录也会被删除)。

这个.WAR 文件可以通过在/META-INF/context.xml里包含一个上下文配置XML 文件来包括 Tomcat特指的部署配置。

URL参数包括：

  • 更新(update)：当被设置为正确(true)时，已有的更新参数会被首先取消部署。默认值是被设为错误(false)。
  • 标志(tag)：指定一个标志名称，这样允许把版本数目与被部署的网络程序相关联。以后可以只用标志(tag)就可以重新部署这个版本的程序。

注意 —— 这个命令在逻辑上和/undeploy命令相反。

如果安装和启动成功，你会收到象下面这种回应：

OK - Deployed application at context path /foo

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 应用程序已经存在于path /foo

    所有当前运行的网络程序的context paths 必须是独特（彼此不同）的。因此，你必须取消部署现有的使用这个context path的网络程序，或者为新程序选择一个不同的context path 。update参数必须指定为URL上的一个参数，为避免错误，把参数值设为true 。这样，在部署新程序前会对现有程序执行取消部署。

  • 遇到异常

    当试图启动新程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)，不过通常的解释多为在语法分析(parsing)/WEB-INF/web.xml 文件时遇到问题，或者是在初始化程序事件(event)监听器(listeners)或过滤器(filters)遇到了缺失的类(missing classes)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • 没有指定上下文路径
    路径参数是必需的。
Deploy A New Application from a Local Path

安装和启动一个新的网络程序，把它和特定的上下文路径相连(这个上下文路径不能被其他网络程序使用)。这个命令(指deploy)与/undeploy 命令在逻辑意义上相反。

有许多种不同的办法来使用deploy命令:

部署一个以前被部署过的网络程序版本

这可以用来部署一个以前版本的网络程序，这个程序曾被使用标志(tag)属性部署过。注意，管理员程序的工作目录必须包含以前部署过的WARs；删除它会使得这里的部署失败。

http://localhost:8080/manager/deploy?path=/footoo&amp;tag=footag

通过URL部署一个目录或者WAR

部署Tomcat服务器上的网络程序目录或者".war"文件。如果没有指定路径(path)，那么目录名称或者不带有".war"扩展名的WAR文件名称就被当作路径。网络应用程序档案(war)参数为每个目录或WAR文件指定了URL(包括文件: scheme)。关于URL指向WAR文件的语法在Javadocs页面java.net.JarURLConnection class里有描述。只能使用那些指向全部(entire)WAR文件的URL。

在下面的这个例子里，位于Tomcat服务器/path/to/foo目录里的网络程序被部署为一个名叫/footoo 的网络程序context。

http://localhost:8080/manager/deploy?path=/footoo&amp;war=file:/path/to/foo

在下面的这个例子里，位于Tomcat服务器上的".war"文件/path/to/bar.war被部署为一个名叫/bar 的网络程序context。注意，这里没有path参数，所以在默认的情况下，context path指向不带有".war"扩展名的网络应用程序档案文件。

http://localhost:8080/manager/deploy?war=jar:file:/path/to/bar.war!/

在主机的appBase部署一个目录或War文件

在主机的appBase目录里部署一个网络程序目录或".war"文件。如果没有指定路径(path)，那么目录名或者不带有".war"扩展符的WAR文件名称就被当作路径。

在下面的这个例子里，位于Tomcat服务器主机appBase目录下的子目录foo里面的网络程序被部署为叫作/foo 的网络程序context。注意，这里没有path参数，所以在默认的情况下，context path指向网络程序目录名。

http://localhost:8080/manager/deploy?war=foo

在下面的这个例子里，位于Tomcat服务器主机appBase目录里的".war"文件bar.war被部署为名叫/bartoo 的网络程序context。

http://localhost:8080/manager/deploy?path=/bartoo&amp;war=bar.war

使用上下文语境配置".xml"文件进行部署

如果主机(Host) deployXML旗标被设置为正确(true)，你可以用上下文语境配置".xml"文件，或者".war"文件，或者程序目录来部署你的网络程序。当使用上下文语境配置".xml"文件来部署网络程序时，不需要使用context path。

一个上下文语境配置".xml"文件可包括有效的网络程序上下文XML文件，就象在Tomcat server.xml 配置文件里被配置过一样。下面是个示例：

&lt;Context path="/foobar" docBase="/path/to/application/foobar"
debug="0"&gt;

&lt;!-- Link to the user database we will get roles from --&gt;
&lt;ResourceLink name="users" global="UserDatabase"
type="org.apache.catalina.UserDatabase"/&gt;

&lt;/Context&gt;

当可任选的网络应用程序档案(war)参数被设置指向一个web程序的".war"文件或目录的URL时,它会取代任何在上下文配置".xml"文件里配置的docBase 。

这里是使用上下文语境配置".xml"文件部署一个应用程序的例子。

http://localhost:8080/manager/deploy?config=file:/path/context.xml

这个例子是使用上下文语境配置".xml"文件和一个位于服务器上的".war"文件来部署一个应用程序。

http://localhost:8080/manager/deploy?config=file:/path/context.xml&amp;war=jar:file:/path/bar.war!/

部署注意事项

如果主机(Host)配置为unpackWARs=true ，并且你部署了一个war文件，那么，这个war文件就会被unpacked到主机的appBase目录上。

如果war文件或者目录被安装到主机的appBase目录上，并且主机被配置为autoDeploy=true 或者liveDeploy=true ，那么Context path 必须与目录名或不带有".war"扩展符的war文件名相配。

因为安全原因，当不可靠用户来管理网络程序时，主机的deployXML旗标可以设置为false 。这就使不可靠用户不能够使用配置XML文件来部署web程序，也不能部署位于主机appBase之外的目录或".war"文件。

部署回应

如果安装和启动成功，你会收到象下面这种回应：

OK - Deployed application at context path /foo

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 应用程序已经存在于path /foo

    所有当前运行的网络程序的context paths 必须是独特（彼此不同）的。因此，你必须取消部署现有的使用这个context path的网络程序，或者为新程序选择一个不同的context path 。update参数必须指定为URL上的一个参数，为避免错误，把参数值设为true 。这样，在部署新程序前会对现有程序执行取消部署。

  • 文档base不存在或者是一个不可读取的目录

    由网络应用程序档案(war)参数指定的URL必须识别这个服务器上包含"unpacked"版本的网络程序目录，或者包含这个程序的网络应用程序档案(WAR)的绝对URL。修正这个网络应用程序档案(war)参数指定值。

  • 遇到异常

    当试图启动新程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)，不过通常的解释多为在语法分析(parsing)/WEB-INF/web.xml 文件时遇到问题，或者是在初始化程序事件(event)监听器(listeners)或过滤器(filters)遇到了缺失的类(missing classes)。

  • 指定的程序URL无效

    你为目录或网络程序指定的URL是无效的。这样的URL必须以“file:”开始，为WAR文件提供的URL必须以".war"结束。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • 上下文路径必须与目录名或WAR文件名相配
    如果war文件或者目录被安装到主机的appBase目录上，并且主机被配置为autoDeploy=true 或者liveDeploy=true ，那么Context path 必须与目录名或不带有".war"扩展符的war文件名相配。
  • 只有在主机网络程序目录里的web程序才能被安装
    如果主机的deployXML旗标被设为false，要是试图部署位于主机appBase目录之外的网络程序目录或".war"文件，就会出现错误。
List Currently Deployed Applications
http://localhost:8080/manager/list

列出所有当前被部署过的程序的context paths，当前状态(运行中的或停止的)，以及活动会话(active sessions)数目。在启动Tomcat后马上出现的典型回应可能象这样：

OK - Listed applications for virtual host localhost
/webdav:running:0
/examples:running:0
/manager:running:0
/:running:0
Reload An Existing Application
http://localhost:8080/manager/reload?path=/examples

向一个现有的程序发出信号去把它自己关闭然后再重新装载。当程序的context不能够被重新装载，但你/WEB-INF/classes目录中有更新过的类或属性文件，或者在/WEB-INF/lib目录中添加或更新过jar文件，上面这个办法就很有用。

注意 —— /WEB-INF/web.xml 网络程序配置文件不能在被重新装载时被再次读取。如果你更改了web.xml文件，你必须停止运行，然后再启动网络程序。

如果这个命令成功，你会看到象下面这样的回应：

OK - Reloaded application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图重新启动网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
  • 在path /foo上部署的WAR文件不支持重新装载
    目前，当网络程序从一个WAR文件直接被部署时，程序的重新装载(拾起classes 或 web.xml文件里的更改)就不被支持。重新装载仅仅适用于那些从未包装目录那里部署的程序。如果你在使用WAR文件，要拾起(pick up)那些更改，你应该先undeploy(旧的文件)，然后再deploy这个程序，或者以update的参数来部署这个程序。
List OS and JVM Properties
http://localhost:8080/manager/serverinfo

列出关于Tomcat版本，OS, 和 JVM属性的信息。

如果出现错误，回应(response)将是以FAIL开头的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    在枚举系统属性时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

List Available Global JNDI Resources
http://localhost:8080/manager/resources[?type=xxxxx]

列出可用于上下文配置文件资源链接(resource links)的全球性JNDI资源。如果你指定类型请求参数(type request parameter)，参数值必须是你所感兴趣的资源类型中完全合格的Java class name(例如，你得要指定javax.sql.DataSource 来取得所有可用的JDBC数据源的名称)。如果你没有指定类型请求参数，所有类型的资源将被返回。

依赖于类型请求参数(type request parameter)被指定与否，通常回应的第一行会是这样：

OK - Listed global resources of all types

or

OK - Listed global resources of type xxxxx

然后是每一行对应一个资源。每一行由以冒号(":")为界限的如下区域组成：

  • 全球性资源名称(Global Resource Name) —— 全球性JNDI资源的名称，它将被用在&lt;ResourceLink&gt;元素的全球性属性中。
  • 全球性资源类型(Global Resource Type)—— 全球性JNDI资源的完全合格的Java class 名称。

如果出现错误，回应(response)将是以FAIL开头的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    在枚举全球性JNDI资源时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 全球性JNDI资源不存在

    你在运行的Tomcat服务器没有被配置全球性JNDI资源。

List Available Security Roles
http://localhost:8080/manager/roles

列出在org.apache.catalina.UserDatabase资源里的安全性能名称(以及相应的描述)，这个资源与Manager网络程序里web.xml文件中的用户资源索引相链连。例如，这通常会被那些想要产生 &lt;security-role-ref&gt;元素的部署工具使用，而&lt;security-role-ref&gt;元素是用来映射网络程序里的安全性能名称和容器里实际上被定义的角色名称的。

在默认的情况下，用户资源索引指向全球性UserDatabase资源。如果你选择让每个虚拟器使用不同的用户数据库，你应该修改默认的manager.xml 配置文件里的&lt;ResourceLink&gt; 元素，让它指向这个虚拟器的全球性用户数据库资源。

当这个命令被执行后，回应的第一行是这样的：

OK - Listed security roles

然后是每一行对应一个安全性能。每一行由以冒号(":")为界限的如下区域组成：

  • 安全性能名称(Security Role Name)——用户数据库里Tomcat所知道的安全性能名称。
  • 描述(Description)——关于这个安全性能的描述(对于产生选定功能的用户界面有用)

如果出现错误，回应(response)将是以FAIL开头的一段错误消息。产生错误的可能原因包括：

  • Cannot resolve user database reference —— 一个JNDI错误，阻止了成功查询org.apache.catalina.UserDatabase 资源。关于这类错误，请查看Tomcat log 文件的stack trace 。
  • No user database is available —— 你还没有为用户资源配置一个可以指向适当的用户数据库实例(instance)的资源索引。检查一下你的manager.xml文件，确保你为这个资源产生了一个适合的&lt;ResourceLink&gt;或&lt;ResourceParams&gt;元素。
Session Statistics
http://localhost:8080/manager/sessions?path=/examples

显示一个网络程序的默认session timeout，以及在实际timeout时间十分钟左右范围里的活动sessions数目。例如，在重新启动Tomcat和执行/examples程序里的一个JSP样本以后，你可能会得到象下面这样的东西：

OK - Session information for application at context path /examples
Default maximum session inactive interval 30 minutes
30 - &lt;40 minutes:1 sessions
Start an Existing Application
http://localhost:8080/manager/start?path=/examples

向一个被停止运行的程序发出重新启动的信号，使它可以再被使用。停止和启动(这两个命令)是有用处的，例如，在你的程序所必需的数据库临时unavailable时。通常停止运行依赖于这个数据库的程序，比起让用户不断地遇到数据库异常要好一些。

如果这个命令成功，你会看到象下面这样的回应：

OK - Started application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图启动网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
Stop an Existing Application
http://localhost:8080/manager/stop?path=/examples

向一个现有的程序发出信号，使它自己变成不能被使用，但让它还是被部署着。当一个程序被停止运行，任何一个进来的请求都会看到一个HTTP错误404，而且在执行list applications命令时，这个程序会显示为"stopped"。

如果这个命令成功，你会看到象下面这样的回应：

OK - Stopped application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图停止运行网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
Undeploy an Existing Application
http://localhost:8080/manager/undeploy?path=/examples

警告：这个命令将会删除存在于虚拟主机appBase 目录下的(典型名称叫做"webapps")任何web程序内容。也会删除源代码.WAR文件， 如果存在的话。这个appBase目录的内容或者是从未包装的程序部署过来的， 或者是.WAR 扩展而来的，它还包括$CATALINA_HOME/conf/[enginename]/[hostname]/ 目录里的XML Context定义。 如果你仅仅只想让程序停止工作，你就使用/stop命令。

向一个现有的程序发出关闭信息，把它自己从Tomcat里删除(这就使得这个context path以后可以被再使用)。另外，存在于虚拟主机appBase目录(典型名称 "webapps")上的文件根目录(document root directory)也被删除掉了。这个命令在逻辑上和/deploy 命令相反。

如果这个命令成功，你会看到象下面这样的回应：

OK - Undeployed application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图取消部署网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
Executing Manager Commands With Ant

除了象上面所讲的可以通过HTTP请求来执行Manager命令，Tomcat 5还包括了一套使用方便的Ant(1.4及其后版本)构造工具的任务定义。为了能够使用这些命令，你必须进行下面的操作设置：

  • 从http://ant.apache.org下载Ant的binary distribution 。你必须使用1.4或其后版本。
  • 把Ant distribution 安装在一个方便的目录(在这个说明的其余部分被称作ANT_HOME)。
  • 把文件server/lib/catalina-ant.jar从Tomcat 5安装复制到Ant的library目录($ANT_HOME/lib)。
  • 把$ANT_HOME/bin目录添加到PATH环境变量中。
  • 在Tomcat具有管理员(manager)角色的用户数据库里至少配置一个用户名/密码组合。

要在Ant里使用客户化的任务，你必须事先用&lt;taskdef&gt;元素对它们进行声明。因此，你的build.xml文件看起来会象这样：

&lt;project name="My Application" default="compile" basedir="."&gt;

&lt;!-- Configure the directory into which the web application is built --&gt;
&lt;property name="build" value="${basedir}/build"/&gt;

&lt;!-- Configure the context path for this application --&gt;
&lt;property name="path" value="/myapp"/&gt;

&lt;!-- Configure properties to access the Manager application --&gt;
&lt;property name="url" value="http://localhost:8080/manager"/&gt;
&lt;property name="username" value="myusername"/&gt;
&lt;property name="password" value="mypassword"/&gt;

&lt;!-- Configure the custom Ant tasks for the Manager application --&gt;
&lt;taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"/&gt;
&lt;taskdef name="list" classname="org.apache.catalina.ant.ListTask"/&gt;
&lt;taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"/&gt;
&lt;taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask"/&gt;
&lt;taskdef name="roles" classname="org.apache.catalina.ant.RolesTask"/&gt;
&lt;taskdef name="start" classname="org.apache.catalina.ant.StartTask"/&gt;
&lt;taskdef name="stop" classname="org.apache.catalina.ant.StopTask"/&gt;
&lt;taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/&gt;

&lt;!-- Executable Targets --&gt;
&lt;target name="compile" description="Compile web application"&gt;
&lt;!-- ... construct web application in ${build} subdirectory, and
generated a ${path}.war ... --&gt;
&lt;/target&gt;

&lt;target name="deploy" description="Install web application"
depends="compile"&gt;
&lt;deploy url="${url}" username="${username}" password="${password}"
path="${path}" war="${build}${path}.war"/&gt;
&lt;/target&gt;

&lt;target name="reload" description="Reload web application"
depends="compile"&gt;
&lt;reload url="${url}" username="${username}" password="${password}"
path="${path}"/&gt;
&lt;/target&gt;

&lt;target name="undeploy" description="Remove web application"&gt;
&lt;undeploy url="${url}" username="${username}" password="${password}"
path="${path}"/&gt;
&lt;/target&gt;

&lt;/project&gt;

现在，你可以执行象ant deploy这样的命令向运行的Tomcat实例部署应用程序，或者用ant reload来告诉Tomcat对程序进行重新装载。请注意，在build.xml文件中大多数有趣的参数值都被定义为可被替换的属性，这样一来你可以从命令行来替代(override)它们的参数值。例如，你可能认为把真实管理员密码写在build.xml的源代码里会对安全性能造成危险。为避免这样，你可以忽略密码这个属性，然后从命令行来指定它：

ant -Dpassword=secret deploy
Tasks output capture

使用Ant 1.6.2或其后版本，Catalina tasks在属性文件或外部文件里提供捕捉它们的输出信息的选项。 它们直接支持下列<redirector>类型attributes的下属属性：

属性 | 描述 | 是否必要
output | 向其进行输出的文件名。如果error stream没有被重新指向一个文件或属性，那么它就出现在这里。 | No
error | 标准的错误信息输出命令应该指向这个文件。 | No
logError | This attribute is used when you wish to see error output in Ant's log and you are redirecting output to a file/property. The error output will not be included in the output file/property. If you redirect error with the error or errorProperty attributes, this will have no effect. | No
append | 输出和错误文件是否应该被附加上或被overwritten。默认设置是false。 | No
createemptyfiles | 即使在输出和错误文件是empty时，它是否应该被产生。默认设置是true。 | No
outputproperty | The name of a property in which the output of the command should be stored. Unless the error stream is redirected to a separate file or stream, this property will include the error output. | No
errorproperty | The name of a property in which the standard error of the command should be stored. | No

A couple of additional attributes can also be specified:

属性 | 描述 | 是否必要
alwaysLog | This attribute is used when you wish to see the output you are capturing, appearing also in the Ant's log. It must not be used unless you are capturing task output. Defaults to false. This attribute will be supported directly by <redirector> in Ant 1.6.3 | No
failonerror This attribute is used when you wish to avoid that any manager command processing error terminates the ant execution. Defaults to true. It must be set to false, if you want to capture error output, otherwise execution will terminate before anything can be captured.
This attribute acts only on manager command execution, any wrong or missing command attribute will still cause Ant execution termination. 		No

They also support the embedded <redirector> element in which you can specify its full set of attributes, but input, inputstring and inputencoding that, even if accepted, are not used because they have no meaning in this context. Refer to ant manual for details on <redirector> element attributes.

Here is a sample build file extract that shows how this output redirection support can be used:

    <target name="manager.deploy"
        depends="context.status"
        if="context.notInstalled">
        <deploy url="${mgr.url}"
            username="${mgr.username}"
            password="${mgr.password}"
            path="${mgr.context.path}"
            config="${mgr.context.descriptor}"/>
    </target>

    <target name="manager.deploy.war"
        depends="context.status"
        if="context.deployable">
        <deploy url="${mgr.url}"
            username="${mgr.username}"
            password="${mgr.password}"
            update="${mgr.update}"
            path="${mgr.context.path}"
            war="${mgr.war.file}"/>
    </target>

    <target name="context.status">
        <property name="running" value="${mgr.context.path}:running"/>
        <property name="stopped" value="${mgr.context.path}:stopped"/>

        <list url="${mgr.url}"
            outputproperty="ctx.status"
            username="${mgr.username}"
            password="${mgr.password}">
        </list>

        <condition property="context.running">
            <contains string="${ctx.status}" substring="${running}"/>
        </condition>
        <condition property="context.stopped">
            <contains string="${ctx.status}" substring="${stopped}"/>
        </condition>
        <condition property="context.notInstalled">
            <and>
                <isfalse value="${context.running}"/>
                <isfalse value="${context.stopped}"/>
            </and>
        </condition>
        <condition property="context.deployable">
            <or>
                <istrue value="${context.notInstalled}"/>
                <and>
                    <istrue value="${context.running}"/>
                    <istrue value="${mgr.update}"/>
                </and>
                <and>
                    <istrue value="${context.stopped}"/>
                    <istrue value="${mgr.update}"/>
                </and>
            </or>
        </condition>
        <condition property="context.undeployable">
            <or>
                <istrue value="${context.running}"/>
                <istrue value="${context.stopped}"/>
            </or>
        </condition>
    </target>

WARNING: even if it doesn't make many sense, and is always a bad idea, calling a Catalina task more than once, badly set Ant tasks depends chains may cause that a task be called more than once in the same Ant run, even if not intended to. A bit of caution should be exercised when you are capturing output from that task, because this could lead to something unexpected:

  • when capturing in a property you will find in it only the output from the first call, because Ant properties are immutable and once set they cannot be changed,
  • when capturing in a file, each run will overwrite it and you will find in it only the last call output, unless you are using the append="true" attribute, in which case you will see the output of each task call appended to the file.

Using the JMX Proxy Servlet
What is JMX Proxy Servlet
JMX Proxy Servlet是用来获取和设置Tomcat内部组织的轻型代理。(或者任何通过MBean被exposed过的类)。 它的用法对客户来说不方便，但是它的UI对于整合命令行scripts来监督和改变Tomcat内部组织很有帮助。你可以用代理来做两件事：获取信息和设置信息。你必须对JMX有个基本了解才能真正理解JMX Proxy Servlet。如果你不知道JMX是什么，那你就会感到迷惑。
JMX Query command
以这种形式：
http://webserver/manager/jmxproxy/?qry=STUFF
这里STUFF是你想要执行的查询(query)。例如，这里是一些你想要运行的查询(queries)：
  • qry=*%3Atype%3DRequestProcessor%2C* --> type=RequestProcessor 找出所有的可以处理请求以及汇报它们的状态的 workers 。
  • qry=*%3Aj2eeType=Servlet%2c* --&gt; j2eeType=Servlet 会返回所有装载的servlets。
  • qry=Catalina%3Atype%3DEnvironment%2Cresourcetype%3DGlobal%2Cname%3DsimpleValue --&gt; Catalina:type=Environment,resourcetype=Global,name=simpleValue 由所给出的名字查看一个特定的MBean。
你得要真正试一试这些查询(queries)才能真正知道它的能力。如果你没有提供qry参数，那么所有的MBeans就会被显示出来。我们极力建议你先去读一读tomcat源代码并弄懂JMX规范，这样你就会更好地理解你运行的那些queries了。
JMX Set command
你可以查询一个MBean,现在是"搅乱"Tomcat内部组织的时候了! 这个set命令的一般形式是:
http://webserver/manager/jmxproxy/?set=BEANNAME&amp;att=MYATTRIBUTE&amp;val=NEWVALUE
这样,你必须提供三个请求参数:
  1. set: 完整的bean名字
  2. att: 你想要改变的特性(attribute)
  3. val: 新的值
如果所有都顺利，机器就会说OK，不然就会出现一段错误消息。例如，我们想要打开ErrorReportValve的排错(debugging)功能，下面将把debugging值设为10:
http://localhost:8080/manager/jmxproxy/
?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost&amp;att=debug&amp;val=10
所得结果是(YMMV):
Result: ok
如果我传送一个坏的值，就会看到下面这种情况。这里我是使用的URL，我把debugging值设为'cowbell':
http://localhost:8080/manager/jmxproxy/
?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost&amp;att=debug&amp;val=cowbell
当试着执行它时，结果是：
Error: java.lang.NumberFormatException: For input string: "cowbell"


Apache Tomcat 5.5 Servlet/JSP 容器 - MBean 描述说明

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

MBean 描述说明

 Printer Friendly Version
print-friendly
version
简介

Tomcat 可以使用 JMX 的 MBeans 来实现Tomcat性能管理。

Java包里的 mbeans-descriptor.xml 是 Catalina 的 MBeans 描述。

为了避免"ManagedBean is not found"异常，你需要为你自己的组件添加MBean描述。

增加 MBean 描述

你可以在 mbeans-descriptor.xml 为你自己写的组件添加 MBean 描述，mbeans-descriptor.xml 应该在要描述的Java类同一个目录里，与所在的包一致。请看下面例子：

&lt;mbean name="LDAPRealm"
className="org.apache.catalina.mbeans.ClassNameMBean"
description="Custom LDAPRealm"
domain="Catalina"
group="Realm"
type="com.myfirm.mypackage.LDAPRealm"&gt;

&lt;attribute name="className"
description="Fully qualified class name of the managed object"
type="java.lang.String"
writeable="false"/&gt;

&lt;attribute name="debug"
description="The debugging detail level for this component"
type="int"/&gt;
.
.
.

&lt;/mbean&gt;


Apache Tomcat 5.5 Servlet/JSP 容器 - Monitoring and Managing Tomcat

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Monitoring and Managing Tomcat

 Printer Friendly Version
print-friendly
version
前言

监视服务器运行状况对于今天的网路来说已经变得越来越重要。监视服务器的运行，获取统计资料， 修改服务器设置是系统管理员的日常工作。

激活 JMX 遥控器

下列Sun的网站包括了一个 Java 5 版本里 设置 JMX 遥控器的选项： http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html.

这里给你的是一个快速简单的安装步骤：

在你的 Tomcat 的启动程序里加入以下几行：

    set CATALINA_OPTS="-Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=%my.jmx.port% \
    -Dcom.sun.management.jmxremote.ssl=false \
    -Dcom.sun.management.jmxremote.authenticate=false"

  1. 如果你觉得有必要验证使用者的用户名和密码，加入以下几行：
        -Dcom.sun.management.jmxremote.authenticate=true \
    -Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password \
    -Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access \
  2. 修改文件 $CATALINA_BASE/conf/jmxremote.access :
    monitorRole readonly
controlRole readwrite
  3. 修改密码文件 $CATALINA_BASE/conf/jmxremote.password :
    monitorRole tomcat
controlRole tomcat
    注意： 密码文件一定要只允许读取，防止以外修改，还要删除其他用户对这个文件操作的许可。
注意： JSR 160 JMX-Adaptor 会打开另一个数据协议的端口， 如果你安装本地防火墙的话， 这会产生问题。

用 Java 1.4 激活 JMX MX4J Http Adaptor：

  1. 安装 Tomcat 的 compat 版
  2. 把 mx4j-tools.jar 放入 common/lib。 请使用与你安装的 Tomcat一样版本的 MX4j
  3. 在 AJP 连接器中加入 MX4J JMX HTTP Adaptor 设置

          <Connector port="${AJP.PORT}"
            handler.list="mx"
            mx.enabled="true"
            mx.httpHost="${JMX.HOST}"
            mx.httpPort="${JMX.PORT}"
            protocol="AJP/1.3" />

    提示： 如果选择 ${AJP.PORT}=0， ajp 连接器不会在那里启动。

    注意： MX4J JSR 160 RMI Adaptor to support JDK 1.4 currently not integrated.

  4. 启动 Tomcat 然后用浏览器查看： http://${JMX.HOST}:${JMX.PORT}
  5. 如果使用 mx connector 属性 mx.authMode="basic" mx.authUser="tomcat" mx.authPassword="strange" 你可以控制用户登陆。
  6. 你可以在下面网站找到完整的 Tomcat 核心 MBean 的列表： http://tomcat.apache.org/tomcat-5.5-doc/catalina/funcspecs/mbean-names.html

使用 JMX 遥控器的 Ant 指令来管理 Tomcat

Tomcat 提供了使用 Ant 1.6 来管理 Tomcat 的 antlib。

antlib 把 $CATALINA_HOME/server/lib 里的 catalina-ant.jar from 复制到 $ANT_HOME/lib 里。

下面的例子显示 JMX Accessor 的使用方法：

<project name="Catalina Ant JMX"
        xmlns:jmx="antlib:org.apache.catalina.ant.jmx"
        default="state"
        basedir=".">
    <property name="jmx.server.name" value="localhost" />
    <property name="jmx.server.port" value="9012" />
    <property name="cluster.server.address" value="192.168.1.75" />
    <property name="cluster.server.port" value="9025" />

    <target name="state" description="Show JMX Cluster state">
        <jmx:open
            host="${jmx.server.name}"
            port="${jmx.server.port}"
            username="controlRole"
            password="tomcat"/>
        <jmx:get
            name="Catalina:type=IDataSender,host=localhost,senderAddress=${cluster.server.address},senderPort=${cluster.server.port}"
            attribute="connected"
            resultproperty="IDataSender.backup.connected"
            echo="false"
        />
       <jmx:get
            name="Catalina:type=ClusterSender,host=localhost"
            attribute="senderObjectNames"
            resultproperty="senderObjectNames"
            echo="false"
        />
        <!-- get current maxActiveSession from ClusterTest application
             echo it to ant output and store at
             property <em>clustertest.maxActiveSessions.orginal</em>
        -->
       <jmx:get
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            attribute="maxActiveSessions"
            resultproperty="clustertest.maxActiveSessions.orginal"
            echo="true"
        />
        <!-- set maxActiveSession to 100
        -->
        <jmx:set
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            attribute="maxActiveSessions"
            value="100"
            type="int"
        />
        <!-- get all sessions and split result as delimiter <em>SPACE</em> for easy
             access all session ids directly with ant property sessions.[0..n].
        -->
        <jmx:invoke
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            operation="listSessionIds"
            resultproperty="sessions"
            echo="false"
            delimiter=" "
        />
        <!-- Access session attribute <em>Hello</em> from first session.
        -->
        <jmx:invoke
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            operation="getSessionAttribute"
            resultproperty="Hello"
            echo="false"
        >
          <arg value="${sessions.0}"/>
          <arg value="Hello"/>
        </jmx:invoke>
        <!-- Query for all application manager.of the server from all hosts
             and bind all attributes from all found manager mbeans.
        -->
        <jmx:query
            name="Catalina:type=Manager,*"
            resultproperty="manager"
            echo="true"
            attributebinding="true"
        />
        <!-- echo the create properties -->
        <echo>
           senderObjectNames: ${senderObjectNames.0}
           IDataSender.backup.connected: ${IDataSender.backup.connected}
           session: ${sessions.0}
           manager.length: ${manager.length}
           manager.0.name: ${manager.0.name}
           manager.1.name: ${manager.1.name}
           hello: ${Hello}
           manager.ClusterTest.0.name: ${manager.ClusterTest.0.name}
           manager.ClusterTest.0.activeSessions: ${manager.ClusterTest.0.activeSessions}
           manager.ClusterTest.0.counterSend_EVT_SESSION_EXPIRED: ${manager.ClusterTest.0.counterSend_EVT_SESSION_EXPIRED}
           manager.ClusterTest.0.counterSend_EVT_GET_ALL_SESSIONS: ${manager.ClusterTest.0.counterSend_EVT_GET_ALL_SESSIONS}
        </echo>

    </target>

</project>

导入： 用下面的指令导入 JMX Accessor 项目 <import file="${CATALINA.HOME}/bin/jmxaccessor-tasks.xml" /> ， 参考下面的 Ant 指令： jmxOpen, jmxSet, jmxGet, jmxQuery, jmxInvoke,jmxEquals and jmxCondition.

JMXAccessorOpenTask - jmx 打开连接指令

属性
属性 | 描述 | 缺省值
url | 设置 jmx 连接 url - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi
<Host> | 设置主机名，简化冗长的 url 格式 | localhost
port | 设置遥控连接的端口 | 8050
username | 遥控器用户名
password | jmx 遥控器用户连接密码
ref | Name of the internal connection referenz. With this attribute you can configure more the one connection inside the same ant projekt. | jmx.server
echo | Echo the command usage (for analyse access or debugging) | false
if | Only execute if a property of the given name exists in the current project.
unless | Only execute if a property of the given name not exists in the current project.

实例：jmx 连接

    <jmx:open
            host="${jmx.server.name}"
            port="${jmx.server.port}"
    />

实例：用URL、用户名和密码打开 jmx 连接

    <jmx:open
            url="service:jmx:rmi:///jndi/rmi://localhost:9024/jmxrmi"
            ref="jmx.server.9024"
            username="controlRole"
            password="tomcat"
    />

实例：当jmx.if 存在而且jmx.unless不存在，用URL、用户名和密码打开 jmx 连接

    <jmx:open
            url="service:jmx:rmi:///jndi/rmi://localhost:9024/jmxrmi"
            ref="jmx.server.9024"
            username="controlRole"
            password="tomcat"
            if="jmx.if"
            unless="jmx.unless"
    />

注意：jmxOpen任务的属性同样适用于其他任务或条件。

JMXAccessorGetTask: get attribute value ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=Server
attribute | Existing Mbean attribute (see Tomcat mbean description above)
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false
resultproperty | Save result at this project property
delimiter | Split result with delimiter (java.util.StringTokenizier) and use resultproperty as prefix to store tokens.
separatearrayresults | When return value is an array, save result as property list ($resultproperty.[0..N] and $resultproperty.lenght) | true

Example to get remote mbean attribute from default jmx connection

    <jmx:get
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        attribute="maxActiveSessions"
        resultproperty="servlets-examples.maxActiveSessions"
    />

Example to get and result array and split it at separate properties

    <jmx:get
        name="Catalina:type=ClusterSender,host=localhost"
        attribute="senderObjectNames"
        resultproperty="senderObjectNames"
    />
Access the senderObjectNames properties with:
    ${senderObjectNames.lenght} give the number of returned sender list.
    ${senderObjectNames.[0..N]} found all sender object names

Example to get IDataSender attribute connected only when cluster is configured.

<jmx:query
    failonerror="false"
    name="Catalina:type=Cluster,host=${tomcat.application.host}"
    resultproperty="cluster"
/>
<jmx:get
    name="Catalina:type=IDataSender,host=${tomcat.application.host},senderAddress=${cluster.backup.address},senderPort=${cluster.backup.port}"
    attribute="connected"
    resultproperty="datasender.connected"
    if="cluster.0.name" />

JMXAccessorSetTask: set attribute value ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=Server
attribute | Existing Mbean attribute (see Tomcat mbean description above)
value | value that set to attribute
type | type of the attribute. | java.lang.String
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false

Example to set remote mbean attribute value

    <jmx:set
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        attribute="maxActiveSessions"
        value="500"
        type="int"
    />

Examples to set multiple remote mbean attributes

    <jmx:set
        name="java.lang:type=Threading">
             <arg name="ThreadContentionMonitoringEnabled" value="true" type="boolean"/>
             <arg name="ThreadCpuTimeEnabled" value="false" type="boolean"/>
    </jmx:set>

JMXAccessorInvokeTask: invoke Mbean operation ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=Server
operation | Existing Mbean operation (see Tomcat http://tomcat.apache.org/tomcat-5.5-doc/catalina/funcspecs/fs-admin-opers.html.
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false
resultproperty | Save result at this project property
delimiter | Split result with delimiter (java.util.StringTokenizier) and use resultproperty as prefix to store tokens.
separatearrayresults | When return value is an array, save result as property list ($resultproperty.[0..N] and $resultproperty.lenght) | true

stop an application

    <jmx:invoke
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        operation="stop"/>
Now you can find the sessionid at ${sessions.[0..N} properties and access the count with ${sessions.lenght} property.

Example to get all sessionids

    <jmx:invoke
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        operation="listSessionIds"
        resultproperty="sessions"
        delimiter=" "
    />
Now you can find the sessionid at ${sessions.[0..N} properties and access the count with ${sessions.lenght} property.

Example to get remote mbean session attribute from session ${sessionid.0}

    <jmx:invoke
        name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
        operation="getSessionAttribute"
        resultproperty="hello">
         <arg value="${sessionid.0}"/>
         <arg value="Hello" />
 </jmx:invoke>

Example to create a new access logger valve at vhost localhost

 <jmx:invoke
         name="Catalina:type=MBeanFactory"
         operation="createAcccesLoggerValve"
         resultproperty="acccesLoggerObjectName"
 >
     <arg value="Catalina:type=Host,host=localhost"/>
 </jmx:invoke>
Now you can find new Mbean with name stored at ${acccesLoggerObjectName} proeprty.

JMXAccessorQueryTask: query Mbean ant task

List of Attributes
属性 | 描述 | Default value
name | JMX ObjectName query string -- Catalina:type=Manager,*
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false
resultproperty | Prefix project property name to all founded Mbeans (mbeans.[0..N].objectname)
attributebinduing | bind ALL MBean attributes in addition to name | false
delimiter | Split result with delimiter (java.util.StringTokenizier) and use resultproperty as prefix to store tokens.
separatearrayresults | When return value is an array, save result as property list ($resultproperty.[0..N] and $resultproperty.lenght) | true

Get all Manager ObjectNames from all services and Hosts

  <jmx:query
           name="Catalina:type=Manager,*
           resultproperty="manager" />
Now you can find the Session Manager at ${manager.[0..N].name} properties and access the result object counter with ${manager.length} property.

Example to get the Manager from servlet-examples application an bind all mbean properties

  <jmx:query
           name="Catalina:type=Manager,path=/servlet-examples,host=localhost*"
           attributebinding="true"
           resultproperty="manager.servletExamples" />
Now you can find the manager at ${manager.servletExamples.0.name} property and can access all properties from this manager with ${manager.servletExamples.0.[manager attribute names]}. The result object counter from MBeans is stored ad ${manager.length} property.

Example to get all MBeans from a server and store inside an external xml property file

<project name="jmx.query"
            xmlns:jmx="antlib:org.apache.catalina.ant.jmx"
            default="query-all" basedir=".">
<property name="jmx.host" value="localhost"/>
<property name="jmx.port" value="8050"/>
<property name="jmx.username" value="controlRole"/>
<property name="jmx.password" value="tomcat"/>

<target name="query-all" description="Query all MBeans of a server">
<!-- Configure connection -->
<jmx:open
    host="${jmx.host}"
    port="${jmx.port}"
    ref="jmx.server"
    username="${jmx.username}"
    password="${jmx.password}"/>
<!-- Query MBean list -->
<jmx:query
    name="*:*"
    resultproperty="mbeans"
    attributebinding="false"/>

<echoproperties
    destfile="mbeans.properties"
    prefix="mbeans."
    format="xml"/>

<!-- Print results -->
<echo
    message="Number of MBeans in server ${jmx.host}:${jmx.port} is ${mbeans.length}"/>
</target>
</project>
Now you can find all MBeans inside the file mbeans.properties.

JMXAccessorCreateTask: remote create mbean ant task

List of Attributes
属性 | 描述 | Default value
name(名称) | Full qualified JMX ObjectName -- Catalina:type=MBeanFactory
className | Existing MBean full qualified classname (see Tomcat mbean description above)
classLoader ObjectName of server or web application classloader
( Catalina:type=ServerClassLoader,name=[server,common,shared] or
Catalina:type=WebappClassLoader,path=/myapps,host=localhost)
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false

Example to create remote mbean

    <jmx:create
             ref="${jmx.reference}"
             name="Catalina:type=MBeanFactory"
             className="org.apache.commons.modeler.BaseModelMBean"
             classLoader="Catalina:type=ServerClassLoader,name=server">
             <Arg value="org.apache.catalina.mbeans.MBeanFactory" />
    </jmx:create>

Warning: A lot of tomcat mbeans can't be really create and connect with
the parent. The valve, cluster or realm Mbeans are not autconnect with there parent.
Use MBeanFacrory create operation instead.

JMXAccessorUnregisterTask: remote unregister mbean ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=MBeanFactory
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false

Example to unregister remote mbean

    <jmx:unregister
        name="Catalina:type=MBeanFactory"
    />

Warning: A lot of tomcat mbeans can't be really unregister.
The Mbeans are not deregister from parent. Use MBeanFacrory
remove operation instead.

JMXAccessorCondition: express condition

List of Attributes
属性 | 描述 | Default value
url | Set jmx connection url - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi
host | Set the host, shortcut the very long url syntax. | localhost
port | Set the remote connection port | 8050
username | remote jmx connection user name.
password | remote jmx connection password.
ref | Name of the internal connection reference. With this attribute you can configure more the one connection inside the same ant projekt. | jmx.server
name | Full qualified JMX ObjectName -- Catalina:type=Server
echo | Echo condition usage (access and result) | false
if | Only execute if a property of the given name exists in the current project.
unless | Only execute if a property of the given name not exists in the current project.
value (requiered) | Second arg for operation
type | Value type to express operation (support long and double) | long
operation express one
  • == equals
  • != not equals
  • > greater than (&gt;)
  • >= greater than or equals (&gt;=)
  • < lesser than (&lt;)
  • <= lesser than or equals (&lt;=)
 ==

Wait for server connection and that cluster backup node is accessable

      <target name="wait">
         <waitfor maxwait="${maxwait}" maxwaitunit="second" timeoutproperty="server.timeout" >
            <and>
                <socket server="${server.name}" port="${server.port}"/>
                <http url="${url}"/>
                <jmx:condition
                    operation="=="
                    host="localhost"
                    port="9014"
                    username="controlRole"
                    password="tomcat"
                    name="Catalina:type=IDataSender,host=localhost,senderAddress=192.168.111.1,senderPort=9025"
                    attribute="connected"
                    value="true"
                />
            </and>
        </waitfor>
        <fail if="server.timeout" message="Server ${url} don't answer inside ${maxwait} sec" />
        <echo message="Server ${url} alive" />
    </target>

JMXAccessorEqualsCondition: equals Mbean ant condition

List of Attributes
属性 | 描述 | Default value
url | Set jmx connection url - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi
host | Set the host, shortcut the very long url syntax. | localhost
port | Set the remote connection port | 8050
username | remote jmx connection user name.
password | remote jmx connection password.
ref | Name of the internal connection referenz. With this attribute you can configure more the one connection inside the same ant projekt. | jmx.server
name | Full qualified JMX ObjectName -- Catalina:type=Server
echo | Echo condition usage (access and result) | false

Wait for server connection and that cluster backup node is accessable

      <target name="wait">
         <waitfor maxwait="${maxwait}" maxwaitunit="second" timeoutproperty="server.timeout" >
            <and>
                <socket server="${server.name}" port="${server.port}"/>
                <http url="${url}"/>
                <jmx:equals
                    host="localhost"
                    port="9014"
                    username="controlRole"
                    password="tomcat"
                    name="Catalina:type=IDataSender,host=localhost,senderAddress=192.168.111.1,senderPort=9025"
                    attribute="connected"
                    value="true"
                />
            </and>
        </waitfor>
        <fail if="server.timeout" message="Server ${url} don't answer inside ${maxwait} sec" />
        <echo message="Server ${url} alive" />
    </target>


Apache Tomcat 5.5 Servlet/JSP 容器 - 用代理服务器整合Apache和Tomcat

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

用代理服务器整合Apache和Tomcat

 Printer Friendly Version
print-friendly
version
介绍

使用标准的Tomcat设置，WEB应用里的Servlet或JSP可以下面的方法，获得为用户服务的主机名称和使用 端口的号码。如果让Tomcat单独运行而不与其他WEB服务器捆绑，Tomcat一般可以转达用户请求里指定的 服务器名称和Tomcat设置里“Connector”所监听的端口。下面的 Servlet API里 面的方法可以用来解决这个问题：

  • ServletRequest.getServerName(): 用户请求里指定的主机名。
  • ServletRequest.getServerPort(): 用户请求里指定的端口。
  • ServletRequest.getLocalName(): 收到用户请求的主机名。
  • ServletRequest.getLocalPort(): 收到用户请求的主机端口。

当你的Tomcat在一个代理服务器(或一个被配置成与代理服务器行为一样的web服务器)后面运行，你 有时候希望根据用户的访问请求的服务器名和端口号码来正确处理，而不是Connector 本监听的那个端口和主机名。你可以使用 &lt;Connector&gt;元素里面的proxyName 和 proxyPort 属性来配置这些值。

用代理器来捆绑Tomcat和Apache可以有多种形式。下面的章节描述了几种常见情况的代理配置。

用代理器捆绑 Tomcat 和 Apache 1.3

Apache 1.3支持一个任选模块(mod_proxy)，这个任选模块用来配置web服务器， 让这个web服务器象代理服务器一样工作。这可以用来把指定的web应用程序的请求传递到一个 Tomcat 去，而不需要配置一个象mod_jk 的web connector。要做到这样， 你需要执行下面的任务：

  1. 修改你的Apache 配置,让它包含mod_proxy模块。如果你从源代码开始创建， 最容易的办法是把--enable-module=proxy指令包含在./configure 命令行上。
  2. 如果你还没有安装mod_proxy模块，你可以在httpd.conf文件里 使用下列指令来装载它：
    LoadModule proxy_module {path-to-modules}/mod_proxy.so
AddModule mod_proxy.c
  3. 对于每个你想要传递给Tomcat的web应用程序，在你的httpd.conf文件里包含 两个指令。例如：
    ProxyPass /myapp http://localhost:8081/mywebapp
ProxyPassReverse /myapp http://localhost:8081/mywebapp
    它告诉Apache把http://localhost/mywebapp/*形式的URLs传递给在端口8081上 监听的 Tomcat 连接器， /mywebapp 是Tomcat里的一个应用。
  4. 修改Tomcat 的 server.xml，让它包括一个特殊的&lt;Connector&gt;元素，以及相应 的代理设置，例如：
    &lt;Connector port="8081" ...
proxyName="www.mycompany.com"
proxyPort="80"/&gt;
    它会让这个web应用程序里边的servlets认为 所有的代理请求被导向端口80上的www.mycompany.com 。
  5. 从&lt;Connector&gt;元素里省略掉proxyName属性是合法的。 如果你这样做，由request.getServerName()返回的值将是Tomcat在它上面运行 的那个主机名字。 在上面的例子中，它就是localhost。
  6. 如果你还有一个在端口8080上监听的&lt;Connector&gt在Service元素里，向其中 任何一个端口发出的请求都将共享相同的虚拟主机和web应用程序。
  7. 你可以使用你的操作系统的IP过滤(filtering)来限制与端口8081的连接， 这个例子里，使用户不能直接连接到8081或8080端口上而一定要通过端口80上的Apache。
  8. 或者，你可以设置仅仅通过代理(proxying)才能被使用的一系列web应用程序，如下：
    • 为代理端口配置包含仅仅一个&lt;Connector&gt;元素的另外一个 &lt;Service&gt;。
    • 通过代理为虚拟主机和web应用程序配置相应的 Engine，Host， 和Context元素。
    • 或者，如早先描述的那样以IP过滤器保护端口8081。
  9. 当请求被Apache代理处理，Apache服务器的访问日志会记录这些请求。因此，你应该终止Tomcat本身 的访问日志。

当请求以这种形式被代理，配置过的web应用程序的所有请求都将由Tomcat处理 (包括对静态内容的请求)。你可以通过使用mod_jk web connector， 而不是mod_proxy 来提高性能。mod_jk可以配置成让web服务器来提供那些静态内容， 如果静态内容在web应用程序部署描述符/WEB-INF/web.xml被定义为必须经过过滤器或有 安全限制，这些内容仍然会由Tomcat来处理。

用代理器捆绑 Tomcat 与 Apache 2.0
在Apache 2.0里，可以忽略AddModule mod_proxy.c， 其它与1.3的说明相同。


Apache Tomcat 5.5 Servlet/JSP 容器 - 权限管理 - 域(Realm)的设置

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

权限管理 - 域(Realm)的设置

 Printer Friendly Version
print-friendly
version
目录

快 速 上 手

什么是域（Realm）?
配置一个域（Realm）
域的共有属性
把密码加密（Digested）
应用程序示例
Tomcat管理员程序
在域（Realm）里面纪录日志
Tomcat现有的标准域（Realm）
JDBCRealm
DataSourceRealm
JNDIRealm
MemoryRealm
JAASRealm
UserDatabaseRealm

快 速 上 手

这个文档描述了怎样通过用一个现有"数据库"里的用户名,密码以及角色来配置 Tomcat，从而来支持容器管理的安全性(container managed security)。 如果你使用一个网络程序，而这个程序里包括了一个或多个<security-constraint> 元素，以及一个定义用户怎样认证他们自己的<login-config>元素，那你就需要设置 这些域（Realm）。如果你不使用这些功能，你就可以跳过这个文档。

关于容器管理安全性的基础背景知识，参看 Servlet 规范 (Version 2.4)，第12章。

关于使用Tomcat 5的一次性登录特性(允许用户只需认证他自己一次就可以使用和虚拟 主机相关的所有网络程序)的信息。请看这里。

概述
什么是域（Realm）?

域(Realm)是一个存储用户名,密码以及和用户名相联系的角色的”数据库”, 用户名,密码用来验证 用户对一个或多个web应用程序的有效性。访问应用程序中特定资源的权限是被授予了拥有特殊角色的用户， 而不是相关的用户名。通过用户名相关联，一个用户可以有任意数量的角色。

尽管Servlet规范描述了一个可以让应用程序声明它们安全性要求(在web.xml 部署描述符里)的机制，但是并没有的API(应用编程接口)来定义一个基于servlet容器和其 相关用户角色之间的界面(interface)。然而在许多情况下，最好能把一个servlet容器和那些已经存在 的认证数据库或机制“连接”起来。因此，Tomcat 5定义了一个 Java界面(org.apache.catalina.Realm)，它可以通过"插件"来实现 这种连接。这里提供了五个标准的插件，用来支持与各个认证信息来源的连接：

  • JDBCRealm - 通过JDBC驱动来访问贮存在关系数据库里的认证信息。
  • DataSourceRealm - 通过一个叫做JNDI JDBC 的 数据源(DataSource)来访问贮存在关系数据库里的认证信息。
  • JNDIRealm - 通过JNDI provider来访问贮存在基于 LDAP(轻量目录访问协议)的目录服务器里的认证信息。
  • MemoryRealm - 访问贮存在电脑内存里的认证信息，它是通过一个 XML文件(conf/tomcat-users.xml)来进行初始化的。
  • JAASRealm - 使用 Java Authentication & Authorization Service (JAAS).

也可以编写你自己的Realm implementation，然后与Tomcat整合在一起。你需要：

  • 实现org.apache.catalina.Realm
  • 把编译过的文件放置到&#036;CATALINA_HOME/server/lib里边
  • 象下面的"配置一个域（Realm）" 章节里描述的那样声明你的realm。
  • 用MBeans 描述符声明你的realm。

配置一个域（Realm）

在进入详细的标准Realm实现之前，弄懂怎样配置一个域（Realm）是很重要的。通常，你需要把 一个XML元素加入到你的conf/server.xml配置文件中，它看起来象这样：

&lt;Realm className="... class name for this implementation"
... other attributes for this implementation .../&gt;

<Realm>元素可以被套嵌在下列任何一个Container 元素里面。这个Realm元素所处的位置直接影响到这个域（Realm）的作用范围（比如，哪些web应用程序 会共享相同的认证信息）：

  • 在<Engine>元素里边 - 这个域（Realm）将会被所有虚拟主机上的所有 网络程序共享，除非它被嵌套在下级<Host> 或 <Context>元素里的Realm元素覆盖。
  • 在<Host>元素里边 - 这个域（Realm）将会被该虚拟主机上所有的 网络程序所共享，除非它被嵌套在下级<Context>元素里的Realm元素覆盖。
  • 在<Context>元素里边 - 这个域（Realm）只被该网络程序使用。
共有特性
把密码加密

对于每个现有的Realm实现里，用户的密码(默认情况下)以明文形式 被贮存。在许多环境中，这是不理想的，因为任何人看见了认证数据都可以收集足够信息成功登录，冒充 其他用户。为了避免这个问题，标准的实现支持digesting用户密码的概念。这被贮存的 密码是被加密后的(以一种不易被转换回去的形式)，但是Realm实现还是可以用它来认证。

当一个标准的realm通过取得贮存的密码并把它与用户提供的密码值作比较来认证时，你可通过在你 的元素<Realm>上指定digest属性选择digested密码。 这个属性的值必须是java.security.MessageDigest class (SHA, MD2, or MD5) 支持的digest 算法之一。当你选择这一选项，贮存在域（Realm）里的密码内容必须是这个密码的明文 形式，然后被指定的运算法则来加密。

当这个Realm的authenticate()方法被调用，用户指定的(明文) 密码被相同的运算法来加密，它的结果与Realm返回的值作比较。如果两个值对等的话，就意味着 原始密码的明文版与用户提供的一样，所以这个用户就被认证了。

要计算一个明文密码经过加密的值，Tomcat 支持下面两个便利的技术：

  • 如果你在编写一个需要自动加密密码的程序， 调用org.apache.catalina.realm.RealmBase类里的Digest()方法， 把明文密码和加密的算法名字作为参数传递过去。这种方法会返回的是经过加密的密码。
  • 如果你想要使用命令行设施来加密密码，简单地执行以下命令：
    java org.apache.catalina.realm.RealmBase \
-a {algorithm} {cleartext-password}
    这个明文密码的加密版本会以标准输出 形式返回。

如果使用加密的密码进行DIGEST认证，用于产生digest的明文是不一样的。在上面的例子中， {cleartext-password}必须被{username}:{realm}:{cleartext-password} 取代。比如说，在一个开发环境中它是这样的形式testUser:localhost:8080:testPassword。

要使用上面所说的任何一个技术，需要把$CATALINA_HOME/server/lib/catalina.jar 文件放在你的class path上，让RealmBase类可以被使用。另外，你还需要JMX.jar和 commons-logging.jar文件 (要么是 commons-logging-api.jar 要么是 commons-logging.jar)。 Tomcat包括有这俩个文件。

非ASCII的用户名和/或密码也被支持，但你需要使用下面的命令

java org.apache.catalina.realm.RealmBase \ -a {algorithm} -e {encoding} {input}
不过必须要保证这个非ASCII输入正确地传递给digester。这个digester会返回 {input}:{digest}值。如果返回的input有误，加密也就是无效的。

应用程序示例

和Tomcat一起的应用程序示例包括被安全限制保护的一个区域,需要使用基于-表格(form-based)的登录。 想要访问它，把浏览器指向http://localhost:8080/jsp-examples/security/protected/， 并使用默认的MemoryRealm里所描述的用户名和密码来登录。

Tomcat管理员程序

如果你想要使用管理员程序(Manager Application) 在运行的Tomcat安装里部署和删除应用程序，你必须在你选择的Realm实现中至少给一个用户名添加 "manager"角色。这是因为管理员网络应用程序本身使用一个安全限制， 需要"manager"的角色在这个程序里面访问任何请求URI。

因为安全的原因，在默认的Realm里(i.e. 使用 conf/tomcat-users.xml文件）没有用户名被指派"manager"角色。 因此，在Tomcat administrator特别地给一个或几个用户指派这个角色之前，没有人能够利用这个程序。

在域（Realm）里面纪录日志

每个Realm排错和异常信息将由与这个realm的容器相关的日志配置记录下来： 它的Context, Host, 或 Engine。

Tomcat现有的标准域（Realm）
JDBCRealm

简介

JDBCRealm是一个Tomcat Realm界面实现，它通过JDBC驱动来查看关系数据库 里的用户信息。这里配置的可塑性很大，它让你能够使用现存的表名和列名(column names)，只要你的 数据库结构与下面的要求一致：

  • 必须要有一个表格(table)存在，它必须是每一行包含一个这个Realm所能识别的 合法用户。下面引用叫做users的表格。
  • 这个用户表格必须包括至少两列(如果你的程序需要还可以有更多列)。
    • 可被Tomcat识别的用户登录名称(username)。
    • 可被Tomcat识别的用户登录密码。这个值可以是明文式(cleartext)或是被编码过(digested) 的形式 - 下面可查看更多信息。
  • 必须要有一个表格存在，它必须是每一行包含一个指派给某个特定用户的某个合法角色。 下面引用叫做user_roles的表格。
  • 这个user_roles表格必须包括至少两列(如果你的程序需要还可以有更多列)：
    • 可被Tomcat识别的用户登录名称(和users table里指定的值相同)。
    • 和这个user_name相关联的有效role_name。

快 速 上 手

要设置好Tomcat来使用JDBCRealm，你必须遵守下面这些步骤：

  1. 根据上面所描述的规定，在你的数据库里产生表格(tables)和列(columns)。
  2. 配置一个可供Tomcat使用的用户名称和密码，它至少应该有只读(read only)权限来访问上述表格。 (Tomcat从不会试图去改写这些表格)。
  3. 把你将要使用的JDBC驱动复制件放置到$CATALINA_HOME/server/lib目录 (如果你不想让网络程序使用它的话)或者放在$CATALINA_HOME/common/lib(如果 Tomcat 和你的程序都要使用它的话)。注意，唯一只有JAR文件才能 被识别。
  4. 象下面所描述的那样，在你的$CATALINA_HOME/conf/server.xml文件设置一个 <Realm>元素。
  5. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 JDBCRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

一个用于产生所需表格的SQL script示例也许看起来象这样(根据你特定的数据库需要做些语法上的改编):

create table users (
user_name varchar(15) not null primary key,
user_pass varchar(15) not null
);

create table user_roles (
user_name varchar(15) not null,
role_name varchar(15) not null,
primary key (user_name, role_name)
);

关于Realm元素的例子被包括在默认的$CATALINA_HOME/conf/server.xml 文件里(但被 commented out)。在下面的例子中，使用了一个叫做"authority"的 MySQL数据库，根据上面所描述的表格进行了配置，可以通过用户名"dbuser" 和 密码"dbpass"进行访问:

<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="org.gjt.mm.mysql.Driver"
connectionURL="jdbc:mysql://localhost/authority?user=dbuser&amp;amp;password=dbpass"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

另外的注意事项

JDBCRealm根据下面的规则进行运作：

  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会传叫(call)这个Realm 的authenticate()方法。因此，你对于这个数据库所做的认何直接更改(新用户，更改 过的密码和角色等等)都会被立即反映出来。
  • 一但用户被认证，用户(以及其相关角色)在这个用户登录期间会被高速缓存(cache)在Tomcat里。 (对于是基于表单(FORM-based)认证的用户，在会话结束或者注销后认证失效；对于BASIC认证的用户， 要等到用户关闭窗口后认证才失效)。被高速缓存的用户不会 在会话系列之间被贮存或再生(restored)。对于已经被认证的用户，任何有关数据库信息的更改，一直 要等到下次用户再次登录后才会被显示出来。
  • 管理users和user_roles表格里的信息应该是你的应用程序的职责。Tomcat没有 提供任何built-in 能力来维护用户及其角色信息。
DataSourceRealm

简介

DataSourceRealm是一个Tomcat 5 Realm界面实现，它通过 一个叫做JDBC DataSource的JNDI来访问查询关系数据库里的用户信息。这里配置的可塑性很大，让你 能够使用现有的表名和列名，只要你的数据库结构与下面的要求一致：

  • 必须要有一个表格(table)存在，它必须是每一行包含一个这个Realm所能识别的 合法用户。下面引用叫做users的表格。
  • 这个用户表格必须包括至少两列(如果你的程序需要还可以有更多列)。
    • 可被Tomcat识别的用户登录名称(username)。
    • 可被Tomcat识别的用户登录密码。这个值可以是明文式(cleartext)或是被编码过(digested) 的形式 - 下面可查看更多信息。
  • 必须要有一个表格存在，它必须是每一行包含一个指派给某个特定用户的某个合法角色。下面引用叫 做用户角色的表格。
  • 这个用户角色表格必须包括至少两列(如果你的程序需要还可以有更多列)：
    • 可被Tomcat识别的用户登录名称(和users table里指定的值相同)。
    • 和这个用户相关联的有效角色名称。

快 速 上 手

要设置好Tomcat来使用DataSourceRealm，你必须遵守下面这些步骤：

  1. 根据上面所描述的规定，在你的数据库里产生表格(tables)和列(columns)。
  2. 配置一个可供Tomcat使用的用户名称和密码，它至少应该有只读(read only)权限来访问上述表格。 (Tomcat从不会试图去改写这些表格)。
  3. 为你的数据库配置一个叫做JDBC DataSource的JNDI。关于怎样配置一个叫做JDBC DataSource的 JNDI的信息请参看JNDI DataSource Example HOW-TO 。
  4. 象下面所描述的那样，在你的$CATALINA_HOME/conf/server.xml文件设置一个 <Realm>元素。
  5. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 DataSourceRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

一个用于产生所需表格的SQL script示例也许看起来象这样(根据你特定的数据库需要做些语法上的改编):

create table users (
user_name varchar(15) not null primary key,
user_pass varchar(15) not null
);

create table user_roles (
user_name varchar(15) not null,
role_name varchar(15) not null,
primary key (user_name, role_name)
);

在下面的例子中，使用了一个叫做"authority"的MySQL数据库，根据上面所描述的表格 进行了配置，可以通过"java:/comp/env/jdbc/authority"访问JNDI JDBC DataSource:

<Realm className="org.apache.catalina.realm.DataSourceRealm" debug="99"
dataSourceName="jdbc/authority"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

另外的注意事项

DataSourceRealm根据下面的规则进行运作：

  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会传叫(call)这个Realm的 authenticate()方法。因此，你对于这个数据库所做的认何直接更改(新用户，更改过的 密码和角色等等)都会被立即反映出来。
  • 一但用户被认证，用户(以及其相关角色)在这个用户登录期间会被高速缓存(cache)在Tomcat里。 (对于是基于表单(FORM-based)认证的用户，在会话结束或者注销后认证失效；对于BASIC认证的用户， 要等到用户关闭窗口后认证才失效)。被高速缓存的用户不会 在会话系列之间被贮存或再生(restored)。对于已经被认证的用户，任何有关数据库信息的更改，一直 要等到下次用户再次登录后才会被显示出来。
  • 管理users和user_roles角色表格里的信息应该是你的应用程序的职责。Tomcat没有 提供任何built-in 能力来维护用户及其角色信息。
JNDIRealm

简介

DataSourceRealm是一个Tomcat 5 Realm界面实现，它通过一个JNDI provider 来访问查询LDAP目录里的用户信息(通常是与JNDI API类一起的标准LDAP provider)。这个realm支持一系列使用目录来进行认证的方法。

与目录相连接

这个realm与目录的连接是由connectionURL配置属性定义的。这个URL的 格式又是由JNDI provider来定义的。它通常是一个LDAP URL，用来指定相连接的目录服务器的领域 名称，或者端口数码以及所需的root naming context的特殊名称。

如果你有不止一个供应者(provider)，你可以配置一个alternateURL。如果 不能在connectionURL与供应者连接上，机器就会试图使用alternateURL来连接。

在为了查询目录和搜索用户及其角色进行连接的时候，这个realm就通过connectionName 和 connectionPassword 属性指定的用户名称和密码来向这个目录认证它自己。 如果属性没有被指定，连接就是无名的。在许多情形下，这也足够了。

选择用户的目录进入

每一个能被认证的用户必须在目录里由一个单个登录(individual entry)来代表，这个单个登录与 初始DirContext里边被connectionURL属性定义的一个元素相 对应。这个用户登录必须有一个包含认证用的用户名称的属性(attribute).

通常这个用户登录的特殊名称包含提供给认证用的用户名，否则所有用户都一样。在这种情况下， userPattern这个属性也许可用来指定DN(特殊名称)，用"{0}" 来标记用户名在什么地方可被替代。

否则这个realm必须搜寻(search)目录才能找到包含用户名称的独特的登录。这样的搜寻由下面的这些 属性配置：

  • userBase - 这个输入是作为包含用户信息subtree的基础。如果没有 指定，search base是最上层context。
  • userSubtree - 搜寻范围。如果你想搜寻根基于 userBase entry的整个subtree，把它设置为true。 默认的值false要求仅仅包括上层的单层搜寻。
  • userSearch - 指定要使用的LDAP搜寻过滤器的模式

认证用户

  • 绑定模式

    在默认的情况下，realm通过与带有用户和用户密码的目录绑定在一起来认证一个用户。如果这个简单 的绑定成功的话，用户就被认为被认证过了。

    因为安全的原因，目录会储存digest形式的用户密码，而不是明码版本(更多信息请看 Digested 密码)。在这种情况下，作为简单绑定操作的一部分， 目录在与储存的值核对之前自动把用户提供的正文密码换算成正确的digest。因此在绑定模式里，域（realm） 没有参与digest过程。这个digest属性没有被使用，即使被设置了，也被忽略掉。

  • 比较模式

    另外，域（realm）可以从目录中取出储存的密码并与用户提供的值做直接比较。通过把 userPassword属性设定为带有密码的用户输入里的一个 directory attribute的名字来配置这个模式。

    比较模式有一些不利的地方。第一，connectionName 和 connectionPassword 属性必须配置能让realm去阅读在目录里的用户密码。 因为安全的原因，这通常是不可取的，事实上，许多目录implementations不允许，即使是目录管理员 也不允许阅读这些密码。另外，realm必须自己处理password digests，包括使用运算法则的变化， 和在目录里表示密码hashes的方法。不过，realm有时也需要访问储存的密码，例如，要支持 HTTP Digest Access Authentication (RFC 2069)。(注意，HTTP digest认证不同于上面所 讨论的在用户信息储藏室里的password digests储存)。

给用户指派角色

目录域（realm）支持下列两种方法来在目录里代表角色：

  • 作为显式目录输入的角色

    角色可以通过显式的目录输入来代表。一个role entry通常是一个LDAP group entry，它具有一个 包含这个角色的名字以及另一个值为这个角色的特殊名字或用户名的属性。下面的这些属性配置一个目录 搜寻来发现与这个认证过的用户相关联的角色名称。

    • roleBase - 角色搜寻的基础输入。如果没有指定，search base是顶层目录context。
    • roleSubtree - 搜寻范围。如果你想搜寻根基于roleBase entry的整个subtree，把它设置为true。默认的值false要求仅仅 包含顶层的单层搜寻。
    • roleSearch - 选择角色输入的LDAP搜寻过滤器。它可选择性地包含两个 模式替代："{0}" 代替被认证过的用户的特殊名字，以及/或者 "{1}" 代替 被认证过的用户的用户名。
    • roleName - 包含那个角色名字的role entry里的属性。

  • 作为用户输入的一个属性的角色

    角色名字也可以作为在用户目录输入里一个属性的值。使用userRoleName来 指定这个属性的名称。

这两种代表角色方法的组合也可以被使用。

快 速 上 手

要设置好Tomcat来使用JNDIRealm，你必须遵守下面这些步骤：

  1. 确保你的目录服务器是依据上面的要求配置的。
  2. 如果需要，配置一个可供Tomcat使用的用户名称和密码，它应该有只读(read only)权限来访问 上述表格。(Tomcat从不会试图去改写这些表格)。
  3. 把你将要使用的JNDI驱动(通常ldap.jar available with JNDI)复制件放置 到$CATALINA_HOME/server/lib目录(如果你不想让网络程序使用它的话)或者放在 $CATALINA_HOME/common/lib(如果Tomcat 5和你的程序都要使用它的话)。
  4. 象下面所描述的那样，在你的$CATALINA_HOME/conf/server.xml文件设置一个 <Realm>元素。
  5. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 JNDIRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

因为每个目录服务器的实现都不同，在你的目录服务器里产生相适宜的schema超出了本文的范围。在 下面的例子里，我们假设你使用的是OpenLDAP目录服务器(2.0.11或其后版本)，你可以从 http://www.openldap.org下载它。 假设你的slapd.conf文件包含下面的设置：

database ldbm
suffix dc="mycompany",dc="com"
rootdn "cn=Manager,dc=mycompany,dc=com"
rootpw secret

至于connectionURL，我们假设目录服务器和Tomcat一样在同一个机器上运行。 更多关于配置和使用JNDI LDAP provider的信息，请参看http://java.sun.com/products/jndi/docs.html 。

下一步，假设这个目录服务器具有下面这些元素(以LDIF格式):

# Define top-level entry
dn: dc=mycompany,dc=com
objectClass: dcObject
dc:mycompany

# Define an entry to contain people
# searches for users are based on this entry
dn: ou=people,dc=mycompany,dc=com
objectClass: organizationalUnit
ou: people

# Define a user entry for Janet Jones
dn: uid=jjones,ou=people,dc=mycompany,dc=com
objectClass: inetOrgPerson
uid: jjones
sn: jones
cn: janet jones
mail: j.jones@mycompany.com
userPassword: janet

# Define a user entry for Fred Bloggs
dn: uid=fbloggs,ou=people,dc=mycompany,dc=com
objectClass: inetOrgPerson
uid: fbloggs
sn: bloggs
cn: fred bloggs
mail: f.bloggs@mycompany.com
userPassword: fred

# Define an entry to contain LDAP groups
# searches for roles are based on this entry
dn: ou=groups,dc=mycompany,dc=com
objectClass: organizationalUnit
ou: groups

# Define an entry for the "tomcat" role
dn: cn=tomcat,ou=groups,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
cn: tomcat
uniqueMember: uid=jjones,ou=people,dc=mycompany,dc=com
uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com

# Define an entry for the "role1" role
dn: cn=role1,ou=groups,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
cn: role1
uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com

假设用户使用他们的uid (e.g. jjones)来登入应用程序，并且无名的连接足够用来搜索目录和取得 角色信息，如上面所描述配置的OpenLDAP目录服务器的Realm元素示例看起来象这样：

<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionURL="ldap://localhost:389"
userPattern="uid={0},ou=people,dc=mycompany,dc=com"
roleBase="ou=groups,dc=mycompany,dc=com"
roleName="cn"
roleSearch="(uniqueMember={0})"
/>

在这样的配置下，realm通过把用户名替代到userPattern里去来决定用户的特殊的 唯一名字，通过把这个特殊的唯一名字(DN)和用户提供的密码与目录绑定来认证，并搜索目录来发现用户的角色。

现在假设用户在登入时使用他们的email地址，而不是他们的userid。在这种情况下，realm必须搜索 目录来寻找用户的输入。(当用户输入被放在与不同的组织单位或公司位置相对应的多个subtrees里时， 搜索也是必要的)。

进一步，假设除了群体输入外，你想要使用关于用户输入的一个属性来保存角色信息。这里，关于Janet Jones的输入读起来象这样：

dn: uid=jjones,ou=people,dc=mycompany,dc=com
objectClass: inetOrgPerson
uid: jjones
sn: jones
cn: janet jones
mail: j.jones@mycompany.com
memberOf: role2
memberOf: role3
userPassword: janet

这个realm的配置应该满足这些新的要求：

<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionURL="ldap://localhost:389"
userBase="ou=people,dc=mycompany,dc=com"
userSearch="(mail={0})"
userRoleName="memberOf"
roleBase="ou=groups,dc=mycompany,dc=com"
roleName="cn"
roleSearch="(uniqueMember={0})"
/>

现在，当Janet Jones以"j.jones@mycompany.com"登录时，realm在目录里搜索具 有那个值作为它的mail属性的独特输入，并以所给的密码，及以下uid=jjones,ou=people,dc=mycompany,dc=com 与目录绑定。如果认证成功，她就被指派给三个角色："role2" and "role3"分别作为 她的目录输入里"memberOf"属性的值，"tomcat"作为唯一一个群体(她是其中 一个成员)输入"cn"属性的值。

最后，要想通过从目录中取得密码，并在realm里做局部比较来认证，你也许需要使用象这样的一个realm配置：

<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionName="cn=Manager,dc=mycompany,dc=com"
connectionPassword="secret"
connectionURL="ldap://localhost:389"
userPassword="userPassword"
userPattern="uid={0},ou=people,dc=mycompany,dc=com"
roleBase="ou=groups,dc=mycompany,dc=com"
roleName="cn"
roleSearch="(uniqueMember={0})"
/>

当然，正如上面所描述的，通常比较偏向使用默认的绑定模式来认证。

另外的注意事项

JNDIRealm根据下面的规则进行运作：

  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会调用这个Realm 的authenticate()方法。因此，你在目录里的任何更改(新用户，更改过的密码或角色， 等等)会立即被反映出来。
  • 一旦用户被认证过，这个用户(及其相关的角色)在这个用户登录期间被高速缓存(cached)在Tomcat 里。(对于基于-表格(FORM-based)的认证，这意味着直致会话时间结束或无效；对于BASIC认证，这 意味着用户关闭他们的浏览器)。被缓存的用户在会话系列之间不 被保存和再贮存。一个已经被认证过的用户的任何目录信息的更改，直到下次用户再登录时才会被反映出来。
  • 管理目录服务器里的信息是你的程序自身的责任。Tomcat不提供任何内在的功能来维持用户及角色信息。
MemoryRealm

简介

MemoryRealm是一个简单的Tomcat 5 Realm界面实现。它 不是为大量用户名称认证而设计的。在启动时，MemoryRealm从一个XML文件装载关于所有用户，以及他们相应的 角色的信息(在默认情况下，这个文件从$CATALINA_HOME/conf/tomcat-users.xml 被装载)。这个文件里的数据更改直到Tomcat被重新被启动后才会被识别。

Realm元素属性

为了配置一个 MemoryRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

用户文件格式

用户文件(默认文件conf/tomcat-users.xml必须是一个带有 根元素<tomcat-users>的XML文件。每个合法用户 的<user>元素嵌套在根元素里，包含有下列属性：

  • name(名称) - 这个用户必须用来登录的用户名。
  • password(密码)- 这个用户登录必须使用的密码(如果 在<Realm>元素上digest属性没有被设置，或者没有象 这里描述的那样正确地被digested)。
  • roles(角色) - 与这个用户相关的以逗号分隔开的角色名称列单。

例子

The default contents of the conf/tomcat-users.xml file is:

<tomcat-users>
<user name="tomcat" password="tomcat" roles="tomcat" />
<user name="role1" password="tomcat" roles="role1" />
<user name="both" password="tomcat" roles="tomcat,role1" />
</tomcat-users>

另外的注意事项

MemoryRealm根据下面的规则进行运作：

  • 当Tomcat第一次启动，它从用户文件装载了所有定义的用户以及他们的相关信息。直到Tomcat被 重新启动之前，这个文件里的数据的更改不会被识别出来。
  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会调用这个Realm 的authenticate()方法。
  • 一旦用户被认证过，这个用户(及其相关的角色)在这个用户登录期间被高速缓存(cached)在Tomcat 里。(对于基于-表格(FORM-based)的认证，这意味着直致会话时间结束或无效；对于BASIC认证，这意味 着用户关闭他们的浏览器)。被缓存的用户在会话系列之间不被保存和再贮存。
  • 管理目录服务器里的信息是你的程序自身的责任。Tomcat不提供任何内在的功能来维持用户及角色信息。
UserDatabaseRealm

简介

UserDatabaseRealm 是一个简单的Tomcat 5 Realm界面实现。所有用户和 他们的角色信息都来自于 JNDI 资源。这个 JNDI资源实现的是UserDatabase界面。

Realm元素属性

为了配置一个 UserDatabaseRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

缺省安装的Tomcat 5 配置的 UserDatabaseRealm 嵌套在<Engine>元素内， 所以它适用于所有虚拟主机和web应用。这个域（realm）使用与MemoryRealm相同的 tomcat-users.xml。

JAASRealm

简介

JAASRealm 是一个通过Java Authentication & Authorization Service (JAAS)框架认证用户的Tomcat 4 Realm 接口 的实现，而这个JAAS是一个Java软件包，它在Java 2 SDK 1.3里是作为选择性软件包被使用，在 SDK 1.4里它则完全整合在其中了。

使用JAASRealm给予开发人员这种能力，那就是把任何可想象的安全realm与 Tomcat 的CMA组合在一起。

JAASRealm是基于JAAS的J2EE 1.4版本的J2EE认证框架的原型(prototype)，它是在 JCP Specification Request 196 基础上来加强容器-管理的安全性，并促进不依赖于容器 的实现的'pluggable'认证机制。 JCP Specification Request 196

在JAAS登录模块和原则(参看javax.security.auth.spi.LoginModule 和javax.security.Principal)的基础上，你可以开发你自己的安全机制或者把第三方 的机制与Tomcat执行的CMA整合包裹在一起。

快 速 上 手

要设置好Tomcat来与你自己JAAS login模块一起使用JAASRealm，你必须遵守下面这些步骤：

  1. 在JAAS (参看the JAAS Authentication Tutorial 和 the JAAS Login Module Developer's Guide)基础上编写你自己的由JAAS Login Context (javax.security.auth.login.LoginContext) 管理的 LoginModule, User 和Role 类。在开发你的LoginModule时，注意JAASRealm自身具有的 CallbackHandler目前仅仅能识别NameCallback 和PasswordCallback。 the JAAS Authentication Tutorial the JAAS Login Module Developer's Guide
  2. 尽管JAAS里没有指明，但你还是应该通过扩展javax.security.Principal产生 不同的类来区分用户和角色，这样Tomcat可以从你的login module返回的Principals中区别 哪个是用户，哪个是角色（参看org.apache.catalina.realm.JAASRealm）。 不然的话，返回的第一个Principal总是被当作用户Principal。
  3. 把编译过的类放置在Tomcat的classpath上。
  4. 设置一个Java的login.config文件(参看JAAS LoginConfig file)，并对JVM指明 这个文件的位置告诉Tomcat到哪里去找到它。例如，可以把环境变量设置如下： JAVA_OPTS=-DJAVA_OPTS=-Djava.security.auth.login.config==$CATALINA_HOME/conf/jaas.config 。 JAAS LoginConfig file JAVA_OPTS=-DJAVA_OPTS=-Djava.security.auth.login.config==$CATALINA_HOME/conf/jaas.config
  5. 在你的web.xml文件里为你想要保护的资源配置安全-限制(security-constraints) 。
  6. 在你的server.xml文件里配置JAASRealm模块(module)。
  7. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 JAASRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

你的server.xml文件看起来应该象这个例子这样。

<Realm className="org.apache.catalina.realm.JAASRealm"
appName="MyFooRealm"
userClassNames="org.foobar.realm.FooUser"
roleClassNames="org.foobar.realm.FooRole"
debug="99"/>

是你的login模块的责任来产生并保存代表用户的Principals的( javax.security.auth.Subject ) User和Role对象(objects)。如果你的login模块没有产生一个user object ，也没有抛出一个login异常， 那么Tomcat CMA 会终断，你会被停留在http://localhost:8080/myapp/j_security_check URI 或其他未指定的位置。

JAAS方法的可塑性有两层：

  • 你可以在你自己的login模块里实现任何你需要的程序处理。
  • 不用对你的应用程序编码有任何更改，你可以通过更改配置并重新启动服务器来插入(plug in)一个完全 不同的LoginModule。

另外的注意事项

  • 当一个用户第一次试图访问一个被保护的资源，Tomcat 5会调用这个Realm的 authenticate()方法。这样一来，你在这个安全机制里做的任何更改（新用户，更改密码 和角色，等等）会立即被反映出来。
  • 一旦用户被认证过，这个用户(及其相关的角色)在这个用户登录期间被零时缓存(cached)在Tomcat里。 对于基于-表格(FORM-based)的认证，这意味着直致会话时间结束或无效；对于BASIC认证，这意味着直到 用户关闭他们的浏览器。对于被认证过的用户，任何安全信息更改在这个用户再次登录之前都不 会被反映出来。
  • 和其他Realm实现一样，如果server.xml 里面的 <Realm>元素包含有一个digest属性，digested密码就被支持； JAASRealm 的 CallbackHandler在把密码传递回LoginModule 之前会先digest密码。


Apache Tomcat 5.5 Servlet/JSP 容器 - Tomcat的系统安全管理

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Tomcat的系统安全管理

 Printer Friendly Version
print-friendly
version
背景知识

Java的SecurityManager允许浏览器在它可执行的范围内运行，这样可以 防止不可靠的程序读写用户在局部文件系统里的文件，或者未经授权进行网络连接，等等。同样， SecurityManager可用来防止不可靠的程序在你的浏览器上运行，在运行Tomcat时，使用 SecurityManager可以保护你的服务器不受到类似于木马的servlets, JSPs, JSP beans 和标签库（tag libraries）的影响，或者发生错误。

试想某个被允许在你的网站上发表JSPs的人不慎包括了以下的语句在他们的JSP里：

&lt;%System.exit(1);%&gt;

每次Tomcat运行该JSP都会导致Tomcat中断。使用Java SecurityManager 如同多了一层防护， 可以让服务器更加安全可靠。

警告——虽然Tomcat 5 的程序通过了安全检查，最重要的程序包都已被 保护，新的安全机制也已实施，但在允许用户发表网络程序，JSPs, servlets, beans, 或 标签库（tag libraries）之前，你还是有必要确保 SecurityManager 的各项配置符合你的要求。 当然，有SecurityManager绝对比没有它要安全的多。

许可 Permissions

Java的Permission类是用来定义Tomcat载入的类所拥有的权限。Java本身包括了一些 Permission类，你也可以在你的网络应用中加入你自己的Permission类。 这两种技术在Tomcat 5里都被应用。

标准许可

这里将简单总结标准系统中适用于Tomcat的SecurityManager 和 Permission 类。 更多信息请参看 http://java.sun.com/security/。

  • java.util.PropertyPermission - 控制读/写Java虚拟器的属性，如java.home 。
  • java.lang.RuntimePermission - 控制使用一些系统/运行时(System/Runtime)的功能，如exit() 和 exec()。它也控制包(package)的访问/定义。
  • java.io.FilePermission - 控制对文件和目录的读/写/执行操作。
  • java.net.SocketPermission - 控制使用网路sockets连接。
  • java.net.NetPermission - 控制使用multicast网路连接。
  • java.lang.reflect.ReflectPermission - 控制使用reflection来对类进行检视。
  • java.security.SecurityPermission - 控制对安全方法的访问。
  • java.security.AllPermission - 给予所有访问权限，就如你运行一个没有SecurityManager的Tomcat 。
Tomcat 中可修改的许可

Tomcat利用一个叫做org.apache.naming.JndiPermission 许可类。它用来控制以JNDI命名的文件资源的可读权限。该许可的名称是以JNDI来表达， 没有命令。在给予许可时，"*"的结尾可以用来以wild card方式映射JNDI命名 的文件资源。例如，你可以在你的政策(policy)文件加入以下一行：

permission org.apache.naming.JndiPermission "jndi://localhost/examples/*";

一个象这样的许可(Permission)会在部署网络程序时被自动产生，允许它读取它自己的静态资源， 但不允许它使用文件访问权来读取其它文件(除非你明确地给出访问那些文件的许可).

并且, Tomcat 总是自动产生以下文件许可:

permission java.io.FilePermission "** your application context**", "read";

这里**your application context**代表那个拥有你的应用程序的文件夹(或者是WAR文件)。

改变 Tomcat 中的 SecurityManager

政策文件的格式

由Java SecurityManager实现的安全政策被配置存放在 $CATALINA_HOME/conf/catalina.policy 文件里。这个文件完全替代了 JDK系统目录里的java.policy文件。这个catalina.policy 文件可以手动修改， 或者使用Java 1.2 及其后版本的 policytool 程序修改。

catalina.policy 文件中的条文使用了标准的java.policy 文件格式，如下：

// Example policy file entry

grant [signedBy &lt;signer&gt;,] [codeBase &lt;code source&gt;] {
permission &lt;class&gt; [&lt;name&gt; [, &lt;action list&gt;]];
};

其中signedBy 和 codeBase是选择项。 注释行是以"//"开始，直到该行结束。codeBase是URL的格式，文件的URL中可用如 ${java.home}和${catalina.home}等属性(这些属性会被扩展到由环境变量 JAVA_HOME 和 CATALINA_HOME为他们定义的目录路径)。

缺省政策文件

缺省$CATALINA_HOME/conf/catalina.policy 文件看起来象这样：

// ============================================================================
// catalina.corepolicy - Security Policy Permissions for Tomcat 5
//
// This file contains a default set of security policies to be enforced (by the
// JVM) when Catalina is executed with the "-security" option.  In addition
// to the permissions granted here, the following additional permissions are
// granted to the codebase specific to each web application:
//
// * Read access to the document root directory
//
// $Id: security-manager-howto.xml 301460 2003-01-15 03:40:45Z glenn $
// ============================================================================

// ========== SYSTEM CODE PERMISSIONS =========================================
// ========== 系统源码许可控制 ===============

// These permissions apply to javac
// 下面的许可适用于javac
grant codeBase "file:${java.home}/lib/-" {
        permission java.security.AllPermission;
};

// These permissions apply to all shared system extensions
// 下面的许可适用于java的扩展
grant codeBase "file:${java.home}/jre/lib/ext/-" {
        permission java.security.AllPermission;
};

// These permissions apply to javac when ${java.home] points at $JAVA_HOME/jre
// 下面的许可适用于当${java.home] 是 $JAVA_HOME/jre时的 javac
grant codeBase "file:${java.home}/../lib/-" {
        permission java.security.AllPermission;
};

// These permissions apply to all shared system extensions when
// 下面的许可适用于java的扩展
// ${java.home} points at $JAVA_HOME/jre
grant codeBase "file:${java.home}/lib/ext/-" {
        permission java.security.AllPermission;
};

// ========== CATALINA CODE PERMISSIONS =======================================
// ========== CATALINA的源码许可控制 =============

// These permissions apply to the launcher code
// 以下许可适用于启动Tomcat的程序
grant codeBase "file:${catalina.home}/bin/commons-launcher.jar" {
        permission java.security.AllPermission;
};

// These permissions apply to the server startup code
// 以下许可适用于启动服务器的程序
grant codeBase "file:${catalina.home}/bin/bootstrap.jar" {
        permission java.security.AllPermission;
};

// These permissions apply to the servlet API classes
// and those that are shared across all class loaders
// located in the "common" directory
// 以下许可适用于 Servlet 的 API 和 common目录里的程序
grant codeBase "file:${catalina.home}/common/-" {
        permission java.security.AllPermission;
};

// These permissions apply to the container's core code, plus any additional
// libraries installed in the "server" directory
// 下面的许可适用于Tomcat的核心和 server 目录里的程序
grant codeBase "file:${catalina.home}/server/-" {
        permission java.security.AllPermission;
};

// ========== WEB APPLICATION PERMISSIONS =====================================
// ========== WEB 应用的许可 ===========

// These permissions are granted by default to all web applications
// In addition, a web application will be given a read FilePermission
// and JndiPermission for all files and directories in its document root.
// 缺省情况下，所有WEB 应用拥有下面这些许可，另外还有 它们本身文件夹里的 “read” FilePermission
// 和JndiPermission。

grant {
        // Required for JNDI lookup of named JDBC DataSource's and
        // javamail named MimePart DataSource used to send mail
        permission java.util.PropertyPermission "java.home", "read";
        permission java.util.PropertyPermission "java.naming.*", "read";
        permission java.util.PropertyPermission "javax.sql.*", "read";

        // OS Specific properties to allow read access
    permission java.util.PropertyPermission "os.name", "read";
    permission java.util.PropertyPermission "os.version", "read";
    permission java.util.PropertyPermission "os.arch", "read";
    permission java.util.PropertyPermission "file.separator", "read";
    permission java.util.PropertyPermission "path.separator", "read";
    permission java.util.PropertyPermission "line.separator", "read";

        // JVM properties to allow read access
        permission java.util.PropertyPermission "java.version", "read";
        permission java.util.PropertyPermission "java.vendor", "read";
        permission java.util.PropertyPermission "java.vendor.url", "read";
        permission java.util.PropertyPermission "java.class.version", "read";
    permission java.util.PropertyPermission "java.specification.version", "read";
    permission java.util.PropertyPermission "java.specification.vendor", "read";
    permission java.util.PropertyPermission "java.specification.name", "read";

    permission java.util.PropertyPermission "java.vm.specification.version", "read";
    permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
    permission java.util.PropertyPermission "java.vm.specification.name", "read";
    permission java.util.PropertyPermission "java.vm.version", "read";
    permission java.util.PropertyPermission "java.vm.vendor", "read";
    permission java.util.PropertyPermission "java.vm.name", "read";

        // Required for getting BeanInfo
        permission java.lang.RuntimePermission "accessClassInPackage.sun.beans.*";

        // Required for OpenJMX
        permission java.lang.RuntimePermission "getAttribute";

    // Allow read of JAXP compliant XML parser debug
    permission java.util.PropertyPermission "jaxp.debug", "read";
};

// 你还可以给某个特定的WEB应用赋予其它许可。
// You can assign additional permissions to particular web applications by
// adding additional "grant" entries here, based on the code base for that
// application, /WEB-INF/classes/, or /WEB-INF/lib/ jar files.
//
// Different permissions can be granted to JSP pages, classes loaded from
// the /WEB-INF/classes/ directory, all jar files in the /WEB-INF/lib/
// directory, or even to individual jar files in the /WEB-INF/lib/ directory.
//
// For instance, assume that the standard "examples" application
// included a JDBC driver that needed to establish a network connection to the
// corresponding database and used the scrape taglib to get the weather from
// the NOAA web server.  You might create a "grant" entries like this:
//
// The permissions granted to the context root directory apply to JSP pages.
// grant codeBase "file:${catalina.home}/webapps/examples/-" {
//      permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect";
//      permission java.net.SocketPermission "*.noaa.gov:80", "connect";
// };
//
// The permissions granted to the context WEB-INF/classes directory
// grant codeBase "file:${catalina.home}/webapps/examples/WEB-INF/classes/-" {
// };
//
// The permission granted to your JDBC driver
// grant codeBase "jar:file:${catalina.home}/webapps/examples/WEB-INF/lib/driver.jar!/-" {
//      permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect";
// };
// The permission granted to the scrape taglib
// grant codeBase "jar:file:${catalina.home}/webapps/examples/WEB-INF/lib/scrape.jar!/-" {
//      permission java.net.SocketPermission "*.noaa.gov:80", "connect";
// };

启动附带SecurityManager的Tomcat

在你配置好与SecurityManager一起使用的catalina.policy文件之后， 你可以使用"-security"选项来启动Tomcat。

$CATALINA_HOME/bin/catalina.sh start -security (Unix)
%CATALINA_HOME%\bin\catalina start -security (Windows)
Configuring Package Protection in Tomcat

从Tomcat 5开始，现在可以配置Tomcat内部包的许可。更多信息请参阅 http://java.sun.com/security/seccodeguide.html 。

警告：删除缺省的包保护，可能打开一个安全漏洞。

缺省的属性文件

缺省的$CATALINA_HOME/conf/catalina.properties 文件看起来象这样：

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,org.apache.catalina.,org.apache.coyote.,org.apache.tomcat.,
org.apache.jasper.
#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageDefinition unless the
# corresponding RuntimePermission ("defineClassInPackage."+package) has
# been granted.
#
# by default, no packages are restricted for definition, and none of
# the class loaders supplied with the JDK call checkPackageDefinition.
#
package.definition=sun.,java.,org.apache.catalina.,org.apache.coyote.,
org.apache.tomcat.,org.apache.jasper.

当你完成配置SecurityManager所需的catalina.properties 文件，记住要重新启动Tomcat。

故障排除

如果你的网络应用程序试图执行没有许可而被阻止的操作，SecurityManager探查出这样的违规后， 就会抛出一个AccessControLException 或 SecurityException。 要查出究竟缺少哪个许可往往非常困难，一个方法是打印执行过程中的所有关于安全决定的排错信息。 这可以在启动Tomcat之前通过设置系统属性来实现。最简单的办法是修改CATALINA_OPTS 环境变量。在启动Tomcat之前，执行下面这个命令：

export CATALINA_OPTS=-Djava.security.debug=all (Unix)
set CATALINA_OPTS=-Djava.security.debug=all (Windows)

（在启动Tomcat之前）。

警告——这会产生很多megabytes的输出。不过，通过 查找"FAILED"这个词可以帮助你搜索问题所在，并确定哪个许可是要找的问题。 请参看Java安全文档资料，那里有你可指定的更多选项。


Apache Tomcat 5.5 Servlet/JSP 容器 - 安装 TOMCAT

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

安装 TOMCAT

Printer Friendly Version
print-friendly
version
介绍

这篇文档介绍了几种在不同的操作平台上运行Tomcat的安装方法。请注意，这里没包含一些高级 的设置问题：完整发布版 (ZIP 文件 or tarball)里有一个叫做RUNNING.txt的文件来讨论这些 问题。如果下面的信息不能回答你的某些问题的话，我们建议你再参考一下RUNNING.txt文件。

Windows下使用安装版安装

用Window安装版可以很简单地在Windows上安装Tomcat。 它的接口和功能与此其它安装程序相似，只需要几个有关的项目就行了。

  • 安装为系统服务：不管选什么样的设置，Tomcat都将被安装 成Windows NT/2K/XP 的系统服务。在组件那一页上，选中"auto" （“自动”） 运行，这样启动Windows时，Tomcat 就会自动启动。 从最佳安全性考虑，这种服务应该作为单独的用户来运行，它的操作权限也应被限制 (参看Windows服务管理工具以及帮助文档)。
  • Java路径：安装程式利用登记名册(registry)的信息，或者 JAVA_HOME 环境变量(variable)来决定J2SE 5 JRE的基础(base)路径(path)。
  • 任务栏图标: 当 Tomcat 作为服务运行时, 任务栏图标将不会出现。 如果你在安装的最后步骤选择运行 Tomcat，任务栏图标会同时出现一次。
  • 关于怎样把Tomcat作为Windows NT service进行管理的信息，请参考 Windows Service HOW-TO 。

安装程式会产生一个快捷方式允许启动和配置Tomcat。必须注意Tomcat管理web应用程序只有在 Tomcat运行时才能被使用。

如果使用J2SE 1.4 JRE，应该下载其相应的软件包并把它扩展在安装Tomcat所放置的文件夹里。

Unix daemon

应用commons-daemon项目里的jsvc工具可以很好地运行Tomcat。 Tomcat二进制(binaries) 里有jsvc的source tarballs, 需要被编译。 建立(building) jsvc需要用C ANSI编译器(如 GCC), GNU, Autoconf, and a JDK。

在运行脚本(script)之前， JAVA_HOME的环境变量要被设定在JDK的基础路径 (base path)里，或者在调用(calling) ./configure脚本时， 用--with-java 参数(parameter)来设定JDK的路径， 比如./configure --with-java=/usr/java。

应用下面的指令(command)可以产生一个编译过的jsvc二进制(文件)，这个文件放在 $CATALINA_HOME/bin文件夹。 这里假设使用了GNU TAR, 同时 $CATALINA_HOME环境变量(environment variable)被设定在Tomcat安装的基础 路径上。 $CATALINA_HOME/bin

请注意,你要用GNU make(g make),而不是用FreeBSD系统(system)本身的BSD make.

    cd $CATALINA_HOME/bin
    tar xvfz jsvc.tar.gz
    cd jsvc-src
    autoconf
    ./configure
    make
    cp jsvc ..
    cd ..

然后Tomcat就可以用下面的命令很好地运行:

    cd $CATALINA_HOME
    ./bin/jsvc -Djava.endorsed.dirs=./common/endorsed -cp ./bin/bootstrap.jar \
        -outfile ./logs/catalina.out -errfile ./logs/catalina.err \
        org.apache.catalina.startup.Bootstrap

javc还有其他的有用的参数，就象-user(用户)，在daemon初始化(initialization) 完成以后，使它转换到另一个用户。这样，既使没有特使权的用户来运行Tomcat，也可以使用特定 的端口(privileged port)。 jsvc --help 会提供全面的jsvc使用信息。 特别是-debug 选项在jsvc运行时对排错很有用。

文件$CATALINA_HOME/bin/jsvc/native/tomcat.sh 可被用作样板(template)，在 开机时从/etc/init.d 自动启动Tomcat。 这个文件目前被设置来运行 Tomcat 4.1x， 所以需要修订一下，把类名(classname) BootstrapService 改成Bootstrap。 $CATALINA_HOME/bin/jsvc/native/tomcat.sh

Commons-Daemon的JAR文件一定要在运行时的 classpath里面。如果你因为 Commons-Daemon 得到一个 ClassNotFoundException 或 NoClassDefFoundError， 请把 Commons-Daemon 的 JAR 用 -cp 选项加入到 classpath 里面，然后再启动 jsvc.


Apache Tomcat 5.5 Servlet/JSP 容器 - SSI How To

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

SSI How To

 Printer Friendly Version
print-friendly
version
简介

SSI (Server Side Includes)是放置在HTML页面里的指令(directives)，在HTML页面被使用的 同时在服务器上被评估。这样可以让你把新产生的内容添加到现存的HTML页面上，而不需要同过CGI程序， 或其他动态的技术来产生整个页面。

当你使用Tomcat作为你的HTTP服务器，并要求有SSI支持，你可以把SSI支持添加到Tomcat里面。 通常在你不想要运行一个象Apache的web服务器的开发过程中它就被完成了。

Tomcat SSI 支持实施与Apache相同的指令。关于使用SSI指令的信息， 请参看 Apache Introduction to SSI 。

Tomcat里面SSI的支持是通过使用Servlet或过滤器来完成的。你必须选择其中一个来支持你的SSI， 而不能同时使用两个。

基于Servlet的SSI是通过实现 org.apache.catalina.ssi.SSIServlet来完成的。按照SSI的习惯，这个Servlet 然后被映射成以 "*.shtml" 结尾的 URL。

基于过滤器的 SSI 是通过实现 org.apache.catalina.ssi.SSIFilter来完成的。 按规矩, 这个过滤器过滤所有 以"*.shtml"结尾的 URL，你也可以用 "*" 映射，让它过滤所有URL，但它会根据 不同的文件种类 （mime types）来决定是否启用SSI。使用初始值 contentType 可以让你决定是否要用 SSI 来处理 JSP， Javascript 或其他内容的网页。

在缺省情况下设置是 Tomcat 不自动启用 SSI。

安装

警告——SSI指令可以用于执行Tomcat JVM外部的程序。如果你在使用 Java SecurityManager，它可以绕过你的catalina.policy里的安全政策配置。

把$CATALINA_BASE/server/lib/servlets-ssi.renametojar 改名为 $CATALINA_BASE/server/lib/servlets-ssi.jar 。

如果选择使用基于Servlet的SSI，请把$CATALINA_BASE/conf/web.xml里面被 注释掉的关于SSI 的 servlet 和 servlet-mapping 定义重新激活。

如果选择基于过滤器的 SSI， 清激活 $CATALINA_BASE/conf/web.xml 关于 SSI 的 filter 和 filter-mapping的设置。 .

Servlet 设置

有几个servlet起始参数可以用来配置SSI servlet的行为。

  • buffered - 这个servlet的输出是不是应该被缓冲？(0=false, 1=true) 默认是 0 (false).
  • debug - 由这个servlet日志的排错消息的详细程度。默认是0。
  • expires - 带有SSI指令的页面失效之前的秒数。默认行为是对于每一个请求都要评估所用的SSI指令。
  • isVirtualWebappRelative - “虚拟”SSI指令路径是否应该被解释为 相对于context root，而不是server root。 (0=false, 1=true) 默认是 0 (false)。
  • inputEncoding - 如果无法决定所调用资源的文字编码，SSI应该使用的编码。 缺省数值是系统的文字编码。
  • outputEncoding - 输出结果的文字编码，缺省值是 UTF-8。

过滤器设置

过滤器的性能可通过修改几个不同的初始值来调整。

  • contentType - 用一个正则表达式来就定那种网页类型应该调用 SSI。在 决定正则表达式时，不要忘记在网页内容种类的定义里可以有文字编码的选项， 它的标准是："mime/type; charset=set"，其中 charset=set 是选择项。 contentType的缺省值是："text/x-server-parsed-html(;.*)?".
  • debug - 由这个servlet日志的排错消息的详细程度。默认是0。
  • expires - 带有SSI指令的页面失效之前的秒数。默认行为是对于每一个请求都要评估所有的SSI指令。
  • isVirtualWebappRelative - “虚拟”SSI指令路径是不是应该被解释为相对于 context root相关，还是相对于server root (0=false, 1=true) 默认是 0 (false)。

Tomcat 允许 SSI 指令

SSI是通过 嵌入在 HTML的指令来完成的实现动态网页的。这些指令在HTML里面如同HTML的注释，在 运行Tomcat会把它替换为响应的内容。这些指令的标准格式是：

<!--#directive [parm=value] -->

有效指令有：

  • config - <!--#config timefmt="%B %Y" --> 用来指定SSI输出的时间日期或其他内容的格式
  • echo - <!--#echo var="VARIABLE_NAME" --> 替换所指定的数值
  • exec - 运行所在系统的命令
  • include - <!--#include virtual="file-name" --> 插入内容
  • flastmod - <!--#flastmod file="filename.shtml" --> 文件最后修改时间
  • fsize - <!--#fsize file="filename.shtml" --> 文件大小
  • printenv - <!--#printenv --> 打印所有环境变量
  • set - <!--#set var="foo" value="Bar" --> 用来为用户定义变量赋值
  • if elif endif else - 用于条件判断，例如：
    • <!--#config timefmt="%A" -->
    <!--#if expr="$DATE_LOCAL = /Monday/" -->
    <p>Meeting at 10:00 on Mondays</p>
    <!--#elif expr="$DATE_LOCAL = /Friday/" -->
    <p>Turn in your time card</p>
    <!--#else -->
    <p>Yoga class at noon.</p>
    <!--#endif -->

阅读更多SSI相关内容：

Apache SSI入门

Variables

SSI Servlet 现在支持下列变量：

变量名称 | 描述
AUTH_TYPE | 用来验证用户的方法，可以是：BASIC, FORM, 等
CONTENT_LENGTH | 从FORM传来的数据长度，单位是 bytes 或字符的个数
CONTENT_TYPE | MIME种类, 例如 "text/html"
DATE_GMT | 现在的国际标准时间 GMT
DATE_LOCAL | 当地时间
DOCUMENT_NAME | 调用的文件名
DOCUMENT_URI | 文件的虚拟路径
GATEWAY_INTERFACE | 服务器如果激活了 CGI 的话，显示支持的 CGI 版本，如 "CGI/1.1"
HTTP_ACCEPT | 所有允许的 MIME 种类
HTTP_ACCEPT_ENCODING | 列出所有客户端允许的压缩方式
HTTP_ACCEPT_LANGUAGE | 列出所有客户端接受的语言
HTTP_CONNECTION | 客户端接受的连接管理方法，如 "Close" or "Keep-Alive"
HTTP_HOST | 用户请求访问的网站
HTTP_REFERER | 连接到本网页的网页地址，用户来自于的网页网页
HTTP_USER_AGENT | 浏览器的名称
LAST_MODIFIED | 当前文件的最后修改时间
PATH_INFO | 传给服务器的路径信息
PATH_TRANSLATED | 经过转换的 PATH_INFO 路径
QUERY_STRING | 浏览器地址栏里 "?" 之后的值
QUERY_STRING_UNESCAPED | Undecoded query string with all shell metacharacters escaped with "\"
REMOTE_ADDR | 用户的IP地址
REMOTE_HOST | 用户的网址
REMOTE_PORT | 用户所用的端口号码
REMOTE_USER | 经确认的用户名字
REQUEST_METHOD | 用户请求访问所使用的方法，如 "GET", "POST" 等
REQUEST_URI | 用户所要求访问的网址
SCRIPT_FILENAME | 目前用户实际访问的网页在服务器上的文件名
SCRIPT_NAME | 网页的文件名
SERVER_ADDR | 服务器的IP地址
SERVER_NAME | 服务器电脑的名称或IP
SERVER_PORT | 服务器等待用户访问的端口
SERVER_PROTOCOL | 服务器使用的协议，如： "HTTP/1.1"
SERVER_SOFTWARE | 服务器所使用的软件名称和版本数
UNIQUE_ID | 服务器与用户目前如果开始会话的特有ID


Apache Tomcat 5.5 Servlet/JSP 容器 - 如何设置SSL

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

如何设置SSL

 Printer Friendly Version
print-friendly
version
速成

文档说明：本文件适用于用JSSE设置Tomcat的SSL。 如果使用 APR, Tomcat是通过 OpenSSL来实现SSL，设置会不同。

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

你需要按照下列简单步骤在Tomcat 5上安装和配置SSL支持。更多信息，请阅读这个帮助的其余部分。

  1. 如果你在使用1.3 JVM，从http://java.sun.com/products/jsse/ 下载JSSE 1.0.3 (或其后的版本)， 然后，或者把它作为系统上installed extension，或者把它设置为一个环境变量 JSSE_HOME，让它指向你所安装JSSE的目录。

  2. 通过执行下面的命令产生一个认可的keystore。
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

    Unix

    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

    并指定一个密码值为"changeit"。

  3. 把$CATALINA_HOME/conf/server.xml中的 "SSL HTTP/1.1 Connector" 去掉注释，并根据需要修改。

SSL简介

SSL, 或者Secure Socket Layer，是一种允许web浏览器和web服务器通过一个安全的连接进行 交流的技术。这意味着将被发送的数据在一端被翻译成密码，传送出去，然后在另一端解开密码， 再进行处理。这是一个双向的过程，也就是浏览器和服务器都需要在发送数据之前对它们进行加密。

SSL协定的另一个重要方面是认证(Authentication)。这就是说，在你开始试图通过一个安全连接 与一个web服务器交流的时候，这个服务器会要求你的浏览器出示一组证件，通过“鉴定”的方式来证明这 就是你所声明的网站。在某些情况下，服务器还会要求你的web浏览器的认证书，证明你就是你所说的那 个人。这就是所知的“客户认证”，尽管实际情况中，更多地用在商务-对-商务(B2B)交易，而不是对个人 用户。大多数有SSL功能的web服务器不要求客户认证(Client Authentication)。

SSL 和 Tomcat

必须要注意，配置Tomcat来利用secure sockets仅仅在它作为一个独立的web服务器时才有必要。 当Tomcat主要作为在另外一个web服务器,如Apache 或Microsoft IIS, 后面的Servlet/JSP容器 运行时，通常有必要把主要的web服务器配置来处理与用户的SSL连接。通常，这个服务器会对所有的 SSL-相关的功能进行交涉，然后再把对Tomcat容器的请求解密后传递过去。同样，Tomcat会返回 明码的回应，这个回应将被加密后才被送到用户浏览器。在这样的环境下，Tomcat知道与主要web服务器 和客户的交流是通过一个安全连接才发生的(因为你的程序需要询问这些情况)，但是它本身并没有参与 加密和解密。

认证书：Certificate

为了能实施SSL，一个web服务器对每个接受安全连接的外部接口(IP 地址)必须要有相应的认 证书(Certificate)。关于这个设计的理论是一个服务器必须提供某种合理的保证以证明这个服务器的 主人就是你所认为的那个人，特别是在接收任何敏感信息之前要这样做。关于Certificates的更广泛 的解释超过了这个文档资料的范围，就把一个认证书当作一个英特网地址的“数码驾驶执照”。这个认证书 要陈述与这个网站相关联的公司，以及这个网站的所有者或系统管理员的一些基本联系信息。

这个"驾驶执照"由所有人以密码方式签字，其他人非常难伪造。对于进行电子商务 (e-commerce)的网站，或其他身份认证至关重要的任何商业交易，认证书要向大家所熟知的认证权威 (Certificate Authority (CA))如VeriSign或Thawte来购买。这样的认证书可用电子 技术证明属实——实际上，认证权威单位会担保它发出的认证书的真实性，如果你信任发出认证书的 认证权威单位的话，你就可以相信这个认证书是有效的。

在许多情况下，认证并不是真正使人担忧的事。系统管理员或许只想要保证被服务器传送和接收的 数据是秘密的，不会被连接线上的偷窃者盗窃到。庆幸的是，Java提供相对简单的被称 为keytool的命令行工具，可以简单地产生“自己签名”的认证书。自己签名的认证书 只是用户产生的认证书，没有正式在大家所熟知的认证权威那里注册过，因此不能确保它的真实性。 认证也许很重要，也许不重要，完全决定于你的需要。

使用SSL需要考虑的地方

用户第一次试图到你的网站访问被安全保卫的页面时,他(她)通常会被要求提供关于认证的 详细信息(如公司名称和联系姓名)，并询问他(她)是否愿意接受这个认证的合法性，并继续进行交易。 一些浏览器会提供一个选项来永久地接受所给的认证的合法性，这样一来用户就不用在每次访问你的网站 时麻烦地去填写认证信息。有的浏览器没有这一选项。一旦用户认可后，这个认证至少在整个浏览器 会话期间被认为是合法的。

虽然SSL协议的设计尽量做到既安全又高效，但是加密和解密是复杂耗时的计算过程。通常没有必要让整个 网站都通过SSL来传输，开发人员可以选择部分网页用SSL，部分网页不用SSL。对于一个相对繁忙的网站 来说，可以选择保护那些比较敏感的信息，如登陆、个人信息、购物车、付账、信用卡等。那些网页只要 把网页地址里http:改为https:，浏览器就会自动把信息按照指定的 协议传输出去。

最后,使用根据网名决定的虚拟主机来进行安全连接可能会出现问题。这是SSL协定本身的设计局限。 SSL handshake，就是客户浏览器接受服务器认证，在HTTP请求访问之前必须产生。因此，包含虚拟 主机名字的请求信息在认证之前不能被确定，所以不可能给单个IP地址分配多个认证书。如果在单个IP 地址上的所有的虚拟主机需要对照同一个认证书来认证的话，再添加多个虚拟主机不应该干扰服务器上 正常的SSL操作。不过要当心，大多数的客户浏览器会按认证书上列出的domain names(主要是官方的， CA-签署的认证书)对照比较服务器的domain name。如果领域名(domain names)不相配，这些浏览器 会向客户端用户显示警告。总的来说，只有address-based虚拟主机通常和SSL一起在生产环境中 被使用。

设置
检查你是否需要下载 JSSE

Java 1.4或更新的版本已经包括了JSSE。如果你使用 1.4或更新版本，你不需要另外下载JSSE。 你可以跳过本节

从下面的网站下载Java Secure Socket Extensions (JSSE) 版本 1.0.3或更新版。 http://java.sun.com/products/jsse/.

在扩展这个软件包后，有两种方法让Tomcat可以使用它(选择其中之一):

  • 通过把所有这三个JAR文件(jcert.jar , jnet.jar , 和 jsse.jar)复制到$JAVA_HOME/jre/lib/ext 目录中去，让JSSE成为 安装好的扩充目录。
  • 产生一个新的环境变量JSSE_HOME，让它包含绝对路径，指向你拆装(unpacked) JSSE二进制分布的目录。
产生 Keystore

Tomcat 现在只支持 JKS或PKCS12 格式的keystores. JKS格式是 Java 的标准 KeyStore格式，它可以用 Java 的 keytool 来产生。这个工具在 Java 的 bin 目录里。 PKCS12 格式时互联网的标准，可以用 OpenSSL 和微软的 Key-Manager来修改。

To import an existing certificate into a JKS keystore, please read the documentation (in your JDK documentation package) about keytool. Note that openssl often adds a readable comments before the key, keytooldoes not support that, so remove the openssl comments if they exist before importing the key using keytool.

使用OpenSSL把一个现存的被你自己CA签署的认证书输入到PKCS12 keystore里面，你会执行象这样的一个命令：

openssl pkcs12 -export -in mycert.crt -inkey mykey.key \
                        -out mycert.p12 -name tomcat -CAfile myCA.crt \
                        -caname root -chain
更深层的情况，请查阅OpenSSL documententation。

要从头开始产生一个新的keystore，包含一个自签的认证书，从一个终端命令行执行下面的命令：

视窗

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

Unix

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

( 应该把RSA运算法则作为主要安全运算法则，这保证了与其它服务器和组件的兼容性。)

这个命令会在用户的home directory产生一个叫做" .keystore " 的新文件。要指定一个不同的位置(location)或文件名，在上面所示的keytool 命令里添加-keystore参数，后面紧跟着你的keystore文件的全部路径名。你还需要把 这个新的位置在server.xml配置文件中反映出来，这在后面将有描述。例如：

视窗

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA \
-keystore \path\to\my\keystore

Unix

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA \
-keystore \path\to\my\keystore

在执行这个命令后，你首先被要求出示keystore密码。Tomcat使用的默认密码是 " changeit "(全都是小写字母)，如果你愿意，你可以指定你自己的 密码。你还需要在server.xml配置文件里指定自己的密码，这在以后会有描述。

下一步，你会被要求出示关于这个认证书的一般性信息，如公司，联系人名称，等等。这些信息会 显示给那些试图访问你程序里安全网页的用户，以确保这里提供的信息与他们期望的相对应。

最后，你会被要求出示密钥(key)密码，也就是这个认证书所特有的密码(与其它的 储存在同一个keystore文件里的认证书不同)。你必须在这里使用与keystore 密码相同的密码。(目前，keytool会提示你按ENTER键会自动帮你做这些)。

如果一切顺利，你现在就拥有了一个可以被你的服务器使用的有认证书的keystore文件。

注意： 你的 private key 的密码和 keystore 的密码应该相同。 如果不同的话你会得到一下错误信息： java.io.IOException: Cannot recover key 这是一个已知的错误，详细请看： Bugzilla issue 38217

Edit the Tomcat Configuration File

最后的步骤是把你的secure socket配置在$CATALINA_HOME/conf/server.xml文件里, $CATALINA_HOME代表你在其中安装Tomcat 5 的目录。一个例子是SSL连接器 的&lt;Connector&gt;元素被包括在和Tomcat一起安装的缺省server.xml文件里。 它看起来象是这样：

<-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<!--
<Connector
           port="8443" minProcessors="5" maxProcessors="75"
           enableLookups="true" disableUploadTimeout="true"
           acceptCount="100" debug="0" scheme="https" secure="true";
           clientAuth="false" sslProtocol="TLS"/>
-->

你会注意到Connector元素本身，其默认形式是被注释掉的(commented out)，所以你需要把它周围 的注释标志删除掉。然后，你可以根据需要客户化(自己设置)特定的属性。关于各种选项的详细信息， 请查阅Server Configuration Reference 。下面的讨论 仅仅涵盖设置SSL通信(communication)时大家最感兴趣的那些属性。

这个port属性(默认值是8443)是 TCP/IP端口数码，Tomcat在其上监听安全连接。 你可以把它更改成任何你愿意要的数值(如默认的https通信，数目是443)。不过，在许 多操作系统中，要想在比1024小的端口数码上运行Tomcat，需要特殊的设置(它超出了这个文档资料 的范围)。

如果你在这里更改端口数值，你还必须更改在non-SSL连接器上的redirectPort 这个属性特定的值。这允许Tomcat自动地redirect那些试图访问有安全限制页面的用户，指明根据 Servlet 2.4 Specification要求，SSL是必需的。

有一些额外的选项被用来配置SSL协定。依赖于你早先怎样配置你的keystore，你也许需要添加或更改下列属性值：

属性 | 描述
clientAuth | 如果你想要Tomcat要求所有的SSL客户在使用这个socket时出示用户认证书，把这个值设定为 true 。如果你想要Tomcat要求出示用户认证书，但是如果没有认证书也可以， 就把这个值设定为want 。
keystoreFile | 如果你产生的keystore文件不在Tomcat期望的默认地方(一个叫做.keystore 的文件在Tomcat运行的主目录)，就添加这个属性。你可以指定一个绝对路径名称， 或者一个由$CATALINA_BASE环境变量而派生的相对路径名称。
keystorePass | 如果你使用一个不同的keystore(以及认证书)密码，而不是Tomcat期望的密码 (就是changeit)，添加这个元素。
keystoreType | 如果使用一个PKCS12 keystore的话，就添加这个element。 有效的值是JKS 和 PKCS12 。
sslProtocol | 要在这个socket上被使用的加密／解密协定。如果你在使用Sun的JVM，我们不提倡更改 这个值。据报道，TLS协定的IBM's 1.4.1 实现与一些通用的浏览器不兼容。 如果是这样，就使用value SSL 。
ciphers | 这个socket允许使用的由逗号分隔开的加密密码列单。默认的情况下，任何可用的密码都允许被使用。
algorithm | 可用的X509算法。默认是Sun的实现( SunX509 )。 对于IBM JVMs，你应该使用值 IbmX509。对于其他卖主，查阅JVM文档资料来 找正确的值。
truststoreFile | 用来验证用户认证书的TrustStore文件。
truststorePass | 访问TrustStore的密码。默认值就是keystorePass的值。
truststoreType | 如果你在使用与KeyStore不同格式的TrustStore，添加这个元素。 合法的值是JKS和PKCS12。
keyAlias | 如果 keystore 里面有多个 key，你可以为用这个选项为加入的 key 起一个名字。 如果没有指定名字，使用时 keystore 内的第一个 key 将会被使用。

在完成这些配置更改后，你必须象通常那样重新启动Tomcat，然后你就可以工作了。 你应该可以通过SSL访问Tomcat支持的任何web应用程序。例如，试一下下面的指令：

https://localhost:8443

你应该看到通常的Tomcat splash页面(除非你修改过ROOT web应用程序)。如果不行的话， 下面的章节包含一些排除故障的提示。

安装和获取认证权威颁发的认证书

要从认证权威(如verisign.com, thawte.com 或 trustcenter.de)获得并安装认证书， 你应该先阅读前面章节，然后再按照下面的指示进行：

产生一个认证签名请求 (CSR)

为了从你选择的认证权威那里获得认证书，你必须产生一个所谓的认证签名请求(Certificate Signing Request (CSR))。这个认证签名请求被认证权威用来产生鉴定你的网站是“安全的”的认证书。 按照下列步骤产生一个CSR：

  • 产生一个局部认证书(如前面章节描述那样):
    keytool -genkey -alias tomcat -keyalg RSA \
   -keystore &lt;your_keystore_filename&gt;
    注意：在某些情况下， 要产生一个工作认证书，你必须在“"first- and lastname" field 键入你的网站的域名 (例如www.jaxmao.org)。
  • 然后用下列指令产生CSR ：
    keytool -certreq -keyalg RSA -alias tomcat
-file certreq.csr \
   -keystore &lt;your_keystore_filename&gt;

执行这个命令之后你会得到一个文件叫 certreq.csr。然后你可以到发送到认证权威， 然后你就可以得到你的认证书。具体步骤可以参考他们的网站的帮助文件。

导入认证书

现在你有了认证书，你可以把它输入到你局部的keystore里。首先你必须输入一个叫做证书链 Chain Certificate 或 Root Certificate 到你的 keystore 里去。在这之后，你可以开始 输入你的认证书。

  • 从你获得认证书的认证权威那里下载一个Chain Certificate 。
    For Verisign.com commercial certificates go to: http://www.verisign.com/support/install/intermediate.html
    For Verisign.com trial certificates go to: http://www.verisign.com/support/verisign-intermediate-ca/Trial_Secure_Server_Root/index.html For Trustcenter.de go to: http://www.trustcenter.de/certservices/cacerts/en/en.htm#server
    对于Thawte.com ， 去http://www.thawte.com/certs/trustmap.html下载
  • 把Chain Certificate 输入到你的keystore里边
    keytool -import -alias root -keystore &lt;your_keystore_filename&gt; \
   -trustcacerts -file &lt;filename_of_the_chain_certificate&gt;
  • 最后输入你的新的认证书
    keytool -import -alias tomcat -keystore &lt;your_keystore_filename&gt; \
   -trustcacerts -file &lt;your_certificate_filename&gt;
Troubleshooting

这里是一些你在设置SSL通信时也许会遇到的常见问题，以及如何解决它们。

  • 我在我的日志文件中得到"java.security.NoSuchAlgorithmException"错误。

    JVM找不到JSSE JAR 文件。按照所有的指导说明 下载并安装JSSE。

  • 当Tomcat启动时，我得到一个象 "java.io.FileNotFoundException: {some-directory}/{some-file} not found"的异常。

    一个可能的解释是Tomcat不能在它要找的地方找到 keystore文件。在默认的情况下， Tomcat预计 keystore文件在Tomcat运行的用户主目录里被命名为.keystore。 如果 keystore存放在别的什么地方，你需要向Tomcat配置文件里的 &lt;Factory&gt;元素添加一个 keystoreFile属性。

  • 当Tomcat启动时，我得到一个象"java.io.FileNotFoundException: Keystore was tampered with, or password was incorrect"的异常。

    如果没有其他人 试图 修改你的 keystore 文件，最可能的情况是 Tomcat 用了错误的密码。你可以尝试重新产生 keystore 文件，或修改 Tomcat 设置文件里 <Connector> 元素的 keystorePass 属性，还请记住密码是分大小写的。

如果你仍然有问题，一个好的地方你可找到帮助是 TOMCAT-USER 邮件列表。你可以 用下面的地址订阅。 http://tomcat.apache.org/lists.html.

Miscellaneous Tips and Bits

你可以用下面的办法获取用户 SSL session 的 ID：
String sslID = (String)request.getAttribute("javax.servlet.request.ssl_session");
你可从下面的网址获得更多这方面的信息： Bugzilla.


Apache Tomcat 5.5 Servlet/JSP 容器 - Project Status

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

Project Status

 Printer Friendly Version
print-friendly
version
前言

本文的意图是为各位介绍Tomcat开发的现状，而没有提供有关某个臭虫是否已经被改正或 Tomcat是否支持某个功能。

This page is updated roughly once per every couple of Tomcat minor releases, so for day-to-day status you should check the tomcat-user and tomcat-dev mailing lists. You can always inquire there as to the availability or status of a specific feature or component.

Current Status Summary

Tomcat 5.0.27 在2004 年6月17日发表。 那时起 TOMCAT_5_0 在 CVS 里面开始分枝， Tomcat 5.5正是开始开发。 Tomcat 5.5 已经发表了几个稳定版。Tomcat 5.5是现在所有工作的 重点。Tomcat 5.0只是处于维护状态，它的修正版会发表的越来越少。

Tomcat 5.5 有几个主要目标。可以从下面的连接看到。 MARC. The status of some of these items is detailed below. Once 5.5 releases are available, please refer to the Changelog accompanying each release for detailed changes, enhancements, and fixes.

Tomcat 4.1.x is no longer actively developed. It is maintained to address only showstopper, security, and Servlet Specification compliance issues. Maintenance for Tomcat 4.1.x will likely cease once a stable release or two of Tomcat 5.5 are out. Users of Tomcat 4.1.x are strongly encouraged to upgrade to the latest stable Tomcat 5.0 release.

Tomcat 4.0.x is relatively old, and not actively maintained or supported. It is strongly recommended that users of these releases upgrade to the latest stable Tomcat 5.0 release or at least the latest stable Tomcat 4.1 release.

Tomcat 3.3.x is in roughly the same maintenance mode as Tomcat 4.1.x.

Tomcat 3.2 and earlier are in roughly the same support state as Tomcat 4.0.x. Users should upgrade to Tomcat 3.3.x or the latest stable Tomcat 5.0.x.

How to read the report

The columns in this report contain the following information:

  • Priority - A sense of how important it is to address this issue in the short term.
  • Action Item - Concise description of the action item to be completed. Where relevant, Java package names of the primary classes involved are listed in [square brackets]
  • Volunteers - Login of those developers who have volunteered to assist in the design, implementation, testing, and documentation of this action item's changes to Tomcat.
Developers can nominate themselves to work on particular action items by asking a Committer to add their name address to those items. The developers working on each item should discuss and agree upon the approach to be used for implementing the item's changes to the project source code and documentation, prior to completing those changes. Such discussions should take place on the tomcat-dev mailing list so that everyone can stay apprised of what is going on, or chime in if they want to contribute ideas and suggestions.

TODO List
Priority | Action Item | Volunteers
High | Refactor ClassLoaders for Tomcat 5.5 to allow container plugins. | costin
Medium | Enhance Cluster functionality for Tomcat 5.5. | fhanik
Medium | Continue fixing bugs and updating docs. | everyone
Open bugs

The list of the bugs which are in an unresolved state for Tomcat 5 can be seen here. Aspiring volunteers and others are strongly encouraged to attempt to comment and help resolve these issues.


Apache Tomcat 5.5 Servlet/JSP 容器 - 如何把Tomcat注册为视窗的服务

Apache Tomcat Servlet/JSP 容器

链接

  • 文档首页
  • 中文用户论坛
  • 常见问题

用户手册

  • 1) 介绍
  • 2) 安装
  • 3) 第一个web应用
  • 4) 部署
  • 5) 管理
  • 6) 权限管理 - 域(Realms)
  • 7) 安全管理器
  • 8) JNDI 资源
  • 9) JDBC 数据源
  • 10) 类加载
  • 11) JSPs
  • 12) SSL
  • 13) SSI
  • 14) CGI
  • 15) 与代理器整合
  • 16) MBean 描述
  • 17) 默认 Servlet
  • 18) 集群
  • 19) 负载均衡
  • 20) 连接器
  • 21) 监控 与 管理
  • 22) 日志
  • 23) APR

参考

  • 发行注记
  • Apache Tomcat 配置
  • JK 1.2 文档
  • Servlet API Javadocs
  • JSP API Javadocs

Apache Tomcat 开发

  • 构建
  • 修订记录
  • 状态
  • 开发者
  • 性能说明.
  • Apache Tomcat Javadocs
  • Apache Jasper Javadocs
  • 体系架构

Apache Tomcat 5.5 Servlet/JSP 容器

如何把Tomcat注册为视窗的服务

 Printer Friendly Version
print-friendly
version
NOTICE

本说明适用于procrun 1.0，现已淘汰。

Tomcat5应用程序

Tomcat5 是一个可以在视窗NT下注册为服务的程序。

Tomcat5w监视程序

Tomcat5w 是一个可用来监视和修改 Tomcat 设置的程序，它有方便使用的界面。

指令选项：

//ES// | 修改设置 | 这是却省是的选项。 运行命令的名称将以servicenameW.exe出现
//MS// | 监视程序运行状况 | 代表程序运行的小图标会出现在视窗有下角

指令行选项

指令行选项的格式为： //XX//ServiceName

现有指令行的选项：

//TS// | 把服务按控制台模式运行 | 不过没有提供其他选项，这是缺省运行模式。其中ServiceName时是可运行文件的名字去 掉exe后缀，这里是Tomcat5
//RS// | 运行为系统的服务 | 由系统ServiceManager来执行
//SS// | 停止服务
//US// | 更新属性
//IS// | 把Tomcat安装为系统的服务
//DS// | 删除Tomcat服务 | 如果Tomcat服务正在运行，这个指令首先终止Tomcat

指令行允许的属性

每个属性都以--开始。以++的属性会给附加在已有的属性里。 如果有系统环境变量的名称与指令的属性相同，有PR_前缀的优先。 例如：

set PR_CLASSPATH=xx.jar

与下面的指令项属性效果一样：

--Classpath=xx.jar

属性名称 | 默认值 | 描述
--Description | 描述Tomcat服务，最多1024个字符
--DisplayName | 名称 | 服务显示的名称
--Install | procrun.exe //RS//ServiceName | 安装服务
--Startup | manual | 启动服务的状态，可以是 auto 或 manual
--DependsOn | 罗列Tomcat服务必须依赖的其他系统服务。如果有多个服务，用# 或 ;符号来分开
--Environment | 罗列需要提供给该服务的环境变量。格式为： key=value. 用 # 或 ; 符号来区分
--User | 用来运行该指令的用户名。只是用在 StartMode 下的 java 或 exe，这样可以使Tomcat服务以没有 LogonAsService 特权的用户的名义来运行。
--Password | --User 所列用户的密码
JAVA_HOME | JAVA_HOME | 可以定义一个不同于系统的JAVA_HOME环境变量，指定使用不同的Java
--Jvm | auto | 允许的值为auto或jvm.dll的完整路径。 路径中可以有环境变量出现。
--JvmOptions | -Xrs | Java虚拟机器的选项。都用-D or -X开始， 将会被传递给JVM。 选项间用 # or ;字符隔开。
--Classpath | 设置Java的classpath环境变量
--JvmMs | 指定开始时所用的内存，单位是MB
--JvmMx | 最大内存，单位用MB
--JvmSs | Thread stack size in KB
--StartImage | 可运行文件
--StartPath | 程序运行时的工作目录
--StartClass | 程序开始时执行的类
--StartParams | 需要传递个程序的变量数值，变量用#或 ;字符分隔
--StartMethod | main | 如果开始执行类中的方法名称，可以不是 main()
--StartMode | 可运行文件 exe | 可以是jvm java 或 exe
--StopImage | 收到终止信号后运行的文件名
--StopPath | 收到终止信号后运行文件的工作目录
--StopClass | 收到终止信号后运行的Java类
--StopParams | 需要传递个终止信号后运行文件的变量数值。变量用# 或 ; 字符分开
--StopMethod | main | 收到终止信号后运行的Java类中的开始方法，可以不是main()
--StopMode | 运行文件 | 可以是jvm java 或exe；中的一个
--StopTimeout | 没有限制 | 定义 procrun 需要等待多少秒让程序安全退出。
--LogPath | 工作目录 | 定义日志所在目录
--LogPrefix | jakarta_service | 定义日志文件名称
--LogLevel | info | 定义日志写入的底限，可以是 error, info, warn 或 debug
--StdOutput | 把标准输出导入到文件的文件名
--StdError | 把错误输出stderr导入到文件的文件名

安装服务

最方便安全的办法是用 Tomcat 提供的service.bat脚本文件。

安装名为'Tomcat5'的服务
C:\> service.bat install

如果你使用 tomcat5.exe，你需要用//IS//选项

安装名为'Tomcat5'的服务
C:\> tomcat5 //IS//Tomcat5 --DisplayName="Apache Tomcat 5" \
C:\> --Install="C:\Program Files\Tomcat\bin\tomcat5.exe" --Jvm=auto \
C:\> --StartMode=jvm --StopMode=jvm \
C:\> --StartClass=org.apache.catalina.startup.Bootstrap --StartParams=start \
C:\> --StopClass=org.apache.catalina.startup.Bootstrap --StopParams=stop

更新服务

更新服务的变量，用 //US// 选项

更新服务'Tomcat5
C:\> tomcat5 //US//Tomcat5 --Description="Apache Tomcat Server - http://tomcat.apache.org/ " \
C:\> --Startup=auto --Classpath=%JAVA_HOME%\lib\tools.jar;%CATALINA_HOME%\bin\bootstrap.jar

删除服务

如果你要删除服务，用 //DS// 变量。
如果该服务正在运行，它先会被终止运行，然后删除。

删除名为'Tomcat5'的服务
C:\> tomcat5 //DS//Tomcat5

纠错

如果需要让服务在控制台运行，用 //TS// 选项。 该服务可用 CTRL+C 或 CTRL+BREAK终止。 如果你把 tomcat5.exe 重新命名为 testservice.exe， 那么你只要运行 testservice.exe， 控制模式是缺省的模式。

用控制台模式运行 'Tomcat5'
C:\> tomcat5 //TS//Tomcat5 [更多变量]
或简单运行:
C:\> tomcat5


<!--
     General purpose build script for web applications and web services,
     including enhanced support for deploying directly to a Tomcat 5
     based server.

     This build script assumes that the source code of your web application
     is organized into the following subdirectories underneath the source
     code directory from which you execute the build script:

        docs                 Static documentation files to be copied to
                             the "docs" subdirectory of your distribution.

        src                  Java source code (and associated resource files)
                             to be compiled to the "WEB-INF/classes"
                             subdirectory of your web applicaiton.

        web                  Static HTML, JSP, and other content (such as
                             image files), including the WEB-INF subdirectory
                             and its configuration file contents.

     $Id: build.xml.txt 302898 2004-05-23 19:50:44Z markt $
-->

<!-- A "project" describes a set of targets that may be requested
     when Ant is executed.  The "default" attribute defines the
     target which is executed if no specific target is requested,
     and the "basedir" attribute defines the current working directory
     from which Ant executes the requested task.  This is normally
     set to the current working directory.
-->

<project name="My Project" default="compile" basedir=".">

<!-- ===================== Property Definitions =========================== -->

<!--

  Each of the following properties are used in the build script.
  Values for these properties are set by the first place they are
  defined, from the following list:

  * Definitions on the "ant" command line (ant -Dfoo=bar compile).

  * Definitions from a "build.properties" file in the top level
    source directory of this application.

  * Definitions from a "build.properties" file in the developer's
    home directory.

  * Default definitions in this build.xml file.

  You will note below that property values can be composed based on the
  contents of previously defined properties.  This is a powerful technique
  that helps you minimize the number of changes required when your development
  environment is modified.  Note that property composition is allowed within
  "build.properties" files as well as in the "build.xml" script.

-->

  <property file="build.properties"/>
  <property file="${user.home}/build.properties"/>

<!-- ==================== File and Directory Names ======================== -->

<!--

  These properties generally define file and directory names (or paths) that
  affect where the build process stores its outputs.

  app.name             Base name of this application, used to
                       construct filenames and directories.
                       Defaults to "myapp".

  app.path             Context path to which this application should be
                       deployed (defaults to "/" plus the value of the
                       "app.name" property).

  app.version          Version number of this iteration of the application.

  build.home           The directory into which the "prepare" and
                       "compile" targets will generate their output.
                       Defaults to "build".

  catalina.home        The directory in which you have installed
                       a binary distribution of Tomcat 5.  This will
                       be used by the "deploy" target.

  dist.home            The name of the base directory in which
                       distribution files are created.
                       Defaults to "dist".

  manager.password     The login password of a user that is assigned the
                       "manager" role (so that he or she can execute
                       commands via the "/manager" web application)

  manager.url          The URL of the "/manager" web application on the
                       Tomcat installation to which we will deploy web
                       applications and web services.

  manager.username     The login username of a user that is assigned the
                       "manager" role (so that he or she can execute
                       commands via the "/manager" web application)

-->

  <property name="app.name"      value="myapp"/>
  <property name="app.path"      value="/${app.name}"/>
  <property name="app.version"   value="0.1-dev"/>
  <property name="build.home"    value="${basedir}/build"/>
  <property name="catalina.home" value="../../../.."/> <!-- UPDATE THIS! -->
  <property name="dist.home"     value="${basedir}/dist"/>
  <property name="docs.home"     value="${basedir}/docs"/>
  <property name="manager.url"   value="http://localhost:8080/manager"/>
  <property name="src.home"      value="${basedir}/src"/>
  <property name="web.home"      value="${basedir}/web"/>

<!-- ================== Custom Ant Task Definitions ======================= -->

<!--

  These properties define custom tasks for the Ant build tool that interact
  with the "/manager" web application installed with Tomcat 5.  Before they
  can be successfully utilized, you must perform the following steps:

  - Copy the file "server/lib/catalina-ant.jar" from your Tomcat 5
    installation into the "lib" directory of your Ant installation.

  - Create a "build.properties" file in your application's top-level
    source directory (or your user login home directory) that defines
    appropriate values for the "manager.password", "manager.url", and
    "manager.username" properties described above.

  For more information about the Manager web application, and the functionality
  of these tasks, see <http://localhost:8080/tomcat-docs/manager-howto.html>.

-->

  <taskdef name="deploy"   classname="org.apache.catalina.ant.DeployTask"/>
  <taskdef name="list"     classname="org.apache.catalina.ant.ListTask"/>
  <taskdef name="reload"   classname="org.apache.catalina.ant.ReloadTask"/>
  <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/>

<!--  ==================== Compilation Control Options ==================== -->

<!--

  These properties control option settings on the Javac compiler when it
  is invoked using the <javac> task.

  compile.debug        Should compilation include the debug option?

  compile.deprecation  Should compilation include the deprecation option?

  compile.optimize     Should compilation include the optimize option?

-->

  <property name="compile.debug"       value="true"/>
  <property name="compile.deprecation" value="false"/>
  <property name="compile.optimize"    value="true"/>

<!-- ==================== External Dependencies =========================== -->

<!--

  Use property values to define the locations of external JAR files on which
  your application will depend.  In general, these values will be used for
  two purposes:
  * Inclusion on the classpath that is passed to the Javac compiler
  * Being copied into the "/WEB-INF/lib" directory during execution
    of the "deploy" target.

  Because we will automatically include all of the Java classes that Tomcat 5
  exposes to web applications, we will not need to explicitly list any of those
  dependencies.  You only need to worry about external dependencies for JAR
  files that you are going to include inside your "/WEB-INF/lib" directory.

-->

<!-- Dummy external dependency -->
<!--
  <property name="foo.jar"
           value="/path/to/foo.jar"/>
-->

<!-- ==================== Compilation Classpath =========================== -->

<!--

  Rather than relying on the CLASSPATH environment variable, Ant includes
  features that makes it easy to dynamically construct the classpath you
  need for each compilation.  The example below constructs the compile
  classpath to include the servlet.jar file, as well as the other components
  that Tomcat makes available to web applications automatically, plus anything
  that you explicitly added.

-->

  <path id="compile.classpath">

    <!-- Include all JAR files that will be included in /WEB-INF/lib -->
    <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
<!--
    <pathelement location="${foo.jar}"/>
-->

    <!-- Include all elements that Tomcat exposes to applications -->
    <pathelement location="${catalina.home}/common/classes"/>
    <fileset dir="${catalina.home}/common/endorsed">
      <include name="*.jar"/>
    </fileset>
    <fileset dir="${catalina.home}/common/lib">
      <include name="*.jar"/>
    </fileset>
    <pathelement location="${catalina.home}/shared/classes"/>
    <fileset dir="${catalina.home}/shared/lib">
      <include name="*.jar"/>
    </fileset>

  </path>

<!-- ==================== All Target ====================================== -->

<!--

  The "all" target is a shortcut for running the "clean" target followed
  by the "compile" target, to force a complete recompile.

-->

  <target name="all" depends="clean,compile"
   description="Clean build and dist directories, then compile"/>

<!-- ==================== Clean Target ==================================== -->

<!--

  The "clean" target deletes any previous "build" and "dist" directory,
  so that you can be ensured the application can be built from scratch.

-->

  <target name="clean"
   description="Delete old build and dist directories">
    <delete dir="${build.home}"/>
    <delete dir="${dist.home}"/>
  </target>

<!-- ==================== Compile Target ================================== -->

<!--

  The "compile" target transforms source files (from your "src" directory)
  into object files in the appropriate location in the build directory.
  This example assumes that you will be including your classes in an
  unpacked directory hierarchy under "/WEB-INF/classes".

-->

  <target name="compile" depends="prepare"
   description="Compile Java sources">

    <!-- Compile Java classes as necessary -->
    <mkdir    dir="${build.home}/WEB-INF/classes"/>
    <javac srcdir="${src.home}"
          destdir="${build.home}/WEB-INF/classes"
            debug="${compile.debug}"
      deprecation="${compile.deprecation}"
         optimize="${compile.optimize}">
        <classpath refid="compile.classpath"/>
    </javac>

    <!-- Copy application resources -->
    <copy  todir="${build.home}/WEB-INF/classes">
      <fileset dir="${src.home}" excludes="**/*.java"/>
    </copy>

  </target>

<!-- ==================== Dist Target ===================================== -->

<!--

  The "dist" target creates a binary distribution of your application
  in a directory structure ready to be archived in a tar.gz or zip file.
  Note that this target depends on two others:

  * "compile" so that the entire web application (including external
    dependencies) will have been assembled

  * "javadoc" so that the application Javadocs will have been created

-->

  <target name="dist" depends="compile,javadoc"
   description="Create binary distribution">

    <!-- Copy documentation subdirectories -->
    <mkdir   dir="${dist.home}/docs"/>
    <copy    todir="${dist.home}/docs">
      <fileset dir="${docs.home}"/>
    </copy>

    <!-- Create application JAR file -->
    <jar jarfile="${dist.home}/${app.name}-${app.version}.war"
         basedir="${build.home}"/>

    <!-- Copy additional files to ${dist.home} as necessary -->

  </target>

<!-- ==================== Install Target ================================== -->

<!--

  The "install" target tells the specified Tomcat 5 installation to dynamically
  install this web application and make it available for execution.  It does
  *not* cause the existence of this web application to be remembered across
  Tomcat restarts; if you restart the server, you will need to re-install all
  this web application.

  If you have already installed this application, and simply want Tomcat to
  recognize that you have updated Java classes (or the web.xml file), use the
  "reload" target instead.

  NOTE:  This target will only succeed if it is run from the same server that
  Tomcat is running on.

  NOTE:  This is the logical opposite of the "remove" target.

-->

  <target name="install" depends="compile"
   description="Install application to servlet container">

    <deploy url="${manager.url}"
       username="${manager.username}"
       password="${manager.password}"
           path="${app.path}"
       localWar="file://${build.home}"/>

  </target>

<!-- ==================== Javadoc Target ================================== -->

<!--

  The "javadoc" target creates Javadoc API documentation for the Java
  classes included in your application.  Normally, this is only required
  when preparing a distribution release, but is available as a separate
  target in case the developer wants to create Javadocs independently.

-->

  <target name="javadoc" depends="compile"
   description="Create Javadoc API documentation">

    <mkdir          dir="${dist.home}/docs/api"/>
    <javadoc sourcepath="${src.home}"
                destdir="${dist.home}/docs/api"
           packagenames="*">
      <classpath refid="compile.classpath"/>
    </javadoc>

  </target>

<!-- ====================== List Target =================================== -->

<!--

  The "list" target asks the specified Tomcat 5 installation to list the
  currently running web applications, either loaded at startup time or
  installed dynamically.  It is useful to determine whether or not the
  application you are currently developing has been installed.

-->

  <target name="list"
   description="List installed applications on servlet container">

    <list    url="${manager.url}"
        username="${manager.username}"
        password="${manager.password}"/>

  </target>

<!-- ==================== Prepare Target ================================== -->

<!--

  The "prepare" target is used to create the "build" destination directory,
  and copy the static contents of your web application to it.  If you need
  to copy static files from external dependencies, you can customize the
  contents of this task.

  Normally, this task is executed indirectly when needed.

-->

  <target name="prepare">

    <!-- Create build directories as needed -->
    <mkdir  dir="${build.home}"/>
    <mkdir  dir="${build.home}/WEB-INF"/>
    <mkdir  dir="${build.home}/WEB-INF/classes"/>

    <!-- Copy static content of this web application -->
    <copy todir="${build.home}">
      <fileset dir="${web.home}"/>
    </copy>

    <!-- Copy external dependencies as required -->
    <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->
    <mkdir  dir="${build.home}/WEB-INF/lib"/>
<!--
    <copy todir="${build.home}/WEB-INF/lib" file="${foo.jar}"/>
-->

    <!-- Copy static files from external dependencies as needed -->
    <!-- *** CUSTOMIZE HERE AS REQUIRED BY YOUR APPLICATION *** -->

  </target>

<!-- ==================== Reload Target =================================== -->

<!--

  The "reload" signals the specified application Tomcat 5 to shut itself down
  and reload. This can be useful when the web application context is not
  reloadable and you have updated classes or property files in the
  /WEB-INF/classes directory or when you have added or updated jar files in the
  /WEB-INF/lib directory.

  NOTE: The /WEB-INF/web.xml web application configuration file is not reread
  on a reload. If you have made changes to your web.xml file you must stop
  then start the web application.

-->

  <target name="reload" depends="compile"
   description="Reload application on servlet container">

    <reload url="${manager.url}"
       username="${manager.username}"
       password="${manager.password}"
           path="${app.path}"/>

  </target>

<!-- ==================== Remove Target =================================== -->

<!--

  The "remove" target tells the specified Tomcat 5 installation to dynamically
  remove this web application from service.

  NOTE:  This is the logical opposite of the "install" target.

-->

  <target name="remove"
   description="Remove application on servlet container">

    <undeploy url="${manager.url}"
         username="${manager.username}"
         password="${manager.password}"
             path="${app.path}"/>

  </target>

</project>


应用开发人员指南 - 部署

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Introduction
  • Installation
  • Deployment
  • Source Code
  • Processes
  • Example App

应用开发人员指南

部署

 Printer Friendly Version
print-friendly
version
Background

在描述怎样组织你的源代码目录(source code directories)之前，有必要考察一下一个网络应用程序的运行时间(runtime)的组织结构。在Servlet API规范2.2版之前，各个服务器平台不是很(统一)一致。然而，遵守2.2(以及其后版)规范的服务器都被要求接受标准格式的网络应用档案(Web Application Archive),我们在下面会再讨论到这点。

一个网络应用程序可以说是由标准规划布局的一些文件和目录组成的一个阶层(hierarchy)。这样一个阶层以“未包装”的形式存取，这种形式就是指每个目录和文件在文件系统里分离存在；或者以“包装过”的形式存取，这种形式就是所谓的网络档案，或WAR文件。前面一种格式在程序开发时比较有用，而后者在你需要把可被安装使用的程序进行分配(distribute)时适用。

网络应用程序阶层的最顶层目录也就是应用程序的文件根(document root)。你将要把组成应用程序的用户接口的HTML和JSP页面放在这里。当系统管理员(system administrator)把你的应用程序调度到一个特定的服务器时，他(她)会给你的应用程序指派一个context path(这个手册的后半部会描述Tomcat的调度)。这样，如果系统管理员把你的应用程序指派给context path /catalog,那么一个有关/catalog/index.html 的URI请求(request)就会从你的文件根那里检索出index.html 文件。

Standard Directory Layout

为了便于按要求格式产生网络应用程序档案,合适的办法就是按照WAR的格式(format)把你的应用程序里的“可执行”文件(就是Tomcat用来执行你的程序的文件)放在同样一个组织结构里。按照这种做法，下面的有关内容应该放置在你的应用程序的“文件根”目录里。

  • *.html, *.jsp, etc. - HTML和JSP页面，还有其他相关文件(比如象JavaScript,stylesheet文件以及图象)应该被客户浏览器看到。对于较大的应用程序，你可以选择把这些文件分配到分支目录(subdirectory)中去，但对于小的应用程序，通常把这些文件放在一个目录里比较简单。

  • /WEB-INF/web.xml - 网络应用程序调度描述符。这是一个可扩充标记语言(XML)文件，它描述了构成你的程序的servlets和其他部件，同时也描述了初始化参数(initialization parameters)，以及你想要服务器执行的有关容器管理安全性的限制。以后的章节里对这个文件会有详细的讨论。

  • /WEB-INF/classes/ - 这个目录包含应用程序里必需的Java类文件(以及相关的资源)，包括没有被组合到JAR文件里的servlet和non-servlet类。如果把你的类文件组织成Java包(package)，你必须把这点也反映在/WEB-INF/classes/ .下的目录里。例如，一个叫做com.mycompany.mypackage.MyServlet 的Java class,应该被放在文件/ WEB-INF/classes/com/mycompany/mypackage/MyServlet.class里面。

  • /WEB-INF/lib/ - 这个目录包括由Java类文件(以及相关资源)组成的JAR文件，比如象其他第三类class libraries或JDBC驱动程式(drivers)。

当你把程序安装在Tomcat里(或其他2.2/2.3相兼容的服务器上)，那些在WEB-INF/classes/目录里的classes,以及其所有的WEB-INF/lib/目录里JAR文件里的classes,对于你的程序里的其他类来说都是可视的。这样，如果你把所必须的library classes放在上面所提到的地址之一（要检查一下你是否具有重新分配third party libraries的权限），你就可以把你的程序安装简单化-- 不需要调整你的系统class path(或者在你的服务器上安装全局库文件(global library files))。

这里的许多信息摘录自第九章Servlet应用编程界面规范，2.3版，详细内容请到那里参考。

Shared Library Files

和许多servlet容器一样，Tomcat支持这样一种机制，那就是安装library JAR文件(或未被包装的classes),使它们可被已安装的程序使用。关于Tomcat是怎样定位和共享这些类的详细内容在Class Loader HOW-TO 文件里有描述。我们这里仅讨论在Tomcat里安装共享编码时二个通用的地址。

  • $CATALINA_HOME/common/lib - 放在这里的JAR文件既可被网络应用程序看见，又可被Tomcat内部编码看见(visible). 最好是把JDBC驱动程式放在这里，JDBC驱动程式是你的程序和Tomcat内部使用所必需的东西(如JDBCRealm)。

  • $CATALINA_BASE/shared/lib - JAR files placed here are visible to all web applications, but not to internal Tomcat code. This is the right place for shared libraries that are specific to your application.

除此之外，标准的Tomcat5安装包括了一些先已安装好的共享文件库，它们包括：

  • The Servlet 2.4和JSP 2.0 APIs，它们是写servlets和JavaServer Pages的基础。

  • 和JAXP(1.2版)应用编程接口相兼容的可扩充标记语言语法分析程式(XML Parser)，这样你的程序可执行DOM-based 或者SAX-based XML文件。

Web Application Deployment Descriptor

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

如上面所提到的，/WEB-INF/web.xml 文件包括了你的程序所使用的网络应用调度描述符。从文件的附注档名(filename extension)就可以知道这是个XML文件，它描述了服务器所需要知道的关于你的程序的所有情况(context path 除外，它是由系统管理员在调度你的程序时指派的)。

完整的关于调度描述符的语法及语义在第13章the Servlet应用编程接口规范，2.3版有定义。希望在将来能够有开发工具来帮你制作和编辑调度描述符。一个basic web.xml 文件给你提供了一个起点。这个文件包含了用来解说每一个元素用途的注释。

注意— The Servlet规范为网络应用程序调度描述符提供了一个文档类型描述符(DTD)，同时Tomcat5在运行你的应用程序/WEB-INF/web.xml 文件时，强制执行这里定义的有关规责。特别地，你必须按DTD规定的顺序输入你的描述符元素(如 &lt;filter&gt; , &lt;servlet&gt; , and &lt;servlet-mapping&gt;)(参看13.3章节)。

Tomcat Context Descriptor

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

一个/META-INF/context.xml 文件可用来定义Tomcat特有的配置选项,如loggers, data sources, session manager 的配置及其他。这个XML文件必须包括一个上下文元素(Context element)，这个元素是Host元素的子元素，Tomcat配置文档中Host元素的注释里有Context元素的详细信息。

Deployment With Tomcat 5

为了能被执行，一个网络应用程序必须要被调度到servlet容器上。在开发程序时也是这样。我们将要描述应用Tomcat来提供一个可执行环境。可以用下面的几种方法在Tomcat里调度你的程序。

  • 把未包装的目录层次复制在$CATALINA_HOME/webapps/目录下面的分目录里。基于你选择的分目录名称， Tomcat会给你的程序指派一个上下文路径(context path)。因为这是开发程序时最快最简易的方法， 我们把这个技术用在我们自己构造的build.xml 文件里。确保在安装和更新你的程序后重新启动Tomcat。

  • 把网络应用程序档案文件复制在$CATALINA_HOME/webapps/目录里。当Tomcat启动时，它会自动把网络应用程序档案文件扩展成为未包装形式，同时执行它。这种处理办法通常用来把第三类卖主或者内部开发人员提供的额外的程序加入到已经存在的Tomcat安装里。注意—如果你用这种办法，又希望在以后更新你的程序，你必须更新网络应用程序档案文件,和同时删除Tomcat产生的扩展目录，然后重新启动Tomcat，这样才能反映出更改。

  • 利用Tomcat5"管理员"网络应用程序来部署(deploy)和反部署(undeploy)网络应用程序。Tomcat5里面包含一个被部署在context path /manager 上的程序，允许你在运行中的Tomcat服务器上进行部署和反部署，而不需要重新启动它。关于使用管理员网络程序(the Manager web application)的更多信息，请参看 administrator 文档资料(TODO: hyperlink)。

  • 使用“管理员”Ant Tasks来制作Script。Tomcat5包括一系列定义Ant build工具的用户化作业(task)，允许你对“管理员”网络程序自动执行命令。这些作业(tasks)被用在Tomcat调度员里。

  • 使用Tomcat调度员。Tomcat5包含一个全包装的工具来绑定(bundling)Ant作业，也可以用于自动预编译JSPs——这些JSP在被调度到服务器之前是网络应用程序的一部分。

把程序调度到其他servlet容器上的方式对每个容器都是特定的，不过所有和Servlet API Specification(2.2以及其后版本)相适宜的容器，都被要求接受网络应用程序档案文件。注意，其他容器没有被要求(象Tomcat那样)接受未包装的目录结构，或者提供共享文件库的机制，不过它们通常都有这些特性。


应用开发人员指南 - 目录

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Introduction
  • Installation
  • Deployment
  • Source Code
  • Processes
  • Example App

应用开发人员指南

目录

 Printer Friendly Version
print-friendly
version
Preface

这个手册包括了来自Tomcat Project开发人员社团许多成员的贡献。 下面的作者提供了非常重要的内容。

  • Craig R. McClanahan (craigmcc@apache.org)
Table of Contents

这些信息被分为下面几部分：

  • 简介- 简单地描述了本段内容。同时还具有通向其他信息源的链接(links)和索引(reference)。
  • 安装(Installation)- 涵盖了怎样获得和安装所需的软件成分，以便使用 Tomcat进行网络应用开发。
  • 部署组织(Deployment Organization)- 讨论关于网络应用程序的标准目录布局(Servlet API Specification 里有定义)， 网络应用程序部署描述符(Deployment Descriptor), 以及怎样把Tomcat整合到你的开发环境的各种选项。
  • 源代码组织(Source Organization)- 描述了一个组织你项目源代码目录的有用的途经，同时介绍了Ant里的 build.xml来管理编译。
  • 开发过程(Development Processes)- 简短地描述了怎样利用推荐的调度和源代码组织来进行开发的典型过程。
  • 应用程序示例(Example Application)- 这个目录包括了一个非常简单，但功能完整的"Hello,World"应用程序, (这个程序)是根据这个手册描述的原则来构造的，你可以使用这个程序去练习这里所描述的技能方法。


应用开发人员指南 - 安 装

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Introduction
  • Installation
  • Deployment
  • Source Code
  • Processes
  • Example App

应用开发人员指南

安 装

 Printer Friendly Version
print-friendly
version
Installation

要使用Tomcat5来开发网站应用程序,你必须先安装它(以及它所以赖的其他软件)。下面的章节里概述了必须的步骤。

JDK

Tomcat 5.5被设计适合在J2SE 5.0上运行，但是它也可以在JDK 1.4上运行，请使用与Tomcat 5.5相兼容的软件包，这在Tomcat installation里有详细说明。

请到http://java.sun.com/j2se/ .去查找和许多操作平台相适宜的JDKs。

Tomcat

Binary downloads of the Tomcat server are available from http://tomcat.apache.org/download-55.cgi. This manual assumes you are using the most recent release of Tomcat 5. Detailed instructions for downloading and installing Tomcat 5 are available here.

在这个手册的后面有shell scripts的样本。 我们假设你设置好了环境变量CATALINA_HOME,它里面的路径(pathname)应该指向已安装的Tomcat5所在目录。

Ant

从http://ant.apache.org/bindownload.cgi可以下载Ant建造工具。这个手册假设你使用Ant1.4或其后版本。这里的指示说明应该和Ant1.4以后的版本相适合，但还没有被测试过。

从上面提到的网址下载和安装Ant。然后，把Ant distribution里的bin directory加入到你的路径(PATH)环境变量里，按常规操作你的系统平台。在完成这些之后，你就可以直接执行ant shell命令了。

CVS

除了上面所描述的必须工具以外，我们非常鼓励你去下载和安装源代码控制系统(source code control systems),比如象Concurrent Version Systems(CVS),用来维护管理你的网络应用程序的historical版源代码文件。除了服务器以外，你还需要相应的客户(client)工具来取出(check out)源代码文件,和存入(check in)修改过的版本。

关于安装和使用源代码控制应用的详细说明超除了着个手册的范围。不过，可以从http://www.cvshome.org .下载适用于许多平台上的CVS服务器和客户工具(以及其文献)。


应用开发人员指南 - 简介

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Introduction
  • Installation
  • Deployment
  • Source Code
  • Processes
  • Example App

应用开发人员指南

简介

 Printer Friendly Version
print-friendly
version
Overview

祝贺你！你决定(或被告知)学习使用servlets和JSP页面来建立网络应用程序，同时选定Tomcat服务器(server)来学习和开发。但是你现在该做些什么呢？

这是一个入门手册，它包括了使用Tomcat来设立开发环境，组织源代码，以及构造和测试你的应用程序的基本步骤。这里没有讨论网络应用开发的体系结构(architectures)或者推荐的编码惯例，也没有提供关于怎样使用操作开发工具的详细说明。其他的有关信息来源和参考文献包括在下面的章节里。

这个手册是针对那些使用文字编辑器(text editor)和指令线路工具(command line tools)来进行开发和排错的开发人员用的。 因此，这里的介绍非常通用--你可以很容易地把它们应用在Window-based或者Unix-based开发环境里。如果你使用的是互动开发环境(IDE)的工具，你就需要根据这里的建议作一些改变来适应具体的(计算机应用)环境。

Links

下面的链连(Links)让你可以进入其他网站去查看网络信息，文献和软件，它们对于用Tomcat开发网络应用程序很有帮助。

  • http://java.sun.com/products/jsp/download.html - JavaServer Pages (JSP)规范,1.2版。描述了JSP技术标准实现所规定的编程环境。和Servlet API规范一起，这个文件描述了一个可移植的应用编程界面(API)的页面允许包含什么内容。 其中关于scripting(第六章), tag extension(第七章)和JSP页面包装(附录A)的特别信息都很有用。 Javadoc API文件包括在这个规范里，可以和Tomcat一起下载。

  • http://java.sun.com/products/servlet/download.html - Servlet应用编程界面规范(Specification),2.3版，描述了所有遵守这一规范的servlet容器(container)所必须提供的编程环境。 特别的是，你需要这个文件来理解网络应用目录结构和文件调度(第九章)，映射(mapping)URIs需求和servlet的方法(第十一章)，容器安全管理性(第十二章)，以及有关web.xml网络应用开发描述符的语法(syntax)(第十三章)。Javadoc API文件包括在这个规范里，可以和Tomcat一起下载。

  • http://java.sun.com/j2ee/blueprints/ - 阳升J2EE设计图本指南。 提供了对于包括Servlet和JSP页面在内的Java2 企业版本(J2EE)平台应用设计的综合建议和样本。即使你的应用程序不需要使用其他J2EE平台组件，关于servlet和JSP设计的章节还是非常有用的。

  • TODO -- Add more entries here!


应用开发人员指南 - 开发过程(Development Processes)

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Introduction
  • Installation
  • Deployment
  • Source Code
  • Processes
  • Example App

应用开发人员指南

开发过程(Development Processes)

 Printer Friendly Version
print-friendly
version
Development Processes

尽管可以采取多种形式来进行应用开发, 这个手册提议以一种标准样本处理方式来利用Tomcat产生web应用程序。以下部分着重强调了作为编程开发人员将执行的命令和任务。只要你有一个适当的源代码控制系统，以及内部条文规定什么人在什么时间内做哪一部分工作，那么当你有多个程序员一起开发程序时，这种基本的处理方法应该行得通。

下面对于工作程序的描述是假设你将使用CVS作为源代码控制系统，以及你已经配置好了相关CVS贮藏库的通路。关于使用和配置CVS的说明超出了本手册的范围。如果你使用不同的源代码控制环境，你要自己弄清楚那个系统的相关命令。

One-Time Setup of Ant and Tomcat for Development

为了使用和管理员(Manager)网络程序相互作用的特别Ant任务，你需要执行一次以下的任务(不管你计划要开发多少个web程序)。

  • 配置Ant custom tasks 。关于Ant custom tasks 的实施代码是在一个叫做$CATALINA_HOME/server/lib/catalina-ant.jar的JAR文件里，它必须被复制到ant安装目录的lib目录中。

  • 定义一个或多个Tomcat用户。管理员(Manager)这个网络程序有安全限制，它要求用户必须注册登记(logged in)，并具有Manager指派的安全职责。 怎样定义这些用户依赖于你在Tomcat's conf/server.xml文件里配置的领域(Realm)——更多信息请参看Realm Configuration HOW-TO。管理员(Manager)可以定义任何数目的用户(任何用户名称和密码)。

Create Project Source Code Directory

第一步就是要产生一个新的项目源目录，并客户化需要使用的build.xml 和build.properties 文件。关于目录结构(directory structure)在上一章有描述，或者你可以使用sample application作为一个起始点。

产生一个项目源目录，并把它定义在你的CVS 贮藏库之内。这可以通过下面这样一系列命令来实现，这里{project}是指你储存在CVS 贮藏库中project的名称，{username}是指你的登录用户名称。

cd {my home directory}
mkdir myapp   &lt;-- Assumed "project source directory"
cd myapp
mkdir docs
mkdir src
mkdir web
mkdir web/WEB-INF
cvs import -m "Initial Project Creation" {project} \
   {username} start

现在, 我们来执行一次checkout这个新项目，以核实它在CVS里被正确地产生了。

cd ..
mv myapp myapp.bu
cvs checkout {project}

再次, 你将需要产生和登记一个初始版本的 build.xml script来用作软件开发。要简易快捷地开始，你可以在这个手册里的basic build .xml 文件基础上产生build.xml，或者从头开始编码它。

cd {my home directory}
cd myapp
emacs build.xml      &lt;-- if you want a real editor :-)
cvs add build.xml
cvs commit

直到你执行CVS commit之前, 你的这些变动还是局限在你自己的开发目录。Committing使得共用同一CVS 贮藏库的同组的其它开发人员可以看得见你的这些更改。

下一步就是要把build.xml script里命名的Ant属性(properties)客户化。这需要在你的项目的上层目录产生一个叫做build.properties的文件。Tomcat支持的属性(properties)被列出在样本build.xml script的注释中。至少，你必须定义catalina.home的属性，这个属性指出了Tomcat 5 被安装在哪里以及管理员程序里的用户名称和密码。你的编码也许象这样:

# Context path to install this application on
app.path=/hello

# Tomcat 5 installation directory
catalina.home=/usr/local/apache-tomcat-5.5

# Manager webapp username and password
manager.username=myusername
manager.password=mypassword

通常，你不要把这个build.properties 文件存入CVS 贮藏库, 因为它对每个开发人员的工作环境来说都是特定的。

现在, 产生初始版本的网络应用调度描述符(web application deployment descriptor)。你可以在basic web. xml 文件基础上产生web.xml，或者从头编码它。

cd {my home directory}
cd myapp/web/WEB-INF
emacs web.xml
cvs add web.xml
cvs commit
注意，这只是一个web.xml 文件的例子。Servlet 规范里对调度描述符(deployment descriptor)文件有完整的定义。
Edit Source Code and Pages

Edit/build/test(编辑/建造/测试)是开发和维护中最常见的活动。以下一般性原则适用。如源代码组织(Source Organization)所描述，新产生的源文件应该被放在项目源目录之下适当的subdirectory。

当你要把其他开发人员的工作加入到你的开发目录时，就让CVS执行下面的任务：

cd {my home directory}
cd myapp
cvs update -dP

要产生一个新文件，到相关的目录产生这个文件并在CVS注册(register)它。当你(在创建和测试成功之后)对它的内容感到满意，你就把这个新文件commit给贮藏库。例如，下面来产生一个新的JSP页面：

cd {my home directory}
cd myapp/web      &lt;-- Ultimate destination is document root
emacs mypage.jsp
cvs add mypage.jsp
... build and test the application ...
cvs commit

被定义在包裹(packages)里的源代码必须要被组织成一个和包裹名称相对映的目录阶层(在src/ subdirectory之下)。 例如，一个叫做com.mycompany.mypackage.MyClass.java 的Java类，必须被存放在文件src&#47;com&#47;mycompany&#47;mypackage&#47;MyClass.java 里面。不论你什么时候产生一个新的子目录，别忘记去CVS注册

要编辑一个现有源文件, 你一般只是开始编辑并且测试, 当程序全都能正常运作后再把这个被改变的文件commit。虽然CVS可能被配置成要求你"check out" 或"lock" 你将修改的文件，但通常我们不这样做。

Build the Web Application

当你准备好编译你的程序时, 发布以下命令(通常, 你打开一个指向项目源目录的shell窗口，这样一来只需要使用最后一句命令)：

cd {my home directory}
cd myapp      &lt;-- Normally leave a window open here
ant

Ant工具会在你的build.xml文件执行缺省"compile"目标,从而编译任何新的或更新过的Java 代码。如果这是你在"build clean"后第一次编译，它将导致所有的程序被重新编译(recompiled)一次。

要强制执行重新编译全部程序，应用下面的命令：

cd {my home directory}
cd myapp
ant all

在checking in 更改之前这样做是个非常好的习惯，这样可以确保不会产生一些Javac的conditional检查没有捕捉住的任何微妙问题。

Test Your Web Application

要测试你的程序,你要把它安装在Tomcat 之下。最快捷的方法就是使用样本build.xml script里的用户Ant任务。也许可以象这样使用这些命令：

  • 按需要启动Tomcat 5。如果Tomcat 5 已经不在运行，你需要按常规启动它。

  • 编译你的程序。使用这个ant compile命令(或者仅仅ant，因为这是缺省命令)。确准没有编辑错误。

  • 安装程序。使用ant install 命令。这个命令告诉Tomcat立刻在context path 上运行你的程序，app.path build 属性里对context path有定义。Tomcat不要被重新启动就能生效。

  • 测试程序。使用你的浏览器或者其它测试工具, 测试你的程序的功能。

  • 根据必要修改(modify)和重建(rebuild)。当你发现需要进行更改时,去原始的源代码文件(original source files)进行修改,而不是在output build 目录,然后再使用ant compile命令。这就保证了你的变动能在以后被保存下来(通过cvs commit)—— output build 目录根据需要会被删除和被再创造。

  • 重新装载你的程序。Tomcat自动地识别JSP页面里的变化，但它将继续使用老版本的servlet 或 JavaBean classes直到你的程序被重新装载为止。你能通过执行ant reload命令使其发生。

  • 完成所有过程后删除你的程序。当你完成所有过程之后，使用ant remove 命令把你的程序从现场执行(live execution)中删除。

当你完成测试后，别忘记把更改过的文件commit到源代码贮藏库去！

Creating a Release

当你完成了添加新功能到你的程序中去，又测试了所有的东西，下面就可以产生一个distributable 版本的网络程序了，这个版本可被调度到生产服务器(production server)上去。以下通常的步骤是需要的：

  • 从项目源目录里发出ant all 命令，来最后一次rebuild 所有程序。

  • 使用cvs tag 命令为所有在发行版里所用到的源文件产生一个标识符(identifier)。这允许你在以后可以可靠地(从源代码文件)重新产生一个发行版本。
  • 发出ant dist命令来产生一个可发布的网络应用档案(WAR)文件，和包含对应的源代码的JAR文件。

  • 根据你们公司(组织)使用的标准发行规程，用tar或者zip共用程序包装这个dist目录里的内容。


应用开发人员指南 - 源代码组织(Source Organization)

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Introduction
  • Installation
  • Deployment
  • Source Code
  • Processes
  • Example App

应用开发人员指南

源代码组织(Source Organization)

 Printer Friendly Version
print-friendly
version
Directory Structure

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

这个手册特别建议你把包含源代码的目录阶层(本章节所描述的)和包含可调度程序的目录阶层(前面章节所描述的)分开。保持这种分离有下面几种好处：

  • 如果没有和“可运行”版的程序相混合，源代码目录里的内容就比较容易来管理，移动和备份(backup)。

  • 在只含有源代码文件的目录里，管理控制源代码就比较容易。

  • 当可调度阶层目录被分开后，就比较容易来选择那些组成可安装分配(installable distribution)程序的文件。

我们将会看到，ant开发工具使得产生和处理这样的目录阶层非常容易。

你可以随意组织用来包含程序源代码的目录和文件阶层。不过，下面的这种组织结构被证明非常实用可行，也是下面将要讨论的例子build.xml配置文件(configuration file)所期望的。所有的这些组成成分存在于你的应用程序的最上层项目源代码目录下面。

  • docs/ —— 关于你的应用程序的文档资料，可以用你们开发组使用的任何格式(format)。

  • src/ —— Java源代码文件，它们是用于产生你的程序特有的servlets, beans, 和其他Java classes。如果你的源代码被组织成包(packages)(我们极力推荐),这个包阶层(hierarchy)就应该被放置这个目录下面。

  • web/ —— 组成你网站的静态文件(HTML页面，JSP页面，JavaScript文件，CSS stylesheet文件，和图象)，这些文件都可以让客户存取(accessible)。这个目录是你的网络程序的文件根(document root)目录，它的任何子目录中的文件可通过浏览器来读取。

  • web/WEB-INF/ —— 你的程序所需的特别的配置文件,包括网络应用程序调度符(web.xml,在Servlet规范里有定义),你为用户标记库(custom tag libraries)所产生的标记库描述符,以及其他你想要包括在网络程序里的资源文件(resource files)。尽管这个目录显得象是文件根目录(document root)的分目录(subdirectory),但是Servlet规范不允许客户能直接使用这个目录里的内容(或它包含的任何文件)。所以，这是一个不错的地方来储存那些程序顺利运行所必须的，但又是非常敏感的配置信息(比如数据库连接用的用户名称及密码)。

在程序开发过程中，会临时产生另外两个目录：

  • build/ —— 执行默认ant指令后，会在这个目录中产生与web应用档案(WAR)完全相同的文件。Tomcat5允许你在象这样未包装的目录里调度程序，你可以把此目录复制到$CATALINA_HOME/webapps 目录上去，或通过“管理者”(Manager)程序把它安装上去。后面的这种处理方式在开发程序中非常有用，下面我们会作些说明。

  • dist/ —— 当你执行ant dist目标后，就会在这个目录中产生与你的网络程序binary distribution 完全相同的文件，包括许可证信息，文档资料和README 文件。

注意 — 不要把这两个目录存档在你的源代码控制系统里，因为这两个目录会在程序开发中根据需要被删除或重新产生。正是因为这个原因，如果你想要保留一个关于程序更改的固定记录，你就不要在这两个目录里编辑源代码文件，因为下一次执行build命令时，所有的程序更改就会被遗失掉。

External Dependencies

如果你的程序需要外部的项目或包(packages)里的JAR文件(或其他资源)，那你应该怎么办呢？一个通常的例子就是你必需在你的程序中引入JDBC驱动程式才能运作。

不同的开发人员采用不同的方式来处理这个问题。有些开发人员会鼓励你对于每一个需要那些JAR文件的程序，把它所依赖的JAR文件复制到源代码控制存档(archives)上。不过，当你在许多程序中使用同样一个JAR文件——特别是当你面临着需要升级(upgrade)到不同版本的JAR文件时，就会产生很严重的管理上的问题。

因此,这个手册提倡不要把你所需要的packages的复制件存放在程序的源代码控制档案里。相反，你应该把这些外部依赖性文件整合到创建你的程序的过程中去。这样一来，你总是可以从系统管理员安装JAR文件的地方选择合适版本的JAR文件，而不用担心每次在你所依赖的JAR文件更改后，要去更新你的程序。

在例子Ant build.xml 文件中，我们将示范怎样去定义那些让你能够配置复制文件地址的build properties，而不需要在这些文件更改时去修改 build.xml 。每个开发人员使用的build属性(properties)可以根据每个不同的程序客户化，或者默认作(defaulted to）“标准”build属性存放在开发人员的主目录(home directory)中。

在许多情况下，系统管理员可能已经把必需的JAR文件安装到Tomcat 5 的 common/lib 或者shared/lib 目录里。如果这已经被做好了，你就不需要再做什么——例子build.xml 会自动创造一个包含这些文件的compile classpath 。

Source Code Control

如先前提到的,我们极力建议你把组成你程序的所有源代码文件放置在一个象Concurrent Version System (CVS)一样的源代码控制系统下来管理。如果你选择这么做，在这个源代码阶层里的每一个目录和文件都会被注册和保存——但是所有产生的文件都不会被注册和保存。如果你注册二进制形式的文件(如图象或JAR库)，一定要指示你的源代码控制系统。

我们(在前面一段)建议你不要把你在开发程序过程中产生的build/ 和dist/ 目录中的内容存放在源代码控制系统里。一个简单的办法让CVS忽略这两个目录就是在你的上层源代码目录中产生一个叫做.cvsignore(注意前面有一个句点)的文件，它应该包括下面这些内容：

build
dist
build.properties

对于在这里提及build.properties的理由，我们会在开发过程这一章节里作解释。

关于源代码控制环境的详细说明超过了本手册的范围。不过，如果你使用命令行的CVS客户端，你要遵守下面的步骤：

  • 要更新储存在源代码储存器(source repository)里的源代码,得到你的源代码目录中去执行cvs update -dP。

  • 当你要在源代码目录阶层产生一个新的子目录(subdirectory)，得到CVS使用象cvs add {子目录名称(subdirname)}的命令来注册。

  • 当你首次产生一个新的源代码文件，找到包括源代码的目录，并用诸如象cvs add {filename}这样的命令来注册这个新文件。

  • 如果你不再需要某个特定的源代码文件，找到包括这个文件的目录，并且删除它。然后在CVS使用象cvs remove {filename}这样的命令来注销这个文件。

  • 在你产生，修改和删除源代码文件时，这些改变还没有反映在服务器端的储存器里。要保持目前的更改，得到项目的源代码目录去执行cvs commit 。你会被要求简述你刚才完成的更改，然后和新版本的源代码文件一起被储存下来。

CVS,象其他源代码控制系统一样，有许多额外的特性(比如能够对特定发行版的文件进行标记，支持开发多个分枝版本—这些分枝在以后可以被合并)。更多信息请参看简介中的链连(link)和参考资料(reference)。

BUILD.XML Configuration File

我们将利用ant工具来管理编译Java源代码文件，以及产生调度目录层次。Ant在一个构建(build)文件控制下操作，通常叫做build.xml，它定义了必需的开发过程的步骤。这个文件储存在你的源代码目录层次的最上层，必须把它读入(check in)到你的源代码控制系统中去。

就象一个Makefile，build.xml文件提供了几个“目标”("target")来支持可选择性的开发活动(比如产生相关的Javadoc文件，擦除调度主目录以便你能从头开始你的项目，或者产生网络应用档案文件以便你可以分配你的程序)。一个构造不错的build.xml文件应该包括描述说明那些设计给开发人员使用的目标(target)的内部文件，以及这些内部使用的目标。要求Ant显示项目的说明资料，你要更换到含有build.xml的目录下，然后打印命令：

ant -projecthelp

为了让你能先做起来，我们提供了basic build.xml 文件，你可以对它用户化并把它安装在你的项目源代码目录中。这个文件包括了描述各种可被执行目标的注释。简单地说，它通常提供了下面的这些目标：

  • 清除(clean)——这个目标删除既存的build 和dist 目录，这样它们可以被重新构造。这样确保你不可能发生因为修改源代码，但没有重新编译(recompiling)所有affected classes，而在运行时出现问题。

  • 编译(compile)——这个目标是用来编译那些自从上次编译后被更改过的源代码。所产生的类文件(class files)被放置在build目录下的子目录WEB-INF/classes 里面，和网络应用程序的结构所要求完全一致的地方。因为这个命令在开发程序过程中经常被执行，所以通常把它设置为“默认（default）”目标，这样一来简单的ant命令就可以执行它。

  • all ——这个目标是一个用来先执行清除目标，然后再执行编译目标的捷径(short cut)。因此，它确保你重新编译所有的程序，这样可以保证你不会在不知不觉中引入一些不相适宜的改变。

  • javadoc ——这个目标产生网络程序中Java类的Javadoc API文档资料。例子build.xml 文件中假设你想把API文档资料包括在你要发表的程序中，所以它把产生的文档资料(docs)放在dist目录下的子目录里。因为你通常不需要在每次编译时都产生Javadocs API文档资料，所以这个目标和dist目标相关联，而与compile目标无关。

  • dist ——这个目标给你的程序产生一个分配目录，包括必要的文档资料，Java类的Javadocs，网络应用档案(WAR)文件，这个WAR文件将被传送给需要安装你的程序的系统管理员。因为这个目标也依赖于deploy目标，网络应用档案还应包括必需的外部文件。

为了用Tomcat5进行互动开发和测试你的程序，我们定义了下面额外的几个目标(targets)：

  • 安装(install)——告诉正在运行的Tomcat5使你开发的程序可被立即用于执行和测试。它不需要重新启动Tomcat5。

  • 重新装载(reload)—— 一但程序安装后，你可以继续更改和用compile目标重新编译。Tomcat5 会自动识别JSP页面里的更改，但不能识别servlet 或 JavaBean 类里的更改——这个命令会告诉Tomcat重新启动最近安装的程序，这样这些改变就会被认可。

  • 删除(remove)——当你完成了开发和测试活动，你可以选择性地告诉Tomcat5把这些程序去掉。

利用开发和测试目标还需要额外的一些一次性设置，这一点我们在下一页会讨论。


应用开发人员指南 - 部署

The Tomcat Servlet/JSP Container

应用开发人员指南

部署
Background

在描述怎样组织你的源代码目录(source code directories)之前，有必要考察一下一个网络应用程序的运行时间(runtime)的组织结构。在Servlet API规范2.2版之前，各个服务器平台不是很(统一)一致。然而，遵守2.2(以及其后版)规范的服务器都被要求接受标准格式的网络应用档案(Web Application Archive),我们在下面会再讨论到这点。

一个网络应用程序可以说是由标准规划布局的一些文件和目录组成的一个阶层(hierarchy)。这样一个阶层以“未包装”的形式存取，这种形式就是指每个目录和文件在文件系统里分离存在；或者以“包装过”的形式存取，这种形式就是所谓的网络档案，或WAR文件。前面一种格式在程序开发时比较有用，而后者在你需要把可被安装使用的程序进行分配(distribute)时适用。

网络应用程序阶层的最顶层目录也就是应用程序的文件根(document root)。你将要把组成应用程序的用户接口的HTML和JSP页面放在这里。当系统管理员(system administrator)把你的应用程序调度到一个特定的服务器时，他(她)会给你的应用程序指派一个context path(这个手册的后半部会描述Tomcat的调度)。这样，如果系统管理员把你的应用程序指派给context path /catalog,那么一个有关/catalog/index.html 的URI请求(request)就会从你的文件根那里检索出index.html 文件。

Standard Directory Layout

为了便于按要求格式产生网络应用程序档案,合适的办法就是按照WAR的格式(format)把你的应用程序里的“可执行”文件(就是Tomcat用来执行你的程序的文件)放在同样一个组织结构里。按照这种做法，下面的有关内容应该放置在你的应用程序的“文件根”目录里。

  • *.html, *.jsp, etc. - HTML和JSP页面，还有其他相关文件(比如象JavaScript,stylesheet文件以及图象)应该被客户浏览器看到。对于较大的应用程序，你可以选择把这些文件分配到分支目录(subdirectory)中去，但对于小的应用程序，通常把这些文件放在一个目录里比较简单。

  • /WEB-INF/web.xml - 网络应用程序调度描述符。这是一个可扩充标记语言(XML)文件，它描述了构成你的程序的servlets和其他部件，同时也描述了初始化参数(initialization parameters)，以及你想要服务器执行的有关容器管理安全性的限制。以后的章节里对这个文件会有详细的讨论。

  • /WEB-INF/classes/ - 这个目录包含应用程序里必需的Java类文件(以及相关的资源)，包括没有被组合到JAR文件里的servlet和non-servlet类。如果把你的类文件组织成Java包(package)，你必须把这点也反映在/WEB-INF/classes/ .下的目录里。例如，一个叫做com.mycompany.mypackage.MyServlet 的Java class,应该被放在文件/ WEB-INF/classes/com/mycompany/mypackage/MyServlet.class里面。

  • /WEB-INF/lib/ - 这个目录包括由Java类文件(以及相关资源)组成的JAR文件，比如象其他第三类class libraries或JDBC驱动程式(drivers)。

当你把程序安装在Tomcat里(或其他2.2/2.3相兼容的服务器上)，那些在WEB-INF/classes/目录里的classes,以及其所有的WEB-INF/lib/目录里JAR文件里的classes,对于你的程序里的其他类来说都是可视的。这样，如果你把所必须的library classes放在上面所提到的地址之一（要检查一下你是否具有重新分配third party libraries的权限），你就可以把你的程序安装简单化-- 不需要调整你的系统class path(或者在你的服务器上安装全局库文件(global library files))。

这里的许多信息摘录自第九章Servlet应用编程界面规范，2.3版，详细内容请到那里参考。

Shared Library Files

和许多servlet容器一样，Tomcat支持这样一种机制，那就是安装library JAR文件(或未被包装的classes),使它们可被已安装的程序使用。关于Tomcat是怎样定位和共享这些类的详细内容在Class Loader HOW-TO 文件里有描述。我们这里仅讨论在Tomcat里安装共享编码时二个通用的地址。

  • $CATALINA_HOME/common/lib - 放在这里的JAR文件既可被网络应用程序看见，又可被Tomcat内部编码看见(visible). 最好是把JDBC驱动程式放在这里，JDBC驱动程式是你的程序和Tomcat内部使用所必需的东西(如JDBCRealm)。

  • $CATALINA_BASE/shared/lib - JAR files placed here are visible to all web applications, but not to internal Tomcat code. This is the right place for shared libraries that are specific to your application.

除此之外，标准的Tomcat5安装包括了一些先已安装好的共享文件库，它们包括：

  • The Servlet 2.4和JSP 2.0 APIs，它们是写servlets和JavaServer Pages的基础。

  • 和JAXP(1.2版)应用编程接口相兼容的可扩充标记语言语法分析程式(XML Parser)，这样你的程序可执行DOM-based 或者SAX-based XML文件。

Web Application Deployment Descriptor

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

如上面所提到的，/WEB-INF/web.xml 文件包括了你的程序所使用的网络应用调度描述符。从文件的附注档名(filename extension)就可以知道这是个XML文件，它描述了服务器所需要知道的关于你的程序的所有情况(context path 除外，它是由系统管理员在调度你的程序时指派的)。

完整的关于调度描述符的语法及语义在第13章the Servlet应用编程接口规范，2.3版有定义。希望在将来能够有开发工具来帮你制作和编辑调度描述符。一个basic web.xml 文件给你提供了一个起点。这个文件包含了用来解说每一个元素用途的注释。

注意— The Servlet规范为网络应用程序调度描述符提供了一个文档类型描述符(DTD)，同时Tomcat5在运行你的应用程序/WEB-INF/web.xml 文件时，强制执行这里定义的有关规责。特别地，你必须按DTD规定的顺序输入你的描述符元素(如 &lt;filter&gt; , &lt;servlet&gt; , and &lt;servlet-mapping&gt;)(参看13.3章节)。

Tomcat Context Descriptor

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

一个/META-INF/context.xml 文件可用来定义Tomcat特有的配置选项,如loggers, data sources, session manager 的配置及其他。这个XML文件必须包括一个上下文元素(Context element)，这个元素是Host元素的子元素，Tomcat配置文档中Host元素的注释里有Context元素的详细信息。

Deployment With Tomcat 5

为了能被执行，一个网络应用程序必须要被调度到servlet容器上。在开发程序时也是这样。我们将要描述应用Tomcat来提供一个可执行环境。可以用下面的几种方法在Tomcat里调度你的程序。

  • 把未包装的目录层次复制在$CATALINA_HOME/webapps/目录下面的分目录里。基于你选择的分目录名称， Tomcat会给你的程序指派一个上下文路径(context path)。因为这是开发程序时最快最简易的方法， 我们把这个技术用在我们自己构造的build.xml 文件里。确保在安装和更新你的程序后重新启动Tomcat。

  • 把网络应用程序档案文件复制在$CATALINA_HOME/webapps/目录里。当Tomcat启动时，它会自动把网络应用程序档案文件扩展成为未包装形式，同时执行它。这种处理办法通常用来把第三类卖主或者内部开发人员提供的额外的程序加入到已经存在的Tomcat安装里。注意—如果你用这种办法，又希望在以后更新你的程序，你必须更新网络应用程序档案文件,和同时删除Tomcat产生的扩展目录，然后重新启动Tomcat，这样才能反映出更改。

  • 利用Tomcat5"管理员"网络应用程序来部署(deploy)和反部署(undeploy)网络应用程序。Tomcat5里面包含一个被部署在context path /manager 上的程序，允许你在运行中的Tomcat服务器上进行部署和反部署，而不需要重新启动它。关于使用管理员网络程序(the Manager web application)的更多信息，请参看 administrator 文档资料(TODO: hyperlink)。

  • 使用“管理员”Ant Tasks来制作Script。Tomcat5包括一系列定义Ant build工具的用户化作业(task)，允许你对“管理员”网络程序自动执行命令。这些作业(tasks)被用在Tomcat调度员里。

  • 使用Tomcat调度员。Tomcat5包含一个全包装的工具来绑定(bundling)Ant作业，也可以用于自动预编译JSPs——这些JSP在被调度到服务器之前是网络应用程序的一部分。

把程序调度到其他servlet容器上的方式对每个容器都是特定的，不过所有和Servlet API Specification(2.2以及其后版本)相适宜的容器，都被要求接受网络应用程序档案文件。注意，其他容器没有被要求(象Tomcat那样)接受未包装的目录结构，或者提供共享文件库的机制，不过它们通常都有这些特性。


应用开发人员指南 - 目录

The Tomcat Servlet/JSP Container

应用开发人员指南

目录
Preface

这个手册包括了来自Tomcat Project开发人员社团许多成员的贡献。 下面的作者提供了非常重要的内容。

  • Craig R. McClanahan (craigmcc@apache.org)
Table of Contents

这些信息被分为下面几部分：

  • 简介- 简单地描述了本段内容。同时还具有通向其他信息源的链接(links)和索引(reference)。
  • 安装(Installation)- 涵盖了怎样获得和安装所需的软件成分，以便使用 Tomcat进行网络应用开发。
  • 部署组织(Deployment Organization)- 讨论关于网络应用程序的标准目录布局(Servlet API Specification 里有定义)， 网络应用程序部署描述符(Deployment Descriptor), 以及怎样把Tomcat整合到你的开发环境的各种选项。
  • 源代码组织(Source Organization)- 描述了一个组织你项目源代码目录的有用的途经，同时介绍了Ant里的 build.xml来管理编译。
  • 开发过程(Development Processes)- 简短地描述了怎样利用推荐的调度和源代码组织来进行开发的典型过程。
  • 应用程序示例(Example Application)- 这个目录包括了一个非常简单，但功能完整的"Hello,World"应用程序, (这个程序)是根据这个手册描述的原则来构造的，你可以使用这个程序去练习这里所描述的技能方法。


应用开发人员指南 - 安 装

The Tomcat Servlet/JSP Container

应用开发人员指南

安 装
Installation

要使用Tomcat5来开发网站应用程序,你必须先安装它(以及它所以赖的其他软件)。下面的章节里概述了必须的步骤。

JDK

Tomcat 5.5被设计适合在J2SE 5.0上运行，但是它也可以在JDK 1.4上运行，请使用与Tomcat 5.5相兼容的软件包，这在Tomcat installation里有详细说明。

请到http://java.sun.com/j2se/ .去查找和许多操作平台相适宜的JDKs。

Tomcat

Binary downloads of the Tomcat server are available from http://tomcat.apache.org/download-55.cgi. This manual assumes you are using the most recent release of Tomcat 5. Detailed instructions for downloading and installing Tomcat 5 are available here.

在这个手册的后面有shell scripts的样本。 我们假设你设置好了环境变量CATALINA_HOME,它里面的路径(pathname)应该指向已安装的Tomcat5所在目录。

Ant

从http://ant.apache.org/bindownload.cgi可以下载Ant建造工具。这个手册假设你使用Ant1.4或其后版本。这里的指示说明应该和Ant1.4以后的版本相适合，但还没有被测试过。

从上面提到的网址下载和安装Ant。然后，把Ant distribution里的bin directory加入到你的路径(PATH)环境变量里，按常规操作你的系统平台。在完成这些之后，你就可以直接执行ant shell命令了。

CVS

除了上面所描述的必须工具以外，我们非常鼓励你去下载和安装源代码控制系统(source code control systems),比如象Concurrent Version Systems(CVS),用来维护管理你的网络应用程序的historical版源代码文件。除了服务器以外，你还需要相应的客户(client)工具来取出(check out)源代码文件,和存入(check in)修改过的版本。

关于安装和使用源代码控制应用的详细说明超除了着个手册的范围。不过，可以从http://www.cvshome.org .下载适用于许多平台上的CVS服务器和客户工具(以及其文献)。


应用开发人员指南 - 简介

The Tomcat Servlet/JSP Container

应用开发人员指南

简介
Overview

祝贺你！你决定(或被告知)学习使用servlets和JSP页面来建立网络应用程序，同时选定Tomcat服务器(server)来学习和开发。但是你现在该做些什么呢？

这是一个入门手册，它包括了使用Tomcat来设立开发环境，组织源代码，以及构造和测试你的应用程序的基本步骤。这里没有讨论网络应用开发的体系结构(architectures)或者推荐的编码惯例，也没有提供关于怎样使用操作开发工具的详细说明。其他的有关信息来源和参考文献包括在下面的章节里。

这个手册是针对那些使用文字编辑器(text editor)和指令线路工具(command line tools)来进行开发和排错的开发人员用的。 因此，这里的介绍非常通用--你可以很容易地把它们应用在Window-based或者Unix-based开发环境里。如果你使用的是互动开发环境(IDE)的工具，你就需要根据这里的建议作一些改变来适应具体的(计算机应用)环境。

Links

下面的链连(Links)让你可以进入其他网站去查看网络信息，文献和软件，它们对于用Tomcat开发网络应用程序很有帮助。

  • http://java.sun.com/products/jsp/download.html - JavaServer Pages (JSP)规范,1.2版。描述了JSP技术标准实现所规定的编程环境。和Servlet API规范一起，这个文件描述了一个可移植的应用编程界面(API)的页面允许包含什么内容。 其中关于scripting(第六章), tag extension(第七章)和JSP页面包装(附录A)的特别信息都很有用。 Javadoc API文件包括在这个规范里，可以和Tomcat一起下载。

  • http://java.sun.com/products/servlet/download.html - Servlet应用编程界面规范(Specification),2.3版，描述了所有遵守这一规范的servlet容器(container)所必须提供的编程环境。 特别的是，你需要这个文件来理解网络应用目录结构和文件调度(第九章)，映射(mapping)URIs需求和servlet的方法(第十一章)，容器安全管理性(第十二章)，以及有关web.xml网络应用开发描述符的语法(syntax)(第十三章)。Javadoc API文件包括在这个规范里，可以和Tomcat一起下载。

  • http://java.sun.com/j2ee/blueprints/ - 阳升J2EE设计图本指南。 提供了对于包括Servlet和JSP页面在内的Java2 企业版本(J2EE)平台应用设计的综合建议和样本。即使你的应用程序不需要使用其他J2EE平台组件，关于servlet和JSP设计的章节还是非常有用的。

  • TODO -- Add more entries here!


应用开发人员指南 - 开发过程(Development Processes)

The Tomcat Servlet/JSP Container

应用开发人员指南

开发过程(Development Processes)
Development Processes

尽管可以采取多种形式来进行应用开发, 这个手册提议以一种标准样本处理方式来利用Tomcat产生web应用程序。以下部分着重强调了作为编程开发人员将执行的命令和任务。只要你有一个适当的源代码控制系统，以及内部条文规定什么人在什么时间内做哪一部分工作，那么当你有多个程序员一起开发程序时，这种基本的处理方法应该行得通。

下面对于工作程序的描述是假设你将使用CVS作为源代码控制系统，以及你已经配置好了相关CVS贮藏库的通路。关于使用和配置CVS的说明超出了本手册的范围。如果你使用不同的源代码控制环境，你要自己弄清楚那个系统的相关命令。

One-Time Setup of Ant and Tomcat for Development

为了使用和管理员(Manager)网络程序相互作用的特别Ant任务，你需要执行一次以下的任务(不管你计划要开发多少个web程序)。

  • 配置Ant custom tasks 。关于Ant custom tasks 的实施代码是在一个叫做$CATALINA_HOME/server/lib/catalina-ant.jar的JAR文件里，它必须被复制到ant安装目录的lib目录中。

  • 定义一个或多个Tomcat用户。管理员(Manager)这个网络程序有安全限制，它要求用户必须注册登记(logged in)，并具有Manager指派的安全职责。 怎样定义这些用户依赖于你在Tomcat's conf/server.xml文件里配置的领域(Realm)——更多信息请参看Realm Configuration HOW-TO。管理员(Manager)可以定义任何数目的用户(任何用户名称和密码)。

Create Project Source Code Directory

第一步就是要产生一个新的项目源目录，并客户化需要使用的build.xml 和build.properties 文件。关于目录结构(directory structure)在上一章有描述，或者你可以使用sample application作为一个起始点。

产生一个项目源目录，并把它定义在你的CVS 贮藏库之内。这可以通过下面这样一系列命令来实现，这里{project}是指你储存在CVS 贮藏库中project的名称，{username}是指你的登录用户名称。

cd {my home directory}
mkdir myapp   &lt;-- Assumed "project source directory"
cd myapp
mkdir docs
mkdir src
mkdir web
mkdir web/WEB-INF
cvs import -m "Initial Project Creation" {project} \
   {username} start

现在, 我们来执行一次checkout这个新项目，以核实它在CVS里被正确地产生了。

cd ..
mv myapp myapp.bu
cvs checkout {project}

再次, 你将需要产生和登记一个初始版本的 build.xml script来用作软件开发。要简易快捷地开始，你可以在这个手册里的basic build .xml 文件基础上产生build.xml，或者从头开始编码它。

cd {my home directory}
cd myapp
emacs build.xml      &lt;-- if you want a real editor :-)
cvs add build.xml
cvs commit

直到你执行CVS commit之前, 你的这些变动还是局限在你自己的开发目录。Committing使得共用同一CVS 贮藏库的同组的其它开发人员可以看得见你的这些更改。

下一步就是要把build.xml script里命名的Ant属性(properties)客户化。这需要在你的项目的上层目录产生一个叫做build.properties的文件。Tomcat支持的属性(properties)被列出在样本build.xml script的注释中。至少，你必须定义catalina.home的属性，这个属性指出了Tomcat 5 被安装在哪里以及管理员程序里的用户名称和密码。你的编码也许象这样:

# Context path to install this application on
app.path=/hello

# Tomcat 5 installation directory
catalina.home=/usr/local/apache-tomcat-5.5

# Manager webapp username and password
manager.username=myusername
manager.password=mypassword

通常，你不要把这个build.properties 文件存入CVS 贮藏库, 因为它对每个开发人员的工作环境来说都是特定的。

现在, 产生初始版本的网络应用调度描述符(web application deployment descriptor)。你可以在basic web. xml 文件基础上产生web.xml，或者从头编码它。

cd {my home directory}
cd myapp/web/WEB-INF
emacs web.xml
cvs add web.xml
cvs commit
注意，这只是一个web.xml 文件的例子。Servlet 规范里对调度描述符(deployment descriptor)文件有完整的定义。
Edit Source Code and Pages

Edit/build/test(编辑/建造/测试)是开发和维护中最常见的活动。以下一般性原则适用。如源代码组织(Source Organization)所描述，新产生的源文件应该被放在项目源目录之下适当的subdirectory。

当你要把其他开发人员的工作加入到你的开发目录时，就让CVS执行下面的任务：

cd {my home directory}
cd myapp
cvs update -dP

要产生一个新文件，到相关的目录产生这个文件并在CVS注册(register)它。当你(在创建和测试成功之后)对它的内容感到满意，你就把这个新文件commit给贮藏库。例如，下面来产生一个新的JSP页面：

cd {my home directory}
cd myapp/web      &lt;-- Ultimate destination is document root
emacs mypage.jsp
cvs add mypage.jsp
... build and test the application ...
cvs commit

被定义在包裹(packages)里的源代码必须要被组织成一个和包裹名称相对映的目录阶层(在src/ subdirectory之下)。 例如，一个叫做com.mycompany.mypackage.MyClass.java 的Java类，必须被存放在文件src&#47;com&#47;mycompany&#47;mypackage&#47;MyClass.java 里面。不论你什么时候产生一个新的子目录，别忘记去CVS注册

要编辑一个现有源文件, 你一般只是开始编辑并且测试, 当程序全都能正常运作后再把这个被改变的文件commit。虽然CVS可能被配置成要求你"check out" 或"lock" 你将修改的文件，但通常我们不这样做。

Build the Web Application

当你准备好编译你的程序时, 发布以下命令(通常, 你打开一个指向项目源目录的shell窗口，这样一来只需要使用最后一句命令)：

cd {my home directory}
cd myapp      &lt;-- Normally leave a window open here
ant

Ant工具会在你的build.xml文件执行缺省"compile"目标,从而编译任何新的或更新过的Java 代码。如果这是你在"build clean"后第一次编译，它将导致所有的程序被重新编译(recompiled)一次。

要强制执行重新编译全部程序，应用下面的命令：

cd {my home directory}
cd myapp
ant all

在checking in 更改之前这样做是个非常好的习惯，这样可以确保不会产生一些Javac的conditional检查没有捕捉住的任何微妙问题。

Test Your Web Application

要测试你的程序,你要把它安装在Tomcat 之下。最快捷的方法就是使用样本build.xml script里的用户Ant任务。也许可以象这样使用这些命令：

  • 按需要启动Tomcat 5。如果Tomcat 5 已经不在运行，你需要按常规启动它。

  • 编译你的程序。使用这个ant compile命令(或者仅仅ant，因为这是缺省命令)。确准没有编辑错误。

  • 安装程序。使用ant install 命令。这个命令告诉Tomcat立刻在context path 上运行你的程序，app.path build 属性里对context path有定义。Tomcat不要被重新启动就能生效。

  • 测试程序。使用你的浏览器或者其它测试工具, 测试你的程序的功能。

  • 根据必要修改(modify)和重建(rebuild)。当你发现需要进行更改时,去原始的源代码文件(original source files)进行修改,而不是在output build 目录,然后再使用ant compile命令。这就保证了你的变动能在以后被保存下来(通过cvs commit)—— output build 目录根据需要会被删除和被再创造。

  • 重新装载你的程序。Tomcat自动地识别JSP页面里的变化，但它将继续使用老版本的servlet 或 JavaBean classes直到你的程序被重新装载为止。你能通过执行ant reload命令使其发生。

  • 完成所有过程后删除你的程序。当你完成所有过程之后，使用ant remove 命令把你的程序从现场执行(live execution)中删除。

当你完成测试后，别忘记把更改过的文件commit到源代码贮藏库去！

Creating a Release

当你完成了添加新功能到你的程序中去，又测试了所有的东西，下面就可以产生一个distributable 版本的网络程序了，这个版本可被调度到生产服务器(production server)上去。以下通常的步骤是需要的：

  • 从项目源目录里发出ant all 命令，来最后一次rebuild 所有程序。

  • 使用cvs tag 命令为所有在发行版里所用到的源文件产生一个标识符(identifier)。这允许你在以后可以可靠地(从源代码文件)重新产生一个发行版本。
  • 发出ant dist命令来产生一个可发布的网络应用档案(WAR)文件，和包含对应的源代码的JAR文件。

  • 根据你们公司(组织)使用的标准发行规程，用tar或者zip共用程序包装这个dist目录里的内容。


应用开发人员指南 - 源代码组织(Source Organization)

The Tomcat Servlet/JSP Container

应用开发人员指南

源代码组织(Source Organization)
Directory Structure

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

这个手册特别建议你把包含源代码的目录阶层(本章节所描述的)和包含可调度程序的目录阶层(前面章节所描述的)分开。保持这种分离有下面几种好处：

  • 如果没有和“可运行”版的程序相混合，源代码目录里的内容就比较容易来管理，移动和备份(backup)。

  • 在只含有源代码文件的目录里，管理控制源代码就比较容易。

  • 当可调度阶层目录被分开后，就比较容易来选择那些组成可安装分配(installable distribution)程序的文件。

我们将会看到，ant开发工具使得产生和处理这样的目录阶层非常容易。

你可以随意组织用来包含程序源代码的目录和文件阶层。不过，下面的这种组织结构被证明非常实用可行，也是下面将要讨论的例子build.xml配置文件(configuration file)所期望的。所有的这些组成成分存在于你的应用程序的最上层项目源代码目录下面。

  • docs/ —— 关于你的应用程序的文档资料，可以用你们开发组使用的任何格式(format)。

  • src/ —— Java源代码文件，它们是用于产生你的程序特有的servlets, beans, 和其他Java classes。如果你的源代码被组织成包(packages)(我们极力推荐),这个包阶层(hierarchy)就应该被放置这个目录下面。

  • web/ —— 组成你网站的静态文件(HTML页面，JSP页面，JavaScript文件，CSS stylesheet文件，和图象)，这些文件都可以让客户存取(accessible)。这个目录是你的网络程序的文件根(document root)目录，它的任何子目录中的文件可通过浏览器来读取。

  • web/WEB-INF/ —— 你的程序所需的特别的配置文件,包括网络应用程序调度符(web.xml,在Servlet规范里有定义),你为用户标记库(custom tag libraries)所产生的标记库描述符,以及其他你想要包括在网络程序里的资源文件(resource files)。尽管这个目录显得象是文件根目录(document root)的分目录(subdirectory),但是Servlet规范不允许客户能直接使用这个目录里的内容(或它包含的任何文件)。所以，这是一个不错的地方来储存那些程序顺利运行所必须的，但又是非常敏感的配置信息(比如数据库连接用的用户名称及密码)。

在程序开发过程中，会临时产生另外两个目录：

  • build/ —— 执行默认ant指令后，会在这个目录中产生与web应用档案(WAR)完全相同的文件。Tomcat5允许你在象这样未包装的目录里调度程序，你可以把此目录复制到$CATALINA_HOME/webapps 目录上去，或通过“管理者”(Manager)程序把它安装上去。后面的这种处理方式在开发程序中非常有用，下面我们会作些说明。

  • dist/ —— 当你执行ant dist目标后，就会在这个目录中产生与你的网络程序binary distribution 完全相同的文件，包括许可证信息，文档资料和README 文件。

注意 — 不要把这两个目录存档在你的源代码控制系统里，因为这两个目录会在程序开发中根据需要被删除或重新产生。正是因为这个原因，如果你想要保留一个关于程序更改的固定记录，你就不要在这两个目录里编辑源代码文件，因为下一次执行build命令时，所有的程序更改就会被遗失掉。

External Dependencies

如果你的程序需要外部的项目或包(packages)里的JAR文件(或其他资源)，那你应该怎么办呢？一个通常的例子就是你必需在你的程序中引入JDBC驱动程式才能运作。

不同的开发人员采用不同的方式来处理这个问题。有些开发人员会鼓励你对于每一个需要那些JAR文件的程序，把它所依赖的JAR文件复制到源代码控制存档(archives)上。不过，当你在许多程序中使用同样一个JAR文件——特别是当你面临着需要升级(upgrade)到不同版本的JAR文件时，就会产生很严重的管理上的问题。

因此,这个手册提倡不要把你所需要的packages的复制件存放在程序的源代码控制档案里。相反，你应该把这些外部依赖性文件整合到创建你的程序的过程中去。这样一来，你总是可以从系统管理员安装JAR文件的地方选择合适版本的JAR文件，而不用担心每次在你所依赖的JAR文件更改后，要去更新你的程序。

在例子Ant build.xml 文件中，我们将示范怎样去定义那些让你能够配置复制文件地址的build properties，而不需要在这些文件更改时去修改 build.xml 。每个开发人员使用的build属性(properties)可以根据每个不同的程序客户化，或者默认作(defaulted to）“标准”build属性存放在开发人员的主目录(home directory)中。

在许多情况下，系统管理员可能已经把必需的JAR文件安装到Tomcat 5 的 common/lib 或者shared/lib 目录里。如果这已经被做好了，你就不需要再做什么——例子build.xml 会自动创造一个包含这些文件的compile classpath 。

Source Code Control

如先前提到的,我们极力建议你把组成你程序的所有源代码文件放置在一个象Concurrent Version System (CVS)一样的源代码控制系统下来管理。如果你选择这么做，在这个源代码阶层里的每一个目录和文件都会被注册和保存——但是所有产生的文件都不会被注册和保存。如果你注册二进制形式的文件(如图象或JAR库)，一定要指示你的源代码控制系统。

我们(在前面一段)建议你不要把你在开发程序过程中产生的build/ 和dist/ 目录中的内容存放在源代码控制系统里。一个简单的办法让CVS忽略这两个目录就是在你的上层源代码目录中产生一个叫做.cvsignore(注意前面有一个句点)的文件，它应该包括下面这些内容：

build
dist
build.properties

对于在这里提及build.properties的理由，我们会在开发过程这一章节里作解释。

关于源代码控制环境的详细说明超过了本手册的范围。不过，如果你使用命令行的CVS客户端，你要遵守下面的步骤：

  • 要更新储存在源代码储存器(source repository)里的源代码,得到你的源代码目录中去执行cvs update -dP。

  • 当你要在源代码目录阶层产生一个新的子目录(subdirectory)，得到CVS使用象cvs add {子目录名称(subdirname)}的命令来注册。

  • 当你首次产生一个新的源代码文件，找到包括源代码的目录，并用诸如象cvs add {filename}这样的命令来注册这个新文件。

  • 如果你不再需要某个特定的源代码文件，找到包括这个文件的目录，并且删除它。然后在CVS使用象cvs remove {filename}这样的命令来注销这个文件。

  • 在你产生，修改和删除源代码文件时，这些改变还没有反映在服务器端的储存器里。要保持目前的更改，得到项目的源代码目录去执行cvs commit 。你会被要求简述你刚才完成的更改，然后和新版本的源代码文件一起被储存下来。

CVS,象其他源代码控制系统一样，有许多额外的特性(比如能够对特定发行版的文件进行标记，支持开发多个分枝版本—这些分枝在以后可以被合并)。更多信息请参看简介中的链连(link)和参考资料(reference)。

BUILD.XML Configuration File

我们将利用ant工具来管理编译Java源代码文件，以及产生调度目录层次。Ant在一个构建(build)文件控制下操作，通常叫做build.xml，它定义了必需的开发过程的步骤。这个文件储存在你的源代码目录层次的最上层，必须把它读入(check in)到你的源代码控制系统中去。

就象一个Makefile，build.xml文件提供了几个“目标”("target")来支持可选择性的开发活动(比如产生相关的Javadoc文件，擦除调度主目录以便你能从头开始你的项目，或者产生网络应用档案文件以便你可以分配你的程序)。一个构造不错的build.xml文件应该包括描述说明那些设计给开发人员使用的目标(target)的内部文件，以及这些内部使用的目标。要求Ant显示项目的说明资料，你要更换到含有build.xml的目录下，然后打印命令：

ant -projecthelp

为了让你能先做起来，我们提供了basic build.xml 文件，你可以对它用户化并把它安装在你的项目源代码目录中。这个文件包括了描述各种可被执行目标的注释。简单地说，它通常提供了下面的这些目标：

  • 清除(clean)——这个目标删除既存的build 和dist 目录，这样它们可以被重新构造。这样确保你不可能发生因为修改源代码，但没有重新编译(recompiling)所有affected classes，而在运行时出现问题。

  • 编译(compile)——这个目标是用来编译那些自从上次编译后被更改过的源代码。所产生的类文件(class files)被放置在build目录下的子目录WEB-INF/classes 里面，和网络应用程序的结构所要求完全一致的地方。因为这个命令在开发程序过程中经常被执行，所以通常把它设置为“默认（default）”目标，这样一来简单的ant命令就可以执行它。

  • all ——这个目标是一个用来先执行清除目标，然后再执行编译目标的捷径(short cut)。因此，它确保你重新编译所有的程序，这样可以保证你不会在不知不觉中引入一些不相适宜的改变。

  • javadoc ——这个目标产生网络程序中Java类的Javadoc API文档资料。例子build.xml 文件中假设你想把API文档资料包括在你要发表的程序中，所以它把产生的文档资料(docs)放在dist目录下的子目录里。因为你通常不需要在每次编译时都产生Javadocs API文档资料，所以这个目标和dist目标相关联，而与compile目标无关。

  • dist ——这个目标给你的程序产生一个分配目录，包括必要的文档资料，Java类的Javadocs，网络应用档案(WAR)文件，这个WAR文件将被传送给需要安装你的程序的系统管理员。因为这个目标也依赖于deploy目标，网络应用档案还应包括必需的外部文件。

为了用Tomcat5进行互动开发和测试你的程序，我们定义了下面额外的几个目标(targets)：

  • 安装(install)——告诉正在运行的Tomcat5使你开发的程序可被立即用于执行和测试。它不需要重新启动Tomcat5。

  • 重新装载(reload)—— 一但程序安装后，你可以继续更改和用compile目标重新编译。Tomcat5 会自动识别JSP页面里的更改，但不能识别servlet 或 JavaBean 类里的更改——这个命令会告诉Tomcat重新启动最近安装的程序，这样这些改变就会被认可。

  • 删除(remove)——当你完成了开发和测试活动，你可以选择性地告诉Tomcat5把这些程序去掉。

利用开发和测试目标还需要额外的一些一次性设置，这一点我们在下一页会讨论。


应用程序示例

应用程序示例以war文件的形式包装，可以从这里下载它。（注意：确保你的浏览器不会更改文件的extension或者附加一个新的extension）。

运行这个应用程序最简单的方法就是把war文件移动到CATALINA_HOME/webapps目录中去。 Tomcat会自动帮你扩展并部署你的应用程序。你可以从下面的URL来看它（假设你在默认的port 8080上运行tomcat）。
http://localhost:8080/sample

如果你想察看源代码，你可以使用 jar 命令打开war文件。 jar -xvf sample.war


Tomcat Architecture - 目录

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Overview
  • Server Startup
  • Request Process

Tomcat Architecture

目录

 Printer Friendly Version
print-friendly
version
Preface

This section of the Tomcat documentation attempts to explain the architecture and design of the Tomcat server. It includes significant contributions from several tomcat developers:

  • Yoav Shapira (yoavs@apache.org)
  • Jeanfrancois Arcand (jfarcand@apache.org)
  • Filip Hanik (fhanik@apache.org)
Table of Contents

这些信息被分为下面几部分：

  • Overview - An overview of the Tomcat server architecture with key terms and concepts.
  • Server Startup - A detailed description, with sequence diagrams, of how the Tomcat server starts up.
  • Request Process Flow - A detailed description of how Tomcat handles a request.


Tomcat Architecture - Architecture Overview

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Overview
  • Server Startup
  • Request Process

Tomcat Architecture

Architecture Overview

 Printer Friendly Version
print-friendly
version
Overview

This page provides an overview of the Tomcat server architecture.

Terms
Server

In the Tomcat world, a Server represents the whole container. Tomcat provides a default implementation of the Server interface., and this is rarely customized by users.

Service

A Service is an intermediate component which lives inside a Server and ties one or more Connectors to exactly one Engine. The Service element is rarely customized by users, as the default implementation is simple and sufficient: Service interface.

Engine

An Engine represents request processing pipeline for a specific Service. As a Service may have multiple Connectors, the Engine received and processes all requests from these connectors, handing the response back to the appropriate connector for transmission to the client. The Engine interface may be implemented to supply custom Engines, though this is uncommon.

Note that the Engine may be used for Tomcat server clustering via the jvmRoute parameter. Read the Clustering documentation for more information.

Host

A Host is an association of a network name, e.g. www.yourcompany.com, to the Tomcat server. An Engine may contain multiple hosts, and the Host element also supports network aliases such as yourcompany.com and abc.yourcompany.com. Users rarely create custom Hosts because the StandardHost implementation provides significant additional functionality.

Connector

A Connector handles communications with the client. There are multiple connectors available with Tomcat, all of which implement the Connector interface. These include the Coyote connector which is used for most HTTP traffic, especially when running Tomcat as a standalone server, and the JK2 connector which implements the AJP procotol used when connecting Tomcat to an Apache HTTPD server. Creating a customized connector is a significant effort.

Context

A Context represents a web application. A Host may contain multiple contexts, each with a unique path. The Context interface may be implemented to create custom Contexts, but this is rarely the case because the StandardContext provides significant additional functionality.

Comments

Tomcat is designed to be a fast and efficient implementation of the Servlet Specification. Tomcat came about as the reference implementation of this specification, and has remained rigorous in adhering to the specification. At the same time, significant attention has been paid to Tomcat's performance and it is now on par with other servlet containers, including commercial ones.

In recent releases of Tomcat, mostly starting with Tomcat 5, we have begun effots to make more aspects of Tomcat managable via JMX. In addition, the Manager and Admin webapps have been greatly enhanced and improved. Managability is a primary area of concern for us as the product matures and the specification becomes more stable.


Tomcat Architecture - Request Process Flow

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Overview
  • Server Startup
  • Request Process

Tomcat Architecture

Request Process Flow

 Printer Friendly Version
print-friendly
version
Request Process Flow

This page describes the process used by Tomcat to handle an incoming request. This process is largely defined by the Servlet Specification, which outlines the order of events that must take place.

description

TODO

diagram

A UML sequence diagram of the request process is available here.

comments

The Servlet Specification provides many opportunities for listening in (using Listeners) or modiying (using Filters) the request handling process even before the request arrives at the servlet that will handle it.


Tomcat Architecture - 启动

The Tomcat Servlet/JSP Container

Links

  • Docs Home

Contents

  • Contents
  • Overview
  • Server Startup
  • Request Process

Tomcat Architecture

启动

 Printer Friendly Version
print-friendly
version
Server Startup

This page describes how the Tomcat server starts up. There are several different ways to start tomcat, including:

  • From the command line.
  • From a Java program as an embedded server.
  • Automatically as a Windows service.

description

A text description of the startup procedure is available here.

diagram

A UML sequence diagram of the startup procedure is available here.

comments

The startup process can be customized in many ways, both by modifying Tomcat code and by implementing your own LifecycleListeners which are then registered in the server.xml configuration file.


Tomcat Architecture - 目录

The Tomcat Servlet/JSP Container

Tomcat Architecture

目录
Preface

This section of the Tomcat documentation attempts to explain the architecture and design of the Tomcat server. It includes significant contributions from several tomcat developers:

  • Yoav Shapira (yoavs@apache.org)
  • Jeanfrancois Arcand (jfarcand@apache.org)
  • Filip Hanik (fhanik@apache.org)
Table of Contents

这些信息被分为下面几部分：

  • Overview - An overview of the Tomcat server architecture with key terms and concepts.
  • Server Startup - A detailed description, with sequence diagrams, of how the Tomcat server starts up.
  • Request Process Flow - A detailed description of how Tomcat handles a request.


Tomcat Architecture - Architecture Overview

The Tomcat Servlet/JSP Container

Tomcat Architecture

Architecture Overview
Overview

This page provides an overview of the Tomcat server architecture.

Terms
Server

In the Tomcat world, a Server represents the whole container. Tomcat provides a default implementation of the Server interface., and this is rarely customized by users.

Service

A Service is an intermediate component which lives inside a Server and ties one or more Connectors to exactly one Engine. The Service element is rarely customized by users, as the default implementation is simple and sufficient: Service interface.

Engine

An Engine represents request processing pipeline for a specific Service. As a Service may have multiple Connectors, the Engine received and processes all requests from these connectors, handing the response back to the appropriate connector for transmission to the client. The Engine interface may be implemented to supply custom Engines, though this is uncommon.

Note that the Engine may be used for Tomcat server clustering via the jvmRoute parameter. Read the Clustering documentation for more information.

Host

A Host is an association of a network name, e.g. www.yourcompany.com, to the Tomcat server. An Engine may contain multiple hosts, and the Host element also supports network aliases such as yourcompany.com and abc.yourcompany.com. Users rarely create custom Hosts because the StandardHost implementation provides significant additional functionality.

Connector

A Connector handles communications with the client. There are multiple connectors available with Tomcat, all of which implement the Connector interface. These include the Coyote connector which is used for most HTTP traffic, especially when running Tomcat as a standalone server, and the JK2 connector which implements the AJP procotol used when connecting Tomcat to an Apache HTTPD server. Creating a customized connector is a significant effort.

Context

A Context represents a web application. A Host may contain multiple contexts, each with a unique path. The Context interface may be implemented to create custom Contexts, but this is rarely the case because the StandardContext provides significant additional functionality.

Comments

Tomcat is designed to be a fast and efficient implementation of the Servlet Specification. Tomcat came about as the reference implementation of this specification, and has remained rigorous in adhering to the specification. At the same time, significant attention has been paid to Tomcat's performance and it is now on par with other servlet containers, including commercial ones.

In recent releases of Tomcat, mostly starting with Tomcat 5, we have begun effots to make more aspects of Tomcat managable via JMX. In addition, the Manager and Admin webapps have been greatly enhanced and improved. Managability is a primary area of concern for us as the product matures and the specification becomes more stable.


Tomcat Architecture - Request Process Flow

The Tomcat Servlet/JSP Container

Tomcat Architecture

Request Process Flow
Request Process Flow

This page describes the process used by Tomcat to handle an incoming request. This process is largely defined by the Servlet Specification, which outlines the order of events that must take place.

description

TODO

diagram

A UML sequence diagram of the request process is available here.

comments

The Servlet Specification provides many opportunities for listening in (using Listeners) or modiying (using Filters) the request handling process even before the request arrives at the servlet that will handle it.


Tomcat Architecture - 启动

The Tomcat Servlet/JSP Container

Tomcat Architecture

启动
Server Startup

This page describes how the Tomcat server starts up. There are several different ways to start tomcat, including:

  • From the command line.
  • From a Java program as an embedded server.
  • Automatically as a Windows service.

description

A text description of the startup procedure is available here.

diagram

A UML sequence diagram of the startup procedure is available here.

comments

The startup process can be customized in many ways, both by modifying Tomcat code and by implementing your own LifecycleListeners which are then registered in the server.xml configuration file.


Tomcat 5 Startup Sequence

Sequence 1. Start from Command Line
Class: org.apache.catalina.startup.Bootstrap
What it does:
    a) Set up classloaders
        commonLoader (common)-> System Loader
        sharedLoader (shared)-> commonLoader -> System Loader
        catalinaLoader(server) -> commonLoader -> System Loader
    b) Load startup class (reflection)
        org.apache.catalina.startup.Catalina
        setParentClassloader -> sharedLoader
        Thread.contextClassloader -> catalinaLoader
    c) Bootstrap.daemon.init() complete

Sequence 2. Process command line argument (start, startd, stop, stopd)
Class: org.apache.catalina.startup.Bootstrap (assume command->start)
What it does:
    a) Catalina.setAwait(true);
    b) Catalina.load()
        b1) initDirs() -> set properties like
                          catalina.home
                          catalina.base == catalina.home (most cases)
        b2) initNaming
            setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                    org.apache.naming.java.javaURLContextFactory ->default)
        b3) createStartDigester()
            Configures a digester for the main server.xml elements like
            org.apache.catalina.core.StandardServer (can change of course :)
            org.apache.catalina.deploy.NamingResources
                Stores naming resources in the J2EE JNDI tree
            org.apache.catalina.LifecycleListener
                implements events for start/stop of major components
            org.apache.catalina.core.StandardService
                The single entry for a set of connectors,
                so that a container can listen to multiple connectors
                ie, single entry
            org.apache.coyote.tomcat5.CoyoteConnector
                Connectors to listen for incoming requests only
            It also adds the following rulesets to the digester
                NamingRuleSet
                EngineRuleSet
                HostRuleSet
                ContextRuleSet
        b4) Load the server.xml and parse it using the digester
            Parsing the server.xml using the digester is an automatic
            XML-object mapping tool, that will create the objects defined in server.xml
            Startup of the actual container has not started yet.
        b5) Assigns System.out and System.err to the SystemLogHandler class
        b6) Calls intialize on all components, this makes each object register itself with the
            JMX agent.
            During the process call the Connectors also initialize the adapters.
            The adapters are the components that do the request pre-processing.
            Typical adapters are HTTP1.1 (default if no protocol is specified,
            org.apache.coyote.http11.Http11Protocol)
            AJP1.3 for mod_jk etc.

    c) Catalina.start()
        c1) Starts the NamingContext and binds all JNDI references into it
        c2) Starts the services under <Server> which are:
            StandardService -> starts Engine (ContainerBase ->Logger,Loader,Realm,Cluster etc)
        c3) StandardHost (started by the service)
                Configures a ErrorReportValvem to do proper HTML output for different HTTP
                errors codes
                Starts the Valves in the pipeline (at least the ErrorReportValve)
                Configures the StandardHostValve,
                    this valves ties the Webapp Class loader to the thread context
                    it also finds the session for the request
                    and invokes the context pipeline
                Starts the HostConfig component
                    This component deploys all the webapps
                        (webapps & conf/Catalina/localhost/*.xml)
                    Webapps are installed using the deployer (StandardHostDeployer)
                    The deployer will create a Digester for your context, this digester
                    will then invoke ContextConfig.start()
                        The ContextConfig.start() will process the default web.xml (conf/web.xml)
                        and then process the applications web.xml (WEB-INF/web.xml)

        c4) During the lifetime of the container (StandardEngine) there is a background thread that
            keeps checking if the context has changed. If a context changes (timestamp of war file,
            context xml file, web.xml) then a reload is issued (stop/remove/deploy/start)

    d) Tomcat receives a request on an HTTP port
        d1) The request is received by a separate thread which is waiting in the PoolTcpEndPoint
             class. It is waiting for a request in a regular ServerSocket.accept() method.
             When a request is received, this thread wakes up.
        d2) The PoolTcpEndPoint assigns the a TcpConnection to handle the request.
            It also supplies a JMX object name to the catalina container (not used I believe)
        d3) The processor to handle the request in this case is Coyote Http11Processor,
            and the process method is invoked.
            This same processor is also continuing to check the input stream of the socket
            until the keep alive point is reached or the connection is disconnected.
        d4) The HTTP request is parsed using an internal buffer class (Coyote Http11 Internal Buffer)
            The buffer class parses the request line, the headers, etc and store the result in a
            Coyote request (not an HTTP request) This request contains all the HTTP info, such
            as servername, port, scheme, etc.
        d5) The processor contains a reference to an Adapter, in this case it is the
            Coyote Tomcat 5 Adapter. Once the request has been parsed, the Http11 processor
            invokes service() on the adapter. In the service method, the Request contains a
            CoyoteRequest and CoyoteRespons (null for the first time)
            The CoyoteRequest(Response) implements HttpRequest(Response) and HttpServletRequest(Response)
            The adapter parses and associates everything with the request, cookies, the context through a
            Mapper, etc
        d6) When the parsing is finished, the CoyoteAdapter invokes its container (StandardEngine)
            and invokes the invoke(request,response) method.
            This initiates the HTTP request into the Catalina container starting at the engine level
        d7) The StandardEngine.invoke() simply invokes the container pipeline.invoke()
        d8) By default the engine only has one valve the StandardEngineValve, this valve simply
            invokes the invoke() method on the Host pipeline (StandardHost.getPipeLine())
        d9) the StandardHost has two valves by default, the StandardHostValve and the ErrorReportValve
        d10) The standard host valve associates the correct class loader with the current thread
             It also retrives the Manager and the session associated with the request (if there is one)
             If there is a session access() is called to keep the session alive
        d11) After that the StandardHostValve invokes the pipeline on the context associated
             with the request.
        d12) The first valve that gets invoked by the Context pipeline is the FormAuthenticator
             valve. Then the StandardContextValve gets invoke.
             The StandardContextValve invokes any context listeners associated with the context.
             Next it invokes the pipeline on the Wrapper component (StandardWrapperValve)
        d13) During the invokation of the StandardWrapperValve, the JSP wrapper (Jasper) gets invoked
             This results in the actual compilation of the JSP.
             And then invokes the actual servlet.
    e) Invokation of the servlet class


Administration

 Tomcat's internal javadoc is no longer installed by default. Download and install the "fulldocs" package to get it. You can also access the javadoc online in the Tomcat documentation bundle.


Catalina Functional Specifications - Administrative Apps - Overall Requirements

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

Administrative Apps - Overall Requirements

 Printer Friendly Version
print-friendly
version
Overview
Introduction

The purpose of this specification is to define high level requirements for administrative applications that can be used to manage the operation of a running Tomcat 5 container. A variety of Access Methods to the supported administrative functionality shall be supported, to meet varying requirements:

  • As A Scriptable Web Application - The existing Manager web application provides a simple HTTP-based interface for managing Tomcat through commands that are expressed entirely through a request URI. This is useful in environments where you wish to script administrative commands with tools that can generate HTTP transactions.
  • As An HTML-Based Web Application - Use an HTML presentation to provide a GUI-like user interface for humans to interact with the administrative capabilities.
  • As SOAP-Based Web Services - The operational commands to administer Tomcat are made available as web services that utilize SOAP message formats.
  • As Java Management Extensions (JMX) Commands - The operational commands to administer Tomcat are made available through JMX APIs, for integration into management consoles that utilize them.
  • Other Remote Access APIs - Other remote access APIs, such as JINI, RMI, and CORBA can also be utilized to access administrative capabilities.

Underlying all of the access methods described above, it is assumed that the actual operations are performed either directly on the corresponding Catalina components (such as calling the Deployer.deploy() method to deploy a new web application), or through a "business logic" layer that can be shared across all of the access methods. This approach minimizes the cost of adding new administrative capabilities later -- it is only necessary to add the corresponding business logic function, and then write adapters to it for all desired access methods.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

External Specifications

The implementation of this functionality depends on the following external specifications:

  • Java IDL (for CORBA, included in the JDK)
  • Java Management Extensions
  • Remote Method Invocation (Included in the JDK)
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • To the maximum extent feasible, all administrative functions, and the access methods that support them, shall run portably on all platforms where Tomcat 5 itself runs.
  • In a default Tomcat distribution, all administrative capabilities shall be disabled. It shall be necessary for a system administrator to specifically enable the desired access methods (such as by adding a username/password with a specific role to the Tomcat user's database.
  • Administrative functions shall be realized as direct calls to corresponding Catalina APIs, or through a business logic layer that is independent of the access method used to initiate it.
  • The common business logic components shall be implemented in package org.apache.catalina.admin.
  • The common business logic components shall be built as part of the standard Catalina build process, and made visible in the Catalina class loader.
  • The Java components required for each access method shall be implemented in subpackages of org.apache.catalina.admin.
  • The build scripts should treat each access method as optional, so that it will be built only if the corresponding required APIs are present at build time.
  • It shall be possible to save the configured state of the running Tomcat container such that this state can be reproduced when the container is shut down and restarted.
  • Adminstrative commands to start up and shut down the overall Tomcat container are out of scope for the purposes of these applications. It is assumed that other (usually platform-specific) mechanisms will be used for container startup and shutdown.
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for administrative applications to operate correctly:

  • For access methods that require creation of server sockets, the appropriate ports must be configured and available.
Container Dependencies

Correct operation of administrative applications depends on the following specific features of the surrounding container:

  • To the maximum extent feasible, Catalina components that offer direct administrative APIs and property setters shall support "live" changes to their operation, without requiring a container restart.
External Technologies

The availability of the following technologies can be assumed for the implementation and operation of the various access methods and the corresponding administrative business logic:

  • Java 2 Standard Edition (Version 1.2 or later)
  • Servlet 2.4 (supported natively by Tomcat 5)
  • JavaServer Pages 2.0 (supported natively by Tomcat 5)
  • JavaServer Pages Standard Tag Library 1.0 (Jakarta Taglibs-Standard 1.0.3)
  • Struts Framework (Version 1.0) - MVC Framework for Web Applications
  • TO BE DETERMINED - Application for hosting SOAP based web services
Functionality
Properties of Administered Objects

Functional requirements for administrative applications are specified in terms of Administered Objects, whose definitions and detailed properties are listed here. In general, Administered Objects correspond to components in the Catalina architecture, but these objects are defined separately here for the following reasons:

  • It is possible that the administrative applications do not expose every possible configurable facet of the underlying components.
  • In some cases, an Administered Object (from the perspective of an administrative operation) is realized by more than one Catalina component, at a finer-grained level of detail.
  • It is necessary to represent the configuration information for a component separately from the component itself (for instance, in order to store that configuration information for later use).
  • It is necessary to represent configuration information (such as a Default Context) when there is no corresponding component instance.
  • Administered Objects, when realized as Java classes, will include methods for administrative operations that have no correspondence to operations performed by the corresponding actual components.

It is assumed that the reader is familiar with the overall component architecture of Catalina. For further information, see the corresponding Developer Documentation. To distinguish names that are used as both Administered Objects and Components, different font presentations are utilized. Default values for many properties are listed in [square brackets].

Supported Administrative Operations

The administrative operations that are available are described in terms of the corresponding Administered Objects (as defined above), in a manner that is independent of the access method by which these operations are requested. In general, such operations are relevant only in the context of a particular Administered Object (and will most likely be realized as method calls on the corresponding Administered Object classes), so they are organized based on the currently "focused" administered object. The available Supported Operations are documented here.

Access Method Specific Requirements
Scriptable Web Application

An appropriate subset of the administrative operations described above shall be implemented as commands that can be performed by the "Manager" web application. FIXME - Enumerate them.

In addition, this web application shall conform to the following requirements:

  • All request URIs shall be protected by a security constraint that requires security role manager for processing.
  • The default user database shall not contain any user that has been assigned the role manager.
HTML-Based Web Application

The entire suite of administrative operations described above shall be made available through a web application designed for human interaction. In addition, this web application shall conform to the following requirements:

  • Must be implemented using servlet, JSP, and MVC framework technologies described under "External Technologies", above.
  • Prompts and error messages must be internationalizable to multiple languages.
  • Rendered HTML must be compatible with Netscape Navigator (verson 4.7 or later) and Internet Explorer (version 5.0 or later).
Testable Assertions

FIXME - Complete this section.


Catalina Functional Specifications - Administrative Apps - Administered Objects

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

Administrative Apps - Administered Objects

 Printer Friendly Version
print-friendly
version
Administered Objects Overview

This document defines the Administered Objects that represent the internal architectural components of the Catalina servlet container. Associated with each is a set of Supported Operations that can be performed when the administrative application is "focused" on a particular configurable object.

The following Administered Objects are defined:

  • Access Logger
  • connector
  • <Context>
  • 默认Context
  • Default Deployment Descriptor
  • <Engine>
  • Environment Entry
  • <Host>
  • JDBC Resource
  • 载入器
  • 管理者
  • <Realm>
  • Request Filter
  • <Server>
  • <Service>
Access Logger

An Access Logger is an optional Valve that can create request access logs in the same formats as those provided by web servers. Such access logs are useful input to hit count and user access tracking analysis programs. An Access Logger can be attached to an Engine, a Host, a Context, or a Default Context.

The standard component implementing an Access Logger is org.apache.catalina.valves.AccessLogValve. It supports the following configurable properties:

  • debug - Debugging detail level. [0]
  • directory - Absolute or relative (to $CATALINA_HOME) path of the directory into which access log files are created. [logs].
  • pattern - Pattern string defining the fields to be included in the access log output, or "common" for the standard access log pattern. See org.apache.catalina.valves.AccessLogValve for more information. [common]
  • prefix - Prefix added to the beginning of each log file name created by this access logger.
  • resolveHosts - Should IP addresses be resolved to host names in the log? [false]
  • suffix - Suffix added to the end of each log file name created by this access logger.
Connector

A Connector is the representation of a communications endpoint by which requests are received from (and responses returned to) a Tomcat client. The administrative applications shall support those connectors that are commonly utilized in Tomcat installations, as described in detail below.

For standalone use, the standard connector supporting the HTTP/1.1 protocol is org.apache.catalina.connectors.http.HttpConnector. It supports the following configurable properties:

  • acceptCount - The maximum queue length of incoming connections that have not yet been accepted. [10]
  • address - For servers with more than one IP address, the address upon which this connector should listen. [All Addresses]
  • bufferSize - Default input buffer size (in bytes) for requests created by this Connector. [2048]
  • debug - Debugging detail level. [0]
  • enableLookups - Should we perform DNS lookups on remote IP addresses when request.getRemoteHost() is called? [true]
  • maxProcessors - The maximum number of processor threads supported by this connector. [20]
  • minProcessors - The minimum number of processor threads to be created at container startup. [5]
  • port - TCP/IP port number on which this Connector should listen for incoming requests. [8080]
  • proxyName - Host name to be returned when an application calls request.getServerName(). [Value of Host: header]
  • proxyPort - Port number to be returned when an application calls request.getServerPort(). [Same as port]
Context

A Context is the representation of an individual web application, which is associated with a corresponding Host. Note that the administrable properties of a Context do not include any settings from inside the web application deployment descriptor for that application.

The standard component implementing a Context is org.apache.catalina.core.StandardContext. It supports the following configurable properties:

  • cookies - Should be use cookies for session identifier communication? [true]
  • crossContext - Should calls to ServletContext.getServletContext() return the actual context responsible for the specified path? [false]
  • debug - Debugging detail level. [0]
  • docBase - The absolute or relative (to the appBase of our owning Host) pathname of a directory containing an unpacked web application, or of a web application archive (WAR) file.
  • override - Should settings in this Context override corresponding settings in the Default Context? [false]
  • path - Context path for this web application, or an empty string for the root application of a Host. [Inferred from directory or WAR file name]
  • reloadable - Should Tomcat monitor classes in the /WEB-INF/classes directory for changes, and reload the application if they occur? [false]
  • useNaming - Should Tomcat provide a JNDI naming context, containing preconfigured entries and resources, corresponding to the requirements of the Java2 Enterprise Edition specification? [true]
  • workDir - Absolute pathname of a scratch directory that is provided to this web application. [Automatically assigned relative to $CATALINA_HOME/work]

Each Context is owned by a parent Host, and is associated with:

  • An optional Access Logger that logs all requests processed by this web application.
  • Zero or more Environment Entries representing environment entries for the JNDI naming context associated with a web application.
  • Zero or more JDBC Resources representing database connection pools associated with a web application.
  • A Loader representing the web application class loader used by this web application.
  • A Manager representing the session manager used by this web application.
  • An optional Realm used to provide authentication and access control information for this web application.
  • Zero or more Request Filters used to limit access to this web application based on remote host name or IP address.
Default Context

A Default Context represents a subset of the configurable properties of a Context, and is used to set defaults for those properties when web applications are automatically deployed. A Default Context object can be associated with an Engine or a Host. The following configurable properties are supported:

  • cookies - Should be use cookies for session identifier communication? [true]
  • crossContext - Should calls to ServletContext.getServletContext() return the actual context responsible for the specified path? [false]
  • reloadable - Should Tomcat monitor classes in the /WEB-INF/classes directory for changes, and reload the application if they occur? [false]
  • useNaming - Should Tomcat provide a JNDI naming context, containing preconfigured entries and resources, corresponding to the requirements of the Java2 Enterprise Edition specification? [true]

Each Default Context is owned by a parent Engine or Host, and is associated with:

  • Zero or more Environment Entries representing environment entries for the JNDI naming context associated with a web application.
  • Zero or more JDBC Resources representing database connection pools associated with a web application.
  • An optional Loader representing default configuration properties for the Loader component of deployed web applications.
  • An optional Manager representing default configuration properties for the Manager component fo deployed web applications.
Default Deployment Descriptor

Default web application characteristics are configured in a special deployment descriptor named $CATALINA_HOME/conf/web.xml. This section describes the configurable components that may be stored there.

FIXME - Complete the description of default servlets, default mappings, default MIME types, and so on.

Engine

An Engine is the representation of the entire Catalina servlet container, and processes all requests for all of the associated virtual hosts and web applications.

The standard component implementing an Engine is org.apache.catalina.core.StandardEngine. It supports the following configurable properties:

  • debug - Debugging detail level. [0]
  • defaultHost - Name of the Host to which requests will be directed if the requested host is unknown. [localhost]
  • name - Logical name of this engine. [Tomcat Stand-Alone]

Each Engine is owned by a parent Service, and is associated with:

  • An optional Access Logger that logs all requests processed by the entire container.
  • A Default Context, representing default properties of a Context for automatically deployed applications for all associated Hosts (unless overridden by a subordinate component).
  • One or more Hosts representing individual virtual hosts supported by this container.
  • A Realm used to provide authentication and access control information for all virtual hosts and web applications (unless overridden by a subordinate component).
  • Zero or more Request Filters used to limit access to the entire container based on remote host name or IP address.
Environment Entry

An Environment Entry is the representation of a <env-entry> element from a web application deployment descriptor. It will cause the creation of a corresponding entry in the JNDI naming context provided to the corresponding Context. The following configurable properties are supported:

  • description - Description of this environment entry.
  • name - Environment entry name (relative to the java:comp/env context)
  • type - Environment entry type (must be one of the fully qualified Java classes listed in the servlet spec).
  • value - Environment entry value (must be convertible from String to the specified type.
Host

A Host is the representation of an individual virtual host, which has a unique set of associated web applications.

The standard component implementing a Host is org.apache.catalina.core.StandardHost. It supports the following configurable properties:

  • aliases - Zero or more DNS names that are also associated with this host (for example, a particular host might be named www.mycompany.com with an alias company.com).
  • appBase - Absolute or relative (to $CATALINA_HOME) path to a directory from which web applications will be automatically deployed.
  • debug - Debugging detail level. [0]
  • name - DNS Name of the virtual host represented by this object.
  • unpackWARs - Should web application archive files deployed by this virtual host be unpacked first? [true]

Each Host is owned by a parent Engine, and is associated with:

  • An optional Access Logger that logs all requests processed by this virtual host.
  • One or more Contexts representing the web applications operating on this Host.
  • A Default Context representing default Context properties for web applications that are automatically deployed by this Host.
  • A optional Realm used to provide authentication and access control information for all web applications associated with this virtual host (unless overridden by a subordinate component).

FIXME - Should we support configuration of the User Web Applications functionality?

JDBC Resource

A JDBC Resources represents a database connection pool (i.e. an implementation of javax.sql.DataSource that will be configured and made available in the JNDI naming context associated with a web application.

FIXME - properties of this administered object

Loader

A Loader represents a web application class loader that will be utilized to provide class loading services for a particular Context.

The standard component implementing a Loader is org.apache.catalina.loader.StandardLoader. It supports the following configurable properties:

  • checkInterval - Number of seconds between checks for modified classes, if automatic reloading is enabled. [15]
  • debug - Debugging detail level. [0]
  • reloadable - Should this class loader check for modified classes and initiate automatic reloads? [Set automatically from the reloadable property of the corresponding Context]

Each Loader is owned by a parent Context.

Manager

A Manager represents a session manager that will be associated with a particular web application. FIXME - Add support for advanced session managers and their associated Stores.

The standard component implementing a Manager is org.apache.catalina.session.StandardManager. It supports the following configurable properties:

  • checkInterval - Number of seconds between checks for expired sessions. [60]
  • debug - Debugging detail level. [0]
  • entropy - String initialization parameter used to increase the entropy (initial randomness) of the random number generator used to create session identifiers. [Inferred from engine, host, and context]
  • maxActiveSessions - The maximum number of active sessions that are allowed, or -1 for no limit. [-1]

Each Manager is owned by a parent Context.

Realm

A Realm represents a "database" of information about authorized users, their passwords, and the security roles assigned to them. This will be used by the container in the implementation of container-managed security in accordance with the Servlet Specification. Several alternative implementations are supported.

org.apache.catalina.realm.MemoryRealm initializes its user information from a simple XML file at startup time. If changes are made to the information in this file, the corresponding web applications using it must be restarted for the changes to take effect. It supports the following configurable properties:

  • debug - Debugging detail level. [0]
  • pathname - Absolute or relative (to $CATALINA_HOME) path to the XML file containing our user information. [conf/tomcat-users.xml]

org.apache.catalina.realm.JDBCRealm uses a relational database (accessed via JDBC APIs) to contain the user information. Changes in the contents of this database take effect immediately; however, the roles assigned to a particular user are calculated only when the user initially logs on (and not per request). The following configurable properties are supported:

  • connectionName - Database username to use when establishing a JDBC connection.
  • connectionPassword - Database password to use when establishing a JDBC connection.
  • connectionURL - Connection URL to use when establishing a JDBC connection.
  • debug - Debugging detail level. [0]
  • digest - Name of the MessageDigest algorithm used to encode passwords in the database, or a zero-length string for no encoding. [Zero-length String]
  • driverName - Fully qualified Java class name of the JDBC driver to be utilized.
  • roleNameCol - Name of the column, in the User Roles table, which contains the role name.
  • userCredCol - Name of the column, in the Users table, which contains the password (encrypted or unencrypted).
  • userNameCol - Name of the column, in both the Users and User Roles tables, that contains the username.
  • userRoleTable - Name of the User Roles table, which contains one row per security role assigned to a particular user. This table must contain the columns specified by the userNameCol and roleNameCol properties.
  • userTable - Name of the Users table, which contains one row per authorized user. This table must contain the columns specified by the userNameCol and userCredCol properties.

FIXME - Should we provide mechanisms to edit the contents of a "tomcat-users.xml" file through the admin applications?

Each Realm is owned by a parent Engine, Host, or Context.

Request Filter

FIXME - complete this entry

Server

FIXME - complete this entry

Service

FIXME - complete this entry


Catalina Functional Specifications - Administrative Apps - Supported Operations

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

Administrative Apps - Supported Operations

 Printer Friendly Version
print-friendly
version
Supported Operations Overview

This document defines the Supported Operations that may be performed against the Administered Objects that are supported by Tomcat 5 administrative applications. Not all operations are required to be available through every administrative application that is implemented. However, if a given operation is available, it should operate consistently with the descriptions found here.

Supported Operations are described for the following Administered Objects:

  • Access Logger
  • connector
  • <Context>
  • 默认Context
  • <Engine>
  • Environment Entry
  • <Host>
  • JDBC Resource
  • 载入器
  • 管理者
  • <Realm>
  • Request Filter
  • <Server>
  • <Service>
Access Logger

From the perspective of a particular Access Logger, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine, Host, or Context.
  • Edit the configurable properties of this object.
Connector

From the perspective of a particular Connector, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Service.
  • Edit the configurable properties of this object.
Context

From the perspective of a particular Context, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Host.
  • Edit the configurable properties of this object.
  • Create and configure a new Access Logger associated with this object.
  • Edit the configurable properties of the associated Access Logger.
  • Remove the associated Access Logger.
  • Create and configure a new Environment Entry associated with this object.
  • Select and edit the configurable properties of an associated Environment Entry.
  • Remove an associated Environment Entry.
  • Create and configure a new JDBC Resource associated with this object.
  • Select and edit the configurable properties of an associated JDBC Resource.
  • Remove an associated JDBC Resource.
  • Create and configure a new Loader associated with this object.
  • Edit the configurable properties of the associated Loader.
  • Remove the associated Loader.
  • Create and configure a new Manager associated with this object.
  • Edit the configurable properties of the associated Manager.
  • Remove the associated Manager.
  • Create and configure a new Realm associated with this object.
  • Edit the configurable properties of the associated Realm.
  • Remove the associated Realm.
  • Create and configure a new Request Filter associated with this object.
  • Select and edit the configurable properties of an associated Request Filter
  • Remove an associated Request Filter.
Default Context

From the perspective of a particular Default Context, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine or Host.
  • Edit the configurable properties of this object.
  • Create and configure a new Environment Entry associated with this object.
  • Select and edit the configurable properties of an associated Environment Entry.
  • Remove an associated Environment Entry.
  • Create and configure a new JDBC Resource associated with this object.
  • Select and edit the configurable properties of an associated JDBC Resource.
  • Remove an associated JDBC Resource.
Engine

From the perspective of a particular Engine, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Service.
  • Edit the configurable properties of this object.
  • Create and configure a new Access Logger associated with this object.
  • Edit the configurable properties of the associated Access Logger.
  • Remove the associated Access Logger.
  • Create and configure a new Default Context associated with this object.
  • Edit the configurable properties of the associated Default Context.
  • Remove the associated Default Context.
  • Create and configure a new Host associated with this object.
  • Select and edit the configurable properties of an associated Host.
  • Remove an associated Host.
  • Create and configure a new Realm associated with this object.
  • Edit the configurable properties of the associated Realm.
  • Remove the associated Realm.
  • Create and configure a new Request Filter associated with this object.
  • Select and edit the configurable properties of an associated Request Filter
  • Remove an associated Request Filter.
Environment Entry

From the perspective of a particular Environment Entry, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context or Default Context.
  • Edit the configurable properties of this object.
Host

From the perspective of a particular Host, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine.
  • Edit the configurable properties of this object.
  • Create and configure a new Access Logger associated with this object.
  • Edit the configurable properties of the associated Access Logger.
  • Remove the associated Access Logger.
  • Create and configure a new Context associated with this object.
  • Select and edit the configurable properties of an associated Context.
  • Remove an associated Context.
  • Create and configure a new Default Context associated with this object.
  • Edit the configurable properties of the associated Default Context.
  • Remove the associated Default Context.
  • Create and configure a new Realm associated with this object.
  • Edit the configurable properties of the associated Realm.
  • Remove the associated Realm.
  • Create and configure a new Request Filter associated with this object.
  • Select and edit the configurable properties of an associated Request Filter
  • Remove an associated Request Filter.
JDBC Resource

From the perspective of a particular JDBC Resource, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context or Default Context.
  • Edit the configurable properties of this object.
Loader

From the perspective of a particular Loader, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context.
  • Edit the configurable properties of this object.
Manager

From the perspective of a particular Manager, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context.
  • Edit the configurable properties of this object.
Realm

From the perspective of a particular Realm, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine, Host, or Context.
  • Edit the configurable properties of this object.
Request Filter

From the perspective of a particular Request Filter, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine, Host, or Context.
  • Edit the configurable properties of this object.
Server

From the perspective of the overall Server, it shall be possible to perform the following administrative operations:

  • Edit the configurable properties of this object.
  • Create and configure a new Service associated with this object.
  • Select and edit the configurable properties of an associated Service.
Service

From the perspective of a particular Service, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Server.
  • Edit the configurable properties of this object.
  • Create and configure a new Connector associated with this object.
  • Select and edit the configurable properties of an associated Connector.
  • Remove an associated Connector.
  • Create and configure a new Engine associated with this object.
  • Edit the configurable properties of the associated Engine.
  • Remove the associated Engine.


Catalina Functional Specifications - 缺省Servlet

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

缺省Servlet

 Printer Friendly Version
print-friendly
version
Overview
Introduction

The purpose of the Default Servlet is to serve static resources of a web application in response to client requests. As the name implies, it is generally configured as the "default" servlet for a web application, by being mapped to a URL pattern "/".

External Specifications

The following external specifications have provisions which partially define the correct behavior of the default servlet:

  • Servlet Specification (Version 2.3 PFD2)
  • Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types
  • Hypertext Transfer Protocol -- HTTP/1.1
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Must be implemented as a servlet.
  • Must support configurable parameters for debugging detail level, input buffer size, output buffer size, whether or not to produce directory listings when no welcome file is present, and whether or not modifications are supported via DELETE and PUT.
  • Log debugging and operational messages (suitably internationalized) via the getServletContext().log() method.
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for the default servlet to operate correctly:

  • The default servlet must be registered in the application deployment descriptor (or the default deployment descriptor in file $CATALINA_HOME/conf/web.xml) using a "default servlet" servlet mapping, signified by URL pattern "/".
Container Dependencies

Correct operation of the default servlet depends on the following specific features of the surrounding container:

  • The container shall provide a servlet context attribute that lists the welcome file names that have been defined for this web application.
  • The container shall provide a servlet context attribute that contains a javax.naming.directory.DirContext implementation representing the static resources of this web application.
Functionality
Initialization Functionality

The following processing must be performed when the init() method of the invoker servlet is called:

  • Process and sanity check configuration parameters.
Per-Request Functionality

For all HTTP request methods, the resource path is determined from the path information provided to this request, either as request attribute javax.servlet.include.path_info (for a request dispatcher access to a static resource) or by calling request.getPathInfo() directly.

On each HTTP DELETE request processed by this servlet, the following processing shall be performed:

  • If modifications to the static resources are not allowed (set by a configuration parameter), return HTTP status 403 (forbidden).
  • If an attempt is made to delete a resource from /META-INF or /WEB-INF, return HTTP status 403 (forbidden).
  • If the requested resource does not exist, return HTTP status 404 (not found)
  • Unbind the resource from the directory context containing the static resources for this web application. If successful, return HTTP status 204 (no content). Otherwise, return HTTP status 405 (method not allowed).

On each HTTP GET request processed by this servlet, the following processing shall be performed:

  • If the request is for a resource under /META-INF or /WEB-INF, return HTTP status 404 (not found).
  • If the requested resource does not exist, return HTTP status 404 (not found).
  • If the requested resource is not a directory, but the resource path ends in "/" or "\", return HTTP status 404 (not found).
  • If the requested resource is a directory:
    • If the request path does not end with "/", redirect to a corresponding path with "/" appended so that relative references in welcome files are resolved correctly.
    • If one of the specified welcome files exists, redirect to the path for that welcome file so that it will be served explicitly.
  • If the request being processed contains an If-Range header, perform the processing described in the HTTP/1.1 specification to determine whether the client's information is up to date.
  • Determine the content type of the response, by looking up the corresponding MIME type in our servlet context.
  • If the requested resource is a directory:
    • If directory listings are suppressed, return HTTP status 404 (not found).
    • Set the content type to text/html.
  • Determine the range(s) to be returned, based on the existence of any If-Range and Range headers.
  • If the requested resource is a directory, include an ETag header in the response, with the value calculated based on the content of the directory.
  • Include a Last-Modified header in the response documenting the date/time that the resource was last modified.
  • Unless we are processing a HEAD request, include the appropriate content (or content ranges) in the response.

On each HTTP HEAD request processed by this servlet, the following processing shall be performed:

  • Processed identically to an HTTP GET request, except that the data content is not transmitted after the headers.

On each HTTP POST request processed by this servlet, the following processing shall be performed:

  • Processed identically to an HTTP GET request.

On each HTTP PUT request processed by this servlet, the following processing shall be perfomred:

  • If modifications to the static resources are not allowed (set by a configuration parameter), return HTTP status 403 (forbidden).
  • If an attempt is made to delete a resource from /META-INF or /WEB-INF, return HTTP status 403 (forbidden).
  • Create a new resource from the body of this request.
  • Bind or rebind the specified path to the new resource (depending on whether it currently exists or not). Return HTTP status as follows:
    • If binding was unsuccessful, return HTTP status 409 (conflict).
    • If binding was successful and the resource did not previously exist, return HTTP status 201 (created).
    • If binding was successful and the resource previously existed, return HTTP status 204 (no content).
Finalization Functionality

No specific processing is required when the destroy() method is called:

Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of the invoker servlet:

  • Requests for resources that do not exist in the web application must return HTTP status 404 (not found).
  • The default servlet must operate identically for web applications that are run out of a WAR file directly, or from an unpacked directory structure.
  • If the web application is running out of an unpacked directory structure, the default servlet must recognize cases where the resource has been updated through external means.


Catalina Functional Specifications - Invoker Servlet

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

Invoker Servlet

 Printer Friendly Version
print-friendly
version
Overview
Introduction

The purpose of the Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a <servlet> element in the /WEB-INF/web.xml deployment descriptor, and execute requests utilizing the new servlet definitions. From the perspective of the newly registered servlets, all servlet lifecycle requirements of the Servlet Specification (such as calling init() and destroy() at the correct times) will be respected.

External Specifications

I do not know of any formal specification of the behavior of an invoker servlet that is publicly available. Anyone know of one?

Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Implemented as a servlet.
  • Exist in the org.apache.catalina.servlets package so that it can be loaded by the Catalina class loader.
  • Implement the org.apache.catalina.ContainerServlet interface, so that it gains knowledge of the Wrapper that is responsible for itself and, therefore, access to other internal Catalina components.
  • Support a configurable debugging detail level.
  • Log debugging and operational messages (suitably internationalized) via the getServletContext().log() method.
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for the Invoker servlet to operate correctly:

  • The invoker servlet must be registered in the application deployment descriptor (or the default deployment descriptor in file $CATALINA_HOME/conf/web.xml) using a "path mapped" servlet mapping. The historical default mapping is to URL pattern "/servlet/*", although the invoker servlet must operate correctly with an arbitrary mapping.
Container Dependencies

Correct operation of the invoker servlet depends on the following specific features of the surrounding container:

  • Correct support for the ContainerServlet interface, including calling setWrapper() before the init() method of the invoker servlet is called.
  • The web application class loader must be stored as the context class loader of the request processing thread.
Functionality
Initialization Functionality

The following processing must be performed when the init() method of the invoker servlet is called:

  • Ensure that the container has called setWrapper(). If not, throw a permanent UnavailableException.
  • Look up and cache the Context that corresponds to our Wrapper. This is the component with which new servlet definitions and mappings will be registered.
Per-Request Functionality

On each request, the following processing shall be performed:

  1. Calculate the {ServletPath} for this request, either from request attribute javax.servlet.include.servlet_path or by calling request.getServletPath().
  2. Calculate the {PathInfo} for this request, either from request attribute javax.servlet.include.path_info or by calling request.getPathInfo(). If the calculated {PathInfo} is null, return HTTP status 400 (bad request).
  3. Parse the calculated {PathInfo} value as follows:
    1. Ignore the leading slash character.
    2. Accumulate characters up to the next '/' (if any) as the {ServletSelector}.
    3. If a '/' was encountered, accumulate all characters from that slash (inclusive) to the end of the string as {PathRemainder}. If no slash was encountered, set {PathRemainder} to a zero-length string.
  4. Determine whether {ServletSelector} is the name of an existing servlet definition, and process it as follows:
    1. Ask our associated Context to find and return a child Wrapper named {ServletSelector}.
    2. If there is no such child, skip to the next major step.
    3. Register a new servlet mapping for this Wrapper, using a URL pattern calculated as follows: {ServletPath} + "/" + {ServletSelector} + "/*"
    4. Create a request dispatcher using a path calculated as follows: {ServletPath} + "/" + {ServletSelector} + {PathRemainder}
    5. Forward this request to the created request dispatcher, and exit from this request.
  5. Assume that {ServletSelector} is the fully qualified name of a Java class that implements javax.servlet.Servlet and process it as follows:
    1. Synthesize a new {ServletName} for the servlet definition that will be created.
    2. If there is already a child Wrapper associated with this name, return HTTP status 500 (internal server error), because a mapping should have already been created for this servlet.
    3. Attempt to load a class named {ServletSelector} from the web application class loader (i.e. the context class loader for our current thread). If this fails, return HTTP status 404 (not found).
    4. Instantiate an instance of this class. If an error occurs, return HTTP status 404 (not found).
    5. If this class does not implement the javax.servlet.Servlet interface, return HTTP status 404 (not found).
    6. Create and register a new Wrapper child with our Context, under name {ServletName}.
    7. Register a new servlet mapping for this Wrapper, using a URL pattern calculated as follows: {ServletPath} + "/" + {ServletSelector} + "/*"
    8. Create a request dispatcher using a path calculated as follows: {ServletPath} + "/" + {ServletSelector} + {PathRemainder}
    9. Forward this request to the created request dispatcher, and exit from this request.
Finalization Functionality

No specific processing is required when the destroy() method is called:

Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of the invoker servlet:

  • It is possible to access an existing servlet definition by name through the invoker. The existing servlet definition can include either a <servlet-class> or <jsp-file> subelement.
  • When an existing servlet definition is accessed by name, the request will be ultimately processed by the same servlet instance that would have processed it had a mapping to that servlet definition been used on the request directly.
  • It is possible to access an anonymous servlet by class name through the invoker.
  • When an anonymous servlet is accessed, the servlet instance is processed according to the lifecycle requirements of the Servlet Specification.
  • When an anonymous servlet is accessed, the servlet instance receives a ServletConfig instance with no servlet initialization parameters.
  • It is possible to utilize the invoker servlet via a direct request.
  • It is possible to utilize the invoker servlet via a call to RequestDispatcher.forward(), or the corresponding <jsp:forward> tag in a JSP page.
  • It is possible to utilize the invoker servlet via a call to RequestDispatcher.include(), or the corresponding <jsp:include> tag in a JSP page.
  • It is possible to use any HTTP method (including GET and POST) that is supported by the Servlet class that is ultimately executed.
  • The invoker servlet should never be asked to process a second or subsequent request for the same {ServletSelector} (because it will have registered an appropriate servlet mapping.


Catalina Functional Specifications - JDBCRealm

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

JDBCRealm

 Printer Friendly Version
print-friendly
version
Overview
Introduction

The purpose of the JDBCRealm implementation is to provide a mechanism by which Tomcat 5 can acquire information needed to authenticate web application users, and define their security roles, from a relational database accessed via JDBC APIs. For integration with Catalina, the resulting class(es) must implement the org.apache.catalina.Realm interface.

This specification reflects a combination of functionality that is already present in the org.apache.catalina.realm.JDBCRealm class, as well as requirements for enhancements that have been discussed. Where appropriate, requirements statements are marked [Current] and [Requested] to distinguish them.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

External Specifications

The implementation of this functionality depends on the following external specifications:

  • Java Database Connectivity (version 2.0 or later)
  • Java Database Connectivity Optional Package (version 2.0 or later)
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Be realized in one or more implementation classes.
  • Implement the org.apache.catalina.Realm interface. [Current]
  • Implement the org.apache.catalina.Lifecycle interface. [Current]
  • Subclass the org.apache.catalina.realm.RealmBase base class.
  • Live in the org.apache.catalina.realm package. [Current]
  • Support a configurable debugging detail level. [Current]
  • Log debugging and operational messages (suitably internationalized) via the getContainer().log() method. [Current]
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for JDBCRealm to operate correctly:

  • The desire to utilize JDBCRealm must be registered in $CATALINA_HOME/conf/server.xml, in a <Realm> element that is nested inside a corresponding <Engine>, <Host>, or <Context> element.
Container Dependencies

Correct operation of JDBCRealm depends on the following specific features of the surrounding container:

  • Interactions with JDBCRealm will be initiated by the appropriate Authenticator implementation, based on the login method that is selected.
  • JDBCRealm must have the JDBC standard API classes available to it. For a JDK 1.2 or later container, these APIs are included in the standard platform.
  • When connection pooling is implemented, JDBCRealm must have the JDBC Optional Package (version 2.0 or later) APIs available to it. This library is available as a separate download (and will be included in Tomcat binary distributions).
Functionality
Overview of Operation

The main purpose of JDBCRealm is to allow Catalina to authenticate users, and look up the corresponding security roles, from the information found in a relational database accessed via JDBC APIs. For maximum flexibility, the details of how this is done (for example, the names of the required tables and columns) should be configurable.

Each time that Catalina needs to authenticate a user, it will call the authenticate() method of this Realm implementation, passing the username and password that were specified by the user. If we find the user in the database (and match on the password), we accumulate all of the security roles that are defined for this user, and create a new GenericPrincipal object to be returned. If the user is not authenticated, we return null instead. The GenericUser object caches the set of security roles that were owned by this user at the time of authentication, so that calls to isUserInRole() can be answered without going back to the database every time.

Detailed Functional Requirements

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • Configuration parameters defining the JDBC driver to use, the database connection URL to be accessed, and the username/password to use for logging in. [Current]
  • Configuration parameters describing the connection pool to be created to support simultaneous authentications. [Requested]
  • Name of the tables to be searched for users and roles. [Current]
  • Name of the columns to be used for usernames, passwords, and role names. [Current]

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • Establish a connection to the configured database, using the configured username and password. [Current]
  • Configure and establish a connection pool of connections to the database. [Requested]

The following processing must be performed when the stop() method is called:

  • Close any opened connections to the database.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Acquire the one and only connection [Current] or acquire a connection from the connection pool [Requested].
  • Select the one and only row from the user's table for this user, and retrieve the corresponding password column. If zero rows (or more than one row) are found, return null.
  • Authenticate the user by comparing the (possibly encrypted) password value that was received against the password presented by the user. If there is no match, return null.
  • Acquire a List of the security roles assigned to the authenticated user by selecting from the roles table.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal, passing as constructor arguments: this realm instance, the authenticated username, and a List of the security roles associated with this user.
  • WARNING - Do not attempt to cache and reuse previous GenericPrincipal objects for a particular user, because the information in the directory server might have changed since the last time this user was authenticated.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of JDBCRealm:


Catalina Functional Specifications - JNDIRealm

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

JNDIRealm

 Printer Friendly Version
print-friendly
version
Overview
Introduction

The purpose of the JNDIRealm implementation is to provide a mechanism by which Tomcat 5 can acquire information needed to authenticate web application users, and define their security roles, from a directory server or other service accessed via JNDI APIs. For integration with Catalina, this class must implement the org.apache.catalina.Realm interface.

This specification reflects a combination of functionality that is already present in the org.apache.catalina.realm.JNDIRealm class, as well as requirements for enhancements that have been discussed. Where appropriate, requirements statements are marked [Current] and [Requested] to distinguish them.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

The code in the current version of JNDIRealm, and the ideas expressed in this functional specification, are the results of contributions from many individuals, including (alphabetically):

  • Holman, John <j.g.holman@qmw.ac.uk>
  • Lockhart, Ellen <elockhart@home.com>
  • McClanahan, Craig <craigmcc@apache.org>
External Specifications

The implementation of this functionality depends on the following external specifications:

  • Java Naming and Directory Interface (version 1.2.1 or later)
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Be realized in one or more implementation classes.
  • Implement the org.apache.catalina.Realm interface. [Current]
  • Implement the org.apache.catalina.Lifecycle interface. [Current]
  • Subclass the org.apache.catalina.realm.RealmBase base class.
  • Live in the org.apache.catalina.realm package. [Current]
  • Support a configurable debugging detail level. [Current]
  • Log debugging and operational messages (suitably internationalized) via the getContainer().log() method. [Current]
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for JNDIRealm to operate correctly:

  • The desire to utilize JNDIRealm must be registered in $CATALINA_HOME/conf/server.xml, in a <Realm> element that is nested inside a corresponding <Engine>, <Host>, or <Context> element.
  • If the Administrator Login operational mode is selected, the configured administrator username and password must be configured in the corresponding directory server.
  • If the Username Login operational mode is selected, the corresponding directory server must be configured to accept logins with the username and password that will be passed to JNDIRealm by the appropriate Authenticator.
Container Dependencies

Correct operation of JNDIRealm depends on the following specific features of the surrounding container:

  • Interactions with JNDIRealm will be initiated by the appropriate Authenticator implementation, based on the login method that is selected.
  • JNDIRealm must have the JNDI API classes available to it. For a JDK 1.2 container, that means jndi.jar and the appropriate implementation (such as ldap.jar) must be placed in the server/lib directory.
Functionality
Operational Modes

The completed JNDIRealm must support two major operational modes in order to support all of the required use cases. For the purposes of this document, the modes are called administrator login and Username Login. They are described further in the following paragraphs.

For Administrator Login mode, JNDIRealm will be configured to establish one or more connections (using a connection pool) to an appropriate directory server, using JNDI APIs, under a "system administrator" username and password. This is similar to the approach normally used to configure JDBCRealm to access authentication and access control information in a database. It is assumed that the system administrator username and password that are configured provide sufficient privileges within the directory server to read (but not modify) the username, password, and assigned roles for each valid user of the web application associated with this Realm. The password can be stored in cleartext, or in one of the digested modes supported by the org.apache.catalina.realm.RealmBase base class.

For Username Login mode, JNDIRealm does not normally remain connected to the directory server. Instead, whenever a user is to be authenticated, a connection to the directory server (using the username and password received from the authenticator) is attempted. If this connection is successful, the user is assumed to be successfully authenticated. This connection is then utilized to read the corresponding security roles associated with this user, and the connection is then broken.

NOTE - Username Login mode cannot be used if you have selected login method DIGEST in your web application deployment descriptor (web.xml) file. This restriction exists because the cleartext password is never available to the container, so it is not possible to bind to the directory server using the user's username and password.

Because these operational modes work so differently, the functionality for each mode will be described separately. Whether or not both modes are actually supported by a single class (versus a class per mode) is an implementation detail left to the designer.

NOTE - The current implementation only implements part of the Administrator Lookup mode requirements. It does not support the Username Lookup mode at all, at this point.

Administrator Login Mode Functionality

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • connectionURL - URL of the directory server we will be contacting.
  • contextFactory - Fully qualified class name of the JNDI context factory used to retrieve our InitialContext. [com.sun.jndi.ldap.LdapCtxFactory]
  • Additional configuration properties required to establish the appropriate connection. [Requested]
  • Connection pool configuration properties. [Requested]
  • Configuration properties defining how a particular user is authenticated. The following capabilities should be supported:
    • Substitute the specified username into a string. [Requested]
    • Retrieve the distinguished name (DN) of an authorized user via an LDAP search string with a replacement placeholder for the username, and comparison of the password to a configurable attribute retrieved from the search result. [Current]
  • Configuration properties defining how the roles associated with a particular authenticated user can be retrieved. The following approaches should be supported:
    • Retrieve a specified attribute (possibly multi-valued) from an LDAP search expression, with a replacement placeholder for the DN of the user. [Current]
    • Retrieve a set of role names that are defined implicitly (by selecting principals that match a search pattern) rather than explicitly (by finding a particular attribute value). [Requested]

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • Establish a connection to the configured directory server, using the configured system administrator username and password. [Current]
  • Configure and establish a connection pool of connections to the directory server. [Requested]

The following processing must be performed when the stop() method is called:

  • Close any opened connections to the directory server.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Acquire the one and only connection [Current] or acquire a connection from the connection pool [Requested].
  • Authenticate the user by retrieving the user's Distinguished Name, based on the specified username and password.
  • If the user was not authenticated, release the allocated connection and return null.
  • Acquire a List of the security roles assigned to the authenticated user.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal, passing as constructor arguments: this realm instance, the authenticated username, and a List of the security roles associated with this user.
  • WARNING - Do not attempt to cache and reuse previous GenericPrincipal objects for a particular user, because the information in the directory server might have changed since the last time this user was authenticated.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Username Login Mode Functionality

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • connectionURL - URL of the directory server we will be contacting.
  • contextFactory - Fully qualified class name of the JNDI context factory used to retrieve our InitialContext. [com.sun.jndi.ldap.LdapCtxFactory]
  • Additional configuration properties required to establish the appropriate connection. [Requested]
  • Connection pool configuration properties. [Requested]
  • Configuration properties defining if and how a user might be looked up before binding to the directory server. The following approaches should be supported:
    • No previous lookup is required - username specified by the user is the same as that used to authenticate to the directory server.
    • Substitute the specified username into a string.
    • Search the directory server based on configured criteria to retrieve the distinguished name of the user, then attempt to bind with that distinguished name.
  • Configuration properties defining how the roles associated with a particular authenticated user can be retrieved. The following approaches should be supported:
    • Retrieve a specified attribute (possibly multi-valued) from an LDAP search expression, with a replacement placeholder for the DN of the user. [Current]

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • None required.

The following processing must be performed when the stop() method is called:

  • None required.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Attempt to bind to the directory server, using the username and password provided by the user.
  • If the user was not authenticated, release the allocated connection and return null.
  • Acquire a List of the security roles assigned to the authenticated user.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal, passing as constructor arguments: this realm instance, the authenticated username, and a List of the security roles associated with this user.
  • WARNING - Do not attempt to cache and reuse previous GenericPrincipal objects for a particular user, because the information in the directory server might have changed since the last time this user was authenticated.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of JNDIRealm:


Catalina Functional Specifications - MemoryRealm

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

MemoryRealm

 Printer Friendly Version
print-friendly
version
Overview
Introduction

The purpose of the MemoryRealm implementation is to provide a mechanism by which Tomcat 5 can acquire information needed to authenticate web application users, and define their security roles, from a simple text-based configuration file in XML format. This is intended to simplify the initial installation and operation of Tomcat 5, without the complexity of configuring a database or directory server based Realm. It is not intended for production use.

This specification reflects a combination of functionality that is already present in the org.apache.catalina.realm.MemoryRealm class, as well as requirements for enhancements that have been discussed. Where appropriate, requirements statements are marked [Current] and [Requested] to distinguish them.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

External Specifications

The implementation of this functionality depends on the following external specifications:

  • None
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Be realized in one or more implementation classes.
  • Implement the org.apache.catalina.Realm interface. [Current]
  • Implement the org.apache.catalina.Lifecycle interface. [Current]
  • Subclass the org.apache.catalina.realm.RealmBase base class.
  • Live in the org.apache.catalina.realm package. [Current]
  • Support a configurable debugging detail level. [Current]
  • Log debugging and operational messages (suitably internationalized) via the getContainer().log() method. [Current]
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for MemoryRealm to operate correctly:

  • The desire to utilize MemoryRealm must be registered in $CATALINA_HOME/conf/server.xml, in a <Realm> element that is nested inside a corresponding <Engine>, <Host>, or <Context> element. (This is already included in the default server.xml file.)
Container Dependencies

Correct operation of MemoryRealm depends on the following specific features of the surrounding container:

  • Interactions with MemoryRealm will be initiated by the appropriate Authenticator implementation, based on the login method that is selected.
  • MemoryRealm must have an XML parser compatible with the JAXP/1.1 APIs available to it. This is normally accomplished by placing the corresponding JAR files in directory $CATALINA_HOME/server/lib (to make them visible only to internal Catalina classes) or in directory $CATALINA_HOME/common/lib (to make them visible to Catalina internal classes and installed web applications).
Functionality
Overview of Operation

The main purpose of MemoryRealm is to allow Catalina to authenticate users, and look up the corresponding security roles, from the information found in an XML-format configuration file. The format of this file is described below. When a MemoryRealm instance is started, it will read the contents of this XML file and create an "in memory database" of all the valid users and their associated security roles.

Each time that Catalina needs to authenticate a user, it will call the authenticate() method of this Realm implementation, passing the username and password that were specified by the user. If we find the user in the database (and match on the password), we accumulate all of the security roles that are defined for this user, and create a new GenericPrincipal object to be returned. If the user is not authenticated, we return null instead. The GenericUser object caches the set of security roles that were owned by this user at the time of authentication, so that calls to isUserInRole() can be answered without going back to the database every time.

Detailed Functional Requirements

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • Configurable debugging detail level.
  • Configurable file pathname (absolute or relative to $CATALINA_HOME of the XML file containing our defined users. [conf/tomcat-users.xml].

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • Open and parse the specified XML file.
  • Create an in-memory database representation of the XML file contents.
  • NOTE - There is no requirement to recognize subsequent changes to the contents of the XML file.

The following processing must be performed when the stop() method is called:

  • Release object references to the in-memory database representation.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Select the one and only "user" instance from the in-memory database, based on matching the specified username. If there is no such instance, return null.
  • Authenticate the user by comparing the (possibly encrypted) password value that was received against the password presented by the user. If there is no match, return null.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal (if not already using this as the internal database representation) that contains the authenticated username and a List of the security roles associated with this user.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of MemoryRealm:


Catalina Functional Specifications - 目录

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

目录

 Printer Friendly Version
print-friendly
version
Catalina Functional Specifications

This documentation area includes functional specifications for many features supported by the Catalina servlet container portion of Tomcat 5. In most cases, these features are not documented in the underlying Servlet or JSP specifications, so a definition of the expected correct behavior is important both to implementors of those features, and to test writers trying to decide what to test.

The functional specifications are divided into the following categories in the menu (to the left):

  • Administrative Apps - Overall requirements for supporting an ability to configure and operate a Tomcat 5 installation through tools, as well as detailed requirements for the tools themselves.
  • Internal Servlets - Requirements for Catalina features that are implemented as internal, container-managed, servlets.
  • Realm Implementations - Requirements for the implementations of the org.apache.catalina.Realm interface (providing access to collections of users, passwords and roles) that are included in the standard Tomcat 5 distribution.

NOTE - In some cases, the contents of these functional specs has been "reverse engineered" from existing implementations. This exercise is stil useful, because it provides an introduction to what Catalina does, without being as concerned with how this is accomplished.

TODO - Obviously, this area has a long ways to go before it is complete. Contributions are welcome!


Catalina Functional Specifications - Tomcat MBean Names

Catalina Functional Specifications

Links

  • Docs Home
  • Functional Specs

Administrative Apps

  • Overall Requirements
  • Tomcat MBean Names
  • Administered Objects
  • Supported Operations

Internal Servlets

  • Default Servlet
  • Invoker Servlet

Realm Implementations

  • JDBC Realm
  • JNDI Realm
  • Memory Realm

Catalina Functional Specifications

Tomcat MBean Names

 Printer Friendly Version
print-friendly
version
Background

We will be using JMX MBeans as the technology for implementing manageability of Tomcat.

One of the key concepts of JMX (and JSR-77) is that each management bean has a unique name in the MBeanServer's registry, and that management applications can utilize these names to retrieve the MBean of interest to them for a particular management operation. This document proposes a naming convention for MBeans that allows easy calculation of the name for a particular MBean. For background information on JMX MBean names, see the Java Management Extensions Instrumentation and Agent Specification, version 1.0, section 6. In particular, we will be discussing the String Representation of ObjectName instances.

Catalina Object Hierarchy

Tomcat's servlet container implementation, called Catalina, can be represented as a hierarchy of objects that contain references to each other. The object hierarchy can be represented as a tree, or (isomorphically) based on the nesting of configuration elements in the conf/server.xml file that is traditionally used to configure Tomcat stand-alone.

The valid component nestings for Catalina are depicted in the following table, with columns that contain the following values:

  • Pattern - Nesting pattern of XML elements (in the conf/server.xml file) used to configure this component.
  • Cardinality - Minimum and maximum number of occurrences of this element at this nesting position, which also corresponds to the minimum and maximum number of Catalina components.
  • Identifier - Name of the JavaBeans property of this component that represents the unique identifier (within the nested hierarchy), if any.
  • MBean ObjectName - The portion of the MBean object name that appears after the domain name. For now, it should be assumed that all of these MBeans appear in the default JMX domain.

In the MBean ObjectName descriptions, several types of symbolic expressions are utilized to define variable text that is replaced by corresponding values:

  • ${GROUP} - One of the standard MBean names of the specified "group" category. For example, the expression ${REALM} represents the values like JDBCRealm and JAASRealm that identify the various MBeans for possible Realm components.
  • ${name} - Replaced by the value of property name from the current component.
  • ${parent.name} - Replaced by the value of property name from a parent of the current component, with the parent's type identified by parent.
  • ${###} - An arbitrary numeric identifier that preserves order but has no other particular meaning. In general, the server will assign numeric values to existing instances with large gaps into which new items can be configured if desired.
模式 | Cardinality | Identifier | MBean ObjectName
<Server> | 1..1 | (none) | type=${SERVER}
Server / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}
Server / Service | 1..n | name(名称) | type=${SERVICE}, name=${name}
Server / Service / Connector | 1..n | address, port | type=${CONNECTOR}, service=${service}, port=${port}, address=${address}
Server / Service / Connector / Factory | 0..1 | (none) | (Only defined explicitly for an SSL connector, but can be treated as part of the connector component)
Server / Service / Connector / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}, service=${service}, port=${connector.port}, address=${connector.address}
Server / Service / Engine | 1..1 | (none) | type=${ENGINE}, service=${service.name}
Server / Service / Engine / Host | 1..n | name(名称) | type=${HOST}, host=${name}, service=${service.name}
Server / Service / Engine / Host / Context | 1..n | 路径 | type=${CONTEXT}, path=${path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / InstanceListener | 0..n | (none) | type=${INSTANCE-LISTENER}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Loader | 0..1 | (none) | type=${LOADER}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Manager | 0..1 | (none) | type=${MANAGER}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Realm | 0..1 | (none) | type=${REALM}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Resources | 0..1 | (none) | type=${RESOURCES}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Valve | 0..n | (none) | type=${VALVE}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Wrapper 0..n (none)
j2eeType=Servlet,name=${name},
        WebModule=//${host.name}/${context.name},
        J2EEApplication=${context.J2EEApplication},
        J2EEServer=${context.J2EEServer}
Server / Service / Engine / Host / Context / WrapperLifecycle | 0..n | (none) | type=${WRAPPER-LIFECYCLE}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / WrapperListener | 0..n | (none) | type=${WRAPPER-LISTENER}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Realm | 0..1 | (none) | type=${REALM}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Valve | 0..n | (none) | type=${VALVE}, sequence=${###}, host=${host.name}, service=${service.name}
Server / Service / Engine / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###} (FIXME - disambiguate from Server / Service / Listener)
Server / Service / Engine / Realm | 0..1 | (none) | type=${REALM}, service=${service.name}
Server / Service / Engine / Valve | 0..n | (none) | type=${VALVE}, sequence=${###}, service=${service.name}
Server / Service / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###} (FIXME - disambiguate from Server / Service / Engine / Listener)
MBean Groups and Names

The following MBean names shall be defined in the resource file /org/apache/catalina/mbeans/mbeans-descriptors.xml (and therefore available for use within the Administration/Configuration web application for Tomcat):

MBean Name | Group Name | Catalina Interface | Implementation Class
AccessLogValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.AccessLogValve
BasicAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.BasicAuthenticator
CertificatesValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.CertificatesValve
ContextConfig | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.startup.ContextConfig
ContextEnvironment | 资源 | org.apache.catalina.deploy.ContextEnvironment | org.apache.catalina.deploy.ContextEnvironment
ContextResource | 资源 | org.apache.catalina.deploy.ContextResource | org.apache.catalina.deploy.ContextResource
ContextResourceLink | 资源 | org.apache.catalina.deploy.ContextResourceLink | org.apache.catalina.deploy.ContextResourceLink
CoyoteConnector | connector | org.apache.catalina.Connector | org.apache.coyote.tomcat4.CoyoteConnector
DigestAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.DigestAuthenticator
EngineConfig | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.startup.EngineConfig
ErrorReportValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.ErrorReportValve
ErrorDispatcherValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.ErrorDispatcherValve
FormAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.FormAuthenticator
组 | 组 | org.apache.catalina.Group | org.apache.catalina.Group
HostConfig | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.startup.HostConfig
HttpConnector10 | connector | org.apache.catalina.Connector | org.apache.catalina.connector.http10.HttpConnector
HttpConnector11 | connector | org.apache.catalina.Connector | org.apache.catalina.connector.http.HttpConnector
JAASRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.JAASRealm
JDBCRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.JDBCRealm
JDBCUserDatabase | USERDATABASE | org.apache.catalina.users.JDBCUserDatabase | org.apache.catalina.users.JDBCUserDatabase
JNDIRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.JNDIRealm
MBeanFactory | org.apache.catalina.mbeans.MBeanFactory
MemoryRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.MemoryRealm
MemoryUserDatabase | USERDATABASE | org.apache.catalina.users.MemoryUserDatabase | org.apache.catalina.users.MemoryUserDatabase
NamingContextListener | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.core.NamingContextListener
NamingResources | 资源 | org.apache.catalina.deploy.NamingResources | org.apache.catalina.deploy.NamingResources
NonLoginAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.NonLoginAuthenticator
PersistentManager | 管理者 | org.apache.catalina.Manager | org.apache.catalina.session.PersistentManager
RemoteAddrValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.RemoteAddrValve
RemoteHostValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.RemoteHostValve
RequestDumperValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.RequestDumperValve
角色 | 角色 | org.apache.catalina.Role | org.apache.catalina.Role
SingleSignOn | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.SingleSignOn
SSLAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.SSLAuthenticator
StandardContext | <Context> | org.apache.catalina.Context | org.apache.catalina.core.StandardContext
StandardContextValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardContextValve
StandardEngine | <Engine> | org.apache.catalina.Engine | org.apache.catalina.core.StandardEngine
StandardEngineValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardEngineValve
StandardHost | <Host> | org.apache.catalina.Host | org.apache.catalina.core.StandardHost
StandardHostValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardHostValve
StandardManager | 管理者 | org.apache.catalina.Manager | org.apache.catalina.session.StandardManager
StandardServer | <Server> | org.apache.catalina.Server | org.apache.catalina.core.StandardServer
StandardService | <Service> | org.apache.catalina.Service | org.apache.catalina.core.StandardService
StandardWrapper | 包? | org.apache.catalina.Wrapper | org.apache.catalina.core.StandardWrapper
StandardWrapperValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardWrapperValve
用户 | 用户 | org.apache.catalina.User | org.apache.catalina.User
UserDatabaseRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.UserDatabaseRealm
WebappLoader | 载入器 | org.apache.catalina.Loader | org.apache.catalina.loader.WebappLoader
JSR-77 Cross Reference

The managed objects in the JSR-77 object hierarchy correspond to the specified MBean names or groups as follows:

JSR-77 Managed Object | MBean Name or Group | 评论，建议
J2EEServer | <Service>
Node | <Service> | Tomcat supports a single node only.
port(端口) | connector
Servlet | 包?
WebModule | <Context>
JSR-88 Cross Reference

The deployment objects in the JSR-88 API object hierarchy correspond to the specified MBean names or groups as follows:

JSR-88 API Object | MBean Name or Group | 评论，建议
DeployableObject | <Context> | Context deployment info plus the corresponding WAR file
目标 | <Host>


Catalina Functional Specifications - Administrative Apps - Overall Requirements

Catalina Functional Specifications

Catalina Functional Specifications

Administrative Apps - Overall Requirements
Overview
Introduction

The purpose of this specification is to define high level requirements for administrative applications that can be used to manage the operation of a running Tomcat 5 container. A variety of Access Methods to the supported administrative functionality shall be supported, to meet varying requirements:

  • As A Scriptable Web Application - The existing Manager web application provides a simple HTTP-based interface for managing Tomcat through commands that are expressed entirely through a request URI. This is useful in environments where you wish to script administrative commands with tools that can generate HTTP transactions.
  • As An HTML-Based Web Application - Use an HTML presentation to provide a GUI-like user interface for humans to interact with the administrative capabilities.
  • As SOAP-Based Web Services - The operational commands to administer Tomcat are made available as web services that utilize SOAP message formats.
  • As Java Management Extensions (JMX) Commands - The operational commands to administer Tomcat are made available through JMX APIs, for integration into management consoles that utilize them.
  • Other Remote Access APIs - Other remote access APIs, such as JINI, RMI, and CORBA can also be utilized to access administrative capabilities.

Underlying all of the access methods described above, it is assumed that the actual operations are performed either directly on the corresponding Catalina components (such as calling the Deployer.deploy() method to deploy a new web application), or through a "business logic" layer that can be shared across all of the access methods. This approach minimizes the cost of adding new administrative capabilities later -- it is only necessary to add the corresponding business logic function, and then write adapters to it for all desired access methods.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

External Specifications

The implementation of this functionality depends on the following external specifications:

  • Java IDL (for CORBA, included in the JDK)
  • Java Management Extensions
  • Remote Method Invocation (Included in the JDK)
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • To the maximum extent feasible, all administrative functions, and the access methods that support them, shall run portably on all platforms where Tomcat 5 itself runs.
  • In a default Tomcat distribution, all administrative capabilities shall be disabled. It shall be necessary for a system administrator to specifically enable the desired access methods (such as by adding a username/password with a specific role to the Tomcat user's database.
  • Administrative functions shall be realized as direct calls to corresponding Catalina APIs, or through a business logic layer that is independent of the access method used to initiate it.
  • The common business logic components shall be implemented in package org.apache.catalina.admin.
  • The common business logic components shall be built as part of the standard Catalina build process, and made visible in the Catalina class loader.
  • The Java components required for each access method shall be implemented in subpackages of org.apache.catalina.admin.
  • The build scripts should treat each access method as optional, so that it will be built only if the corresponding required APIs are present at build time.
  • It shall be possible to save the configured state of the running Tomcat container such that this state can be reproduced when the container is shut down and restarted.
  • Adminstrative commands to start up and shut down the overall Tomcat container are out of scope for the purposes of these applications. It is assumed that other (usually platform-specific) mechanisms will be used for container startup and shutdown.
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for administrative applications to operate correctly:

  • For access methods that require creation of server sockets, the appropriate ports must be configured and available.
Container Dependencies

Correct operation of administrative applications depends on the following specific features of the surrounding container:

  • To the maximum extent feasible, Catalina components that offer direct administrative APIs and property setters shall support "live" changes to their operation, without requiring a container restart.
External Technologies

The availability of the following technologies can be assumed for the implementation and operation of the various access methods and the corresponding administrative business logic:

  • Java 2 Standard Edition (Version 1.2 or later)
  • Servlet 2.4 (supported natively by Tomcat 5)
  • JavaServer Pages 2.0 (supported natively by Tomcat 5)
  • JavaServer Pages Standard Tag Library 1.0 (Jakarta Taglibs-Standard 1.0.3)
  • Struts Framework (Version 1.0) - MVC Framework for Web Applications
  • TO BE DETERMINED - Application for hosting SOAP based web services
Functionality
Properties of Administered Objects

Functional requirements for administrative applications are specified in terms of Administered Objects, whose definitions and detailed properties are listed here. In general, Administered Objects correspond to components in the Catalina architecture, but these objects are defined separately here for the following reasons:

  • It is possible that the administrative applications do not expose every possible configurable facet of the underlying components.
  • In some cases, an Administered Object (from the perspective of an administrative operation) is realized by more than one Catalina component, at a finer-grained level of detail.
  • It is necessary to represent the configuration information for a component separately from the component itself (for instance, in order to store that configuration information for later use).
  • It is necessary to represent configuration information (such as a Default Context) when there is no corresponding component instance.
  • Administered Objects, when realized as Java classes, will include methods for administrative operations that have no correspondence to operations performed by the corresponding actual components.

It is assumed that the reader is familiar with the overall component architecture of Catalina. For further information, see the corresponding Developer Documentation. To distinguish names that are used as both Administered Objects and Components, different font presentations are utilized. Default values for many properties are listed in [square brackets].

Supported Administrative Operations

The administrative operations that are available are described in terms of the corresponding Administered Objects (as defined above), in a manner that is independent of the access method by which these operations are requested. In general, such operations are relevant only in the context of a particular Administered Object (and will most likely be realized as method calls on the corresponding Administered Object classes), so they are organized based on the currently "focused" administered object. The available Supported Operations are documented here.

Access Method Specific Requirements
Scriptable Web Application

An appropriate subset of the administrative operations described above shall be implemented as commands that can be performed by the "Manager" web application. FIXME - Enumerate them.

In addition, this web application shall conform to the following requirements:

  • All request URIs shall be protected by a security constraint that requires security role manager for processing.
  • The default user database shall not contain any user that has been assigned the role manager.
HTML-Based Web Application

The entire suite of administrative operations described above shall be made available through a web application designed for human interaction. In addition, this web application shall conform to the following requirements:

  • Must be implemented using servlet, JSP, and MVC framework technologies described under "External Technologies", above.
  • Prompts and error messages must be internationalizable to multiple languages.
  • Rendered HTML must be compatible with Netscape Navigator (verson 4.7 or later) and Internet Explorer (version 5.0 or later).
Testable Assertions

FIXME - Complete this section.


Catalina Functional Specifications - Administrative Apps - Administered Objects

Catalina Functional Specifications

Catalina Functional Specifications

Administrative Apps - Administered Objects
Administered Objects Overview

This document defines the Administered Objects that represent the internal architectural components of the Catalina servlet container. Associated with each is a set of Supported Operations that can be performed when the administrative application is "focused" on a particular configurable object.

The following Administered Objects are defined:

  • Access Logger
  • connector
  • <Context>
  • 默认Context
  • Default Deployment Descriptor
  • <Engine>
  • Environment Entry
  • <Host>
  • JDBC Resource
  • 载入器
  • 管理者
  • <Realm>
  • Request Filter
  • <Server>
  • <Service>
Access Logger

An Access Logger is an optional Valve that can create request access logs in the same formats as those provided by web servers. Such access logs are useful input to hit count and user access tracking analysis programs. An Access Logger can be attached to an Engine, a Host, a Context, or a Default Context.

The standard component implementing an Access Logger is org.apache.catalina.valves.AccessLogValve. It supports the following configurable properties:

  • debug - Debugging detail level. [0]
  • directory - Absolute or relative (to $CATALINA_HOME) path of the directory into which access log files are created. [logs].
  • pattern - Pattern string defining the fields to be included in the access log output, or "common" for the standard access log pattern. See org.apache.catalina.valves.AccessLogValve for more information. [common]
  • prefix - Prefix added to the beginning of each log file name created by this access logger.
  • resolveHosts - Should IP addresses be resolved to host names in the log? [false]
  • suffix - Suffix added to the end of each log file name created by this access logger.
Connector

A Connector is the representation of a communications endpoint by which requests are received from (and responses returned to) a Tomcat client. The administrative applications shall support those connectors that are commonly utilized in Tomcat installations, as described in detail below.

For standalone use, the standard connector supporting the HTTP/1.1 protocol is org.apache.catalina.connectors.http.HttpConnector. It supports the following configurable properties:

  • acceptCount - The maximum queue length of incoming connections that have not yet been accepted. [10]
  • address - For servers with more than one IP address, the address upon which this connector should listen. [All Addresses]
  • bufferSize - Default input buffer size (in bytes) for requests created by this Connector. [2048]
  • debug - Debugging detail level. [0]
  • enableLookups - Should we perform DNS lookups on remote IP addresses when request.getRemoteHost() is called? [true]
  • maxProcessors - The maximum number of processor threads supported by this connector. [20]
  • minProcessors - The minimum number of processor threads to be created at container startup. [5]
  • port - TCP/IP port number on which this Connector should listen for incoming requests. [8080]
  • proxyName - Host name to be returned when an application calls request.getServerName(). [Value of Host: header]
  • proxyPort - Port number to be returned when an application calls request.getServerPort(). [Same as port]
Context

A Context is the representation of an individual web application, which is associated with a corresponding Host. Note that the administrable properties of a Context do not include any settings from inside the web application deployment descriptor for that application.

The standard component implementing a Context is org.apache.catalina.core.StandardContext. It supports the following configurable properties:

  • cookies - Should be use cookies for session identifier communication? [true]
  • crossContext - Should calls to ServletContext.getServletContext() return the actual context responsible for the specified path? [false]
  • debug - Debugging detail level. [0]
  • docBase - The absolute or relative (to the appBase of our owning Host) pathname of a directory containing an unpacked web application, or of a web application archive (WAR) file.
  • override - Should settings in this Context override corresponding settings in the Default Context? [false]
  • path - Context path for this web application, or an empty string for the root application of a Host. [Inferred from directory or WAR file name]
  • reloadable - Should Tomcat monitor classes in the /WEB-INF/classes directory for changes, and reload the application if they occur? [false]
  • useNaming - Should Tomcat provide a JNDI naming context, containing preconfigured entries and resources, corresponding to the requirements of the Java2 Enterprise Edition specification? [true]
  • workDir - Absolute pathname of a scratch directory that is provided to this web application. [Automatically assigned relative to $CATALINA_HOME/work]

Each Context is owned by a parent Host, and is associated with:

  • An optional Access Logger that logs all requests processed by this web application.
  • Zero or more Environment Entries representing environment entries for the JNDI naming context associated with a web application.
  • Zero or more JDBC Resources representing database connection pools associated with a web application.
  • A Loader representing the web application class loader used by this web application.
  • A Manager representing the session manager used by this web application.
  • An optional Realm used to provide authentication and access control information for this web application.
  • Zero or more Request Filters used to limit access to this web application based on remote host name or IP address.
Default Context

A Default Context represents a subset of the configurable properties of a Context, and is used to set defaults for those properties when web applications are automatically deployed. A Default Context object can be associated with an Engine or a Host. The following configurable properties are supported:

  • cookies - Should be use cookies for session identifier communication? [true]
  • crossContext - Should calls to ServletContext.getServletContext() return the actual context responsible for the specified path? [false]
  • reloadable - Should Tomcat monitor classes in the /WEB-INF/classes directory for changes, and reload the application if they occur? [false]
  • useNaming - Should Tomcat provide a JNDI naming context, containing preconfigured entries and resources, corresponding to the requirements of the Java2 Enterprise Edition specification? [true]

Each Default Context is owned by a parent Engine or Host, and is associated with:

  • Zero or more Environment Entries representing environment entries for the JNDI naming context associated with a web application.
  • Zero or more JDBC Resources representing database connection pools associated with a web application.
  • An optional Loader representing default configuration properties for the Loader component of deployed web applications.
  • An optional Manager representing default configuration properties for the Manager component fo deployed web applications.
Default Deployment Descriptor

Default web application characteristics are configured in a special deployment descriptor named $CATALINA_HOME/conf/web.xml. This section describes the configurable components that may be stored there.

FIXME - Complete the description of default servlets, default mappings, default MIME types, and so on.

Engine

An Engine is the representation of the entire Catalina servlet container, and processes all requests for all of the associated virtual hosts and web applications.

The standard component implementing an Engine is org.apache.catalina.core.StandardEngine. It supports the following configurable properties:

  • debug - Debugging detail level. [0]
  • defaultHost - Name of the Host to which requests will be directed if the requested host is unknown. [localhost]
  • name - Logical name of this engine. [Tomcat Stand-Alone]

Each Engine is owned by a parent Service, and is associated with:

  • An optional Access Logger that logs all requests processed by the entire container.
  • A Default Context, representing default properties of a Context for automatically deployed applications for all associated Hosts (unless overridden by a subordinate component).
  • One or more Hosts representing individual virtual hosts supported by this container.
  • A Realm used to provide authentication and access control information for all virtual hosts and web applications (unless overridden by a subordinate component).
  • Zero or more Request Filters used to limit access to the entire container based on remote host name or IP address.
Environment Entry

An Environment Entry is the representation of a <env-entry> element from a web application deployment descriptor. It will cause the creation of a corresponding entry in the JNDI naming context provided to the corresponding Context. The following configurable properties are supported:

  • description - Description of this environment entry.
  • name - Environment entry name (relative to the java:comp/env context)
  • type - Environment entry type (must be one of the fully qualified Java classes listed in the servlet spec).
  • value - Environment entry value (must be convertible from String to the specified type.
Host

A Host is the representation of an individual virtual host, which has a unique set of associated web applications.

The standard component implementing a Host is org.apache.catalina.core.StandardHost. It supports the following configurable properties:

  • aliases - Zero or more DNS names that are also associated with this host (for example, a particular host might be named www.mycompany.com with an alias company.com).
  • appBase - Absolute or relative (to $CATALINA_HOME) path to a directory from which web applications will be automatically deployed.
  • debug - Debugging detail level. [0]
  • name - DNS Name of the virtual host represented by this object.
  • unpackWARs - Should web application archive files deployed by this virtual host be unpacked first? [true]

Each Host is owned by a parent Engine, and is associated with:

  • An optional Access Logger that logs all requests processed by this virtual host.
  • One or more Contexts representing the web applications operating on this Host.
  • A Default Context representing default Context properties for web applications that are automatically deployed by this Host.
  • A optional Realm used to provide authentication and access control information for all web applications associated with this virtual host (unless overridden by a subordinate component).

FIXME - Should we support configuration of the User Web Applications functionality?

JDBC Resource

A JDBC Resources represents a database connection pool (i.e. an implementation of javax.sql.DataSource that will be configured and made available in the JNDI naming context associated with a web application.

FIXME - properties of this administered object

Loader

A Loader represents a web application class loader that will be utilized to provide class loading services for a particular Context.

The standard component implementing a Loader is org.apache.catalina.loader.StandardLoader. It supports the following configurable properties:

  • checkInterval - Number of seconds between checks for modified classes, if automatic reloading is enabled. [15]
  • debug - Debugging detail level. [0]
  • reloadable - Should this class loader check for modified classes and initiate automatic reloads? [Set automatically from the reloadable property of the corresponding Context]

Each Loader is owned by a parent Context.

Manager

A Manager represents a session manager that will be associated with a particular web application. FIXME - Add support for advanced session managers and their associated Stores.

The standard component implementing a Manager is org.apache.catalina.session.StandardManager. It supports the following configurable properties:

  • checkInterval - Number of seconds between checks for expired sessions. [60]
  • debug - Debugging detail level. [0]
  • entropy - String initialization parameter used to increase the entropy (initial randomness) of the random number generator used to create session identifiers. [Inferred from engine, host, and context]
  • maxActiveSessions - The maximum number of active sessions that are allowed, or -1 for no limit. [-1]

Each Manager is owned by a parent Context.

Realm

A Realm represents a "database" of information about authorized users, their passwords, and the security roles assigned to them. This will be used by the container in the implementation of container-managed security in accordance with the Servlet Specification. Several alternative implementations are supported.

org.apache.catalina.realm.MemoryRealm initializes its user information from a simple XML file at startup time. If changes are made to the information in this file, the corresponding web applications using it must be restarted for the changes to take effect. It supports the following configurable properties:

  • debug - Debugging detail level. [0]
  • pathname - Absolute or relative (to $CATALINA_HOME) path to the XML file containing our user information. [conf/tomcat-users.xml]

org.apache.catalina.realm.JDBCRealm uses a relational database (accessed via JDBC APIs) to contain the user information. Changes in the contents of this database take effect immediately; however, the roles assigned to a particular user are calculated only when the user initially logs on (and not per request). The following configurable properties are supported:

  • connectionName - Database username to use when establishing a JDBC connection.
  • connectionPassword - Database password to use when establishing a JDBC connection.
  • connectionURL - Connection URL to use when establishing a JDBC connection.
  • debug - Debugging detail level. [0]
  • digest - Name of the MessageDigest algorithm used to encode passwords in the database, or a zero-length string for no encoding. [Zero-length String]
  • driverName - Fully qualified Java class name of the JDBC driver to be utilized.
  • roleNameCol - Name of the column, in the User Roles table, which contains the role name.
  • userCredCol - Name of the column, in the Users table, which contains the password (encrypted or unencrypted).
  • userNameCol - Name of the column, in both the Users and User Roles tables, that contains the username.
  • userRoleTable - Name of the User Roles table, which contains one row per security role assigned to a particular user. This table must contain the columns specified by the userNameCol and roleNameCol properties.
  • userTable - Name of the Users table, which contains one row per authorized user. This table must contain the columns specified by the userNameCol and userCredCol properties.

FIXME - Should we provide mechanisms to edit the contents of a "tomcat-users.xml" file through the admin applications?

Each Realm is owned by a parent Engine, Host, or Context.

Request Filter

FIXME - complete this entry

Server

FIXME - complete this entry

Service

FIXME - complete this entry


Catalina Functional Specifications - Administrative Apps - Supported Operations

Catalina Functional Specifications

Catalina Functional Specifications

Administrative Apps - Supported Operations
Supported Operations Overview

This document defines the Supported Operations that may be performed against the Administered Objects that are supported by Tomcat 5 administrative applications. Not all operations are required to be available through every administrative application that is implemented. However, if a given operation is available, it should operate consistently with the descriptions found here.

Supported Operations are described for the following Administered Objects:

  • Access Logger
  • connector
  • <Context>
  • 默认Context
  • <Engine>
  • Environment Entry
  • <Host>
  • JDBC Resource
  • 载入器
  • 管理者
  • <Realm>
  • Request Filter
  • <Server>
  • <Service>
Access Logger

From the perspective of a particular Access Logger, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine, Host, or Context.
  • Edit the configurable properties of this object.
Connector

From the perspective of a particular Connector, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Service.
  • Edit the configurable properties of this object.
Context

From the perspective of a particular Context, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Host.
  • Edit the configurable properties of this object.
  • Create and configure a new Access Logger associated with this object.
  • Edit the configurable properties of the associated Access Logger.
  • Remove the associated Access Logger.
  • Create and configure a new Environment Entry associated with this object.
  • Select and edit the configurable properties of an associated Environment Entry.
  • Remove an associated Environment Entry.
  • Create and configure a new JDBC Resource associated with this object.
  • Select and edit the configurable properties of an associated JDBC Resource.
  • Remove an associated JDBC Resource.
  • Create and configure a new Loader associated with this object.
  • Edit the configurable properties of the associated Loader.
  • Remove the associated Loader.
  • Create and configure a new Manager associated with this object.
  • Edit the configurable properties of the associated Manager.
  • Remove the associated Manager.
  • Create and configure a new Realm associated with this object.
  • Edit the configurable properties of the associated Realm.
  • Remove the associated Realm.
  • Create and configure a new Request Filter associated with this object.
  • Select and edit the configurable properties of an associated Request Filter
  • Remove an associated Request Filter.
Default Context

From the perspective of a particular Default Context, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine or Host.
  • Edit the configurable properties of this object.
  • Create and configure a new Environment Entry associated with this object.
  • Select and edit the configurable properties of an associated Environment Entry.
  • Remove an associated Environment Entry.
  • Create and configure a new JDBC Resource associated with this object.
  • Select and edit the configurable properties of an associated JDBC Resource.
  • Remove an associated JDBC Resource.
Engine

From the perspective of a particular Engine, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Service.
  • Edit the configurable properties of this object.
  • Create and configure a new Access Logger associated with this object.
  • Edit the configurable properties of the associated Access Logger.
  • Remove the associated Access Logger.
  • Create and configure a new Default Context associated with this object.
  • Edit the configurable properties of the associated Default Context.
  • Remove the associated Default Context.
  • Create and configure a new Host associated with this object.
  • Select and edit the configurable properties of an associated Host.
  • Remove an associated Host.
  • Create and configure a new Realm associated with this object.
  • Edit the configurable properties of the associated Realm.
  • Remove the associated Realm.
  • Create and configure a new Request Filter associated with this object.
  • Select and edit the configurable properties of an associated Request Filter
  • Remove an associated Request Filter.
Environment Entry

From the perspective of a particular Environment Entry, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context or Default Context.
  • Edit the configurable properties of this object.
Host

From the perspective of a particular Host, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine.
  • Edit the configurable properties of this object.
  • Create and configure a new Access Logger associated with this object.
  • Edit the configurable properties of the associated Access Logger.
  • Remove the associated Access Logger.
  • Create and configure a new Context associated with this object.
  • Select and edit the configurable properties of an associated Context.
  • Remove an associated Context.
  • Create and configure a new Default Context associated with this object.
  • Edit the configurable properties of the associated Default Context.
  • Remove the associated Default Context.
  • Create and configure a new Realm associated with this object.
  • Edit the configurable properties of the associated Realm.
  • Remove the associated Realm.
  • Create and configure a new Request Filter associated with this object.
  • Select and edit the configurable properties of an associated Request Filter
  • Remove an associated Request Filter.
JDBC Resource

From the perspective of a particular JDBC Resource, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context or Default Context.
  • Edit the configurable properties of this object.
Loader

From the perspective of a particular Loader, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context.
  • Edit the configurable properties of this object.
Manager

From the perspective of a particular Manager, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Context.
  • Edit the configurable properties of this object.
Realm

From the perspective of a particular Realm, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine, Host, or Context.
  • Edit the configurable properties of this object.
Request Filter

From the perspective of a particular Request Filter, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Engine, Host, or Context.
  • Edit the configurable properties of this object.
Server

From the perspective of the overall Server, it shall be possible to perform the following administrative operations:

  • Edit the configurable properties of this object.
  • Create and configure a new Service associated with this object.
  • Select and edit the configurable properties of an associated Service.
Service

From the perspective of a particular Service, it shall be possible to perform the following administrative operations:

  • Navigate to the owning Server.
  • Edit the configurable properties of this object.
  • Create and configure a new Connector associated with this object.
  • Select and edit the configurable properties of an associated Connector.
  • Remove an associated Connector.
  • Create and configure a new Engine associated with this object.
  • Edit the configurable properties of the associated Engine.
  • Remove the associated Engine.


Catalina Functional Specifications - 缺省Servlet

Catalina Functional Specifications

Catalina Functional Specifications

缺省Servlet
Overview
Introduction

The purpose of the Default Servlet is to serve static resources of a web application in response to client requests. As the name implies, it is generally configured as the "default" servlet for a web application, by being mapped to a URL pattern "/".

External Specifications

The following external specifications have provisions which partially define the correct behavior of the default servlet:

  • Servlet Specification (Version 2.3 PFD2)
  • Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types
  • Hypertext Transfer Protocol -- HTTP/1.1
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Must be implemented as a servlet.
  • Must support configurable parameters for debugging detail level, input buffer size, output buffer size, whether or not to produce directory listings when no welcome file is present, and whether or not modifications are supported via DELETE and PUT.
  • Log debugging and operational messages (suitably internationalized) via the getServletContext().log() method.
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for the default servlet to operate correctly:

  • The default servlet must be registered in the application deployment descriptor (or the default deployment descriptor in file $CATALINA_HOME/conf/web.xml) using a "default servlet" servlet mapping, signified by URL pattern "/".
Container Dependencies

Correct operation of the default servlet depends on the following specific features of the surrounding container:

  • The container shall provide a servlet context attribute that lists the welcome file names that have been defined for this web application.
  • The container shall provide a servlet context attribute that contains a javax.naming.directory.DirContext implementation representing the static resources of this web application.
Functionality
Initialization Functionality

The following processing must be performed when the init() method of the invoker servlet is called:

  • Process and sanity check configuration parameters.
Per-Request Functionality

For all HTTP request methods, the resource path is determined from the path information provided to this request, either as request attribute javax.servlet.include.path_info (for a request dispatcher access to a static resource) or by calling request.getPathInfo() directly.

On each HTTP DELETE request processed by this servlet, the following processing shall be performed:

  • If modifications to the static resources are not allowed (set by a configuration parameter), return HTTP status 403 (forbidden).
  • If an attempt is made to delete a resource from /META-INF or /WEB-INF, return HTTP status 403 (forbidden).
  • If the requested resource does not exist, return HTTP status 404 (not found)
  • Unbind the resource from the directory context containing the static resources for this web application. If successful, return HTTP status 204 (no content). Otherwise, return HTTP status 405 (method not allowed).

On each HTTP GET request processed by this servlet, the following processing shall be performed:

  • If the request is for a resource under /META-INF or /WEB-INF, return HTTP status 404 (not found).
  • If the requested resource does not exist, return HTTP status 404 (not found).
  • If the requested resource is not a directory, but the resource path ends in "/" or "\", return HTTP status 404 (not found).
  • If the requested resource is a directory:
    • If the request path does not end with "/", redirect to a corresponding path with "/" appended so that relative references in welcome files are resolved correctly.
    • If one of the specified welcome files exists, redirect to the path for that welcome file so that it will be served explicitly.
  • If the request being processed contains an If-Range header, perform the processing described in the HTTP/1.1 specification to determine whether the client's information is up to date.
  • Determine the content type of the response, by looking up the corresponding MIME type in our servlet context.
  • If the requested resource is a directory:
    • If directory listings are suppressed, return HTTP status 404 (not found).
    • Set the content type to text/html.
  • Determine the range(s) to be returned, based on the existence of any If-Range and Range headers.
  • If the requested resource is a directory, include an ETag header in the response, with the value calculated based on the content of the directory.
  • Include a Last-Modified header in the response documenting the date/time that the resource was last modified.
  • Unless we are processing a HEAD request, include the appropriate content (or content ranges) in the response.

On each HTTP HEAD request processed by this servlet, the following processing shall be performed:

  • Processed identically to an HTTP GET request, except that the data content is not transmitted after the headers.

On each HTTP POST request processed by this servlet, the following processing shall be performed:

  • Processed identically to an HTTP GET request.

On each HTTP PUT request processed by this servlet, the following processing shall be perfomred:

  • If modifications to the static resources are not allowed (set by a configuration parameter), return HTTP status 403 (forbidden).
  • If an attempt is made to delete a resource from /META-INF or /WEB-INF, return HTTP status 403 (forbidden).
  • Create a new resource from the body of this request.
  • Bind or rebind the specified path to the new resource (depending on whether it currently exists or not). Return HTTP status as follows:
    • If binding was unsuccessful, return HTTP status 409 (conflict).
    • If binding was successful and the resource did not previously exist, return HTTP status 201 (created).
    • If binding was successful and the resource previously existed, return HTTP status 204 (no content).
Finalization Functionality

No specific processing is required when the destroy() method is called:

Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of the invoker servlet:

  • Requests for resources that do not exist in the web application must return HTTP status 404 (not found).
  • The default servlet must operate identically for web applications that are run out of a WAR file directly, or from an unpacked directory structure.
  • If the web application is running out of an unpacked directory structure, the default servlet must recognize cases where the resource has been updated through external means.


Catalina Functional Specifications - Invoker Servlet

Catalina Functional Specifications

Catalina Functional Specifications

Invoker Servlet
Overview
Introduction

The purpose of the Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a <servlet> element in the /WEB-INF/web.xml deployment descriptor, and execute requests utilizing the new servlet definitions. From the perspective of the newly registered servlets, all servlet lifecycle requirements of the Servlet Specification (such as calling init() and destroy() at the correct times) will be respected.

External Specifications

I do not know of any formal specification of the behavior of an invoker servlet that is publicly available. Anyone know of one?

Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Implemented as a servlet.
  • Exist in the org.apache.catalina.servlets package so that it can be loaded by the Catalina class loader.
  • Implement the org.apache.catalina.ContainerServlet interface, so that it gains knowledge of the Wrapper that is responsible for itself and, therefore, access to other internal Catalina components.
  • Support a configurable debugging detail level.
  • Log debugging and operational messages (suitably internationalized) via the getServletContext().log() method.
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for the Invoker servlet to operate correctly:

  • The invoker servlet must be registered in the application deployment descriptor (or the default deployment descriptor in file $CATALINA_HOME/conf/web.xml) using a "path mapped" servlet mapping. The historical default mapping is to URL pattern "/servlet/*", although the invoker servlet must operate correctly with an arbitrary mapping.
Container Dependencies

Correct operation of the invoker servlet depends on the following specific features of the surrounding container:

  • Correct support for the ContainerServlet interface, including calling setWrapper() before the init() method of the invoker servlet is called.
  • The web application class loader must be stored as the context class loader of the request processing thread.
Functionality
Initialization Functionality

The following processing must be performed when the init() method of the invoker servlet is called:

  • Ensure that the container has called setWrapper(). If not, throw a permanent UnavailableException.
  • Look up and cache the Context that corresponds to our Wrapper. This is the component with which new servlet definitions and mappings will be registered.
Per-Request Functionality

On each request, the following processing shall be performed:

  1. Calculate the {ServletPath} for this request, either from request attribute javax.servlet.include.servlet_path or by calling request.getServletPath().
  2. Calculate the {PathInfo} for this request, either from request attribute javax.servlet.include.path_info or by calling request.getPathInfo(). If the calculated {PathInfo} is null, return HTTP status 400 (bad request).
  3. Parse the calculated {PathInfo} value as follows:
    1. Ignore the leading slash character.
    2. Accumulate characters up to the next '/' (if any) as the {ServletSelector}.
    3. If a '/' was encountered, accumulate all characters from that slash (inclusive) to the end of the string as {PathRemainder}. If no slash was encountered, set {PathRemainder} to a zero-length string.
  4. Determine whether {ServletSelector} is the name of an existing servlet definition, and process it as follows:
    1. Ask our associated Context to find and return a child Wrapper named {ServletSelector}.
    2. If there is no such child, skip to the next major step.
    3. Register a new servlet mapping for this Wrapper, using a URL pattern calculated as follows: {ServletPath} + "/" + {ServletSelector} + "/*"
    4. Create a request dispatcher using a path calculated as follows: {ServletPath} + "/" + {ServletSelector} + {PathRemainder}
    5. Forward this request to the created request dispatcher, and exit from this request.
  5. Assume that {ServletSelector} is the fully qualified name of a Java class that implements javax.servlet.Servlet and process it as follows:
    1. Synthesize a new {ServletName} for the servlet definition that will be created.
    2. If there is already a child Wrapper associated with this name, return HTTP status 500 (internal server error), because a mapping should have already been created for this servlet.
    3. Attempt to load a class named {ServletSelector} from the web application class loader (i.e. the context class loader for our current thread). If this fails, return HTTP status 404 (not found).
    4. Instantiate an instance of this class. If an error occurs, return HTTP status 404 (not found).
    5. If this class does not implement the javax.servlet.Servlet interface, return HTTP status 404 (not found).
    6. Create and register a new Wrapper child with our Context, under name {ServletName}.
    7. Register a new servlet mapping for this Wrapper, using a URL pattern calculated as follows: {ServletPath} + "/" + {ServletSelector} + "/*"
    8. Create a request dispatcher using a path calculated as follows: {ServletPath} + "/" + {ServletSelector} + {PathRemainder}
    9. Forward this request to the created request dispatcher, and exit from this request.
Finalization Functionality

No specific processing is required when the destroy() method is called:

Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of the invoker servlet:

  • It is possible to access an existing servlet definition by name through the invoker. The existing servlet definition can include either a <servlet-class> or <jsp-file> subelement.
  • When an existing servlet definition is accessed by name, the request will be ultimately processed by the same servlet instance that would have processed it had a mapping to that servlet definition been used on the request directly.
  • It is possible to access an anonymous servlet by class name through the invoker.
  • When an anonymous servlet is accessed, the servlet instance is processed according to the lifecycle requirements of the Servlet Specification.
  • When an anonymous servlet is accessed, the servlet instance receives a ServletConfig instance with no servlet initialization parameters.
  • It is possible to utilize the invoker servlet via a direct request.
  • It is possible to utilize the invoker servlet via a call to RequestDispatcher.forward(), or the corresponding <jsp:forward> tag in a JSP page.
  • It is possible to utilize the invoker servlet via a call to RequestDispatcher.include(), or the corresponding <jsp:include> tag in a JSP page.
  • It is possible to use any HTTP method (including GET and POST) that is supported by the Servlet class that is ultimately executed.
  • The invoker servlet should never be asked to process a second or subsequent request for the same {ServletSelector} (because it will have registered an appropriate servlet mapping.


Catalina Functional Specifications - JDBCRealm

Catalina Functional Specifications

Catalina Functional Specifications

JDBCRealm
Overview
Introduction

The purpose of the JDBCRealm implementation is to provide a mechanism by which Tomcat 5 can acquire information needed to authenticate web application users, and define their security roles, from a relational database accessed via JDBC APIs. For integration with Catalina, the resulting class(es) must implement the org.apache.catalina.Realm interface.

This specification reflects a combination of functionality that is already present in the org.apache.catalina.realm.JDBCRealm class, as well as requirements for enhancements that have been discussed. Where appropriate, requirements statements are marked [Current] and [Requested] to distinguish them.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

External Specifications

The implementation of this functionality depends on the following external specifications:

  • Java Database Connectivity (version 2.0 or later)
  • Java Database Connectivity Optional Package (version 2.0 or later)
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Be realized in one or more implementation classes.
  • Implement the org.apache.catalina.Realm interface. [Current]
  • Implement the org.apache.catalina.Lifecycle interface. [Current]
  • Subclass the org.apache.catalina.realm.RealmBase base class.
  • Live in the org.apache.catalina.realm package. [Current]
  • Support a configurable debugging detail level. [Current]
  • Log debugging and operational messages (suitably internationalized) via the getContainer().log() method. [Current]
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for JDBCRealm to operate correctly:

  • The desire to utilize JDBCRealm must be registered in $CATALINA_HOME/conf/server.xml, in a <Realm> element that is nested inside a corresponding <Engine>, <Host>, or <Context> element.
Container Dependencies

Correct operation of JDBCRealm depends on the following specific features of the surrounding container:

  • Interactions with JDBCRealm will be initiated by the appropriate Authenticator implementation, based on the login method that is selected.
  • JDBCRealm must have the JDBC standard API classes available to it. For a JDK 1.2 or later container, these APIs are included in the standard platform.
  • When connection pooling is implemented, JDBCRealm must have the JDBC Optional Package (version 2.0 or later) APIs available to it. This library is available as a separate download (and will be included in Tomcat binary distributions).
Functionality
Overview of Operation

The main purpose of JDBCRealm is to allow Catalina to authenticate users, and look up the corresponding security roles, from the information found in a relational database accessed via JDBC APIs. For maximum flexibility, the details of how this is done (for example, the names of the required tables and columns) should be configurable.

Each time that Catalina needs to authenticate a user, it will call the authenticate() method of this Realm implementation, passing the username and password that were specified by the user. If we find the user in the database (and match on the password), we accumulate all of the security roles that are defined for this user, and create a new GenericPrincipal object to be returned. If the user is not authenticated, we return null instead. The GenericUser object caches the set of security roles that were owned by this user at the time of authentication, so that calls to isUserInRole() can be answered without going back to the database every time.

Detailed Functional Requirements

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • Configuration parameters defining the JDBC driver to use, the database connection URL to be accessed, and the username/password to use for logging in. [Current]
  • Configuration parameters describing the connection pool to be created to support simultaneous authentications. [Requested]
  • Name of the tables to be searched for users and roles. [Current]
  • Name of the columns to be used for usernames, passwords, and role names. [Current]

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • Establish a connection to the configured database, using the configured username and password. [Current]
  • Configure and establish a connection pool of connections to the database. [Requested]

The following processing must be performed when the stop() method is called:

  • Close any opened connections to the database.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Acquire the one and only connection [Current] or acquire a connection from the connection pool [Requested].
  • Select the one and only row from the user's table for this user, and retrieve the corresponding password column. If zero rows (or more than one row) are found, return null.
  • Authenticate the user by comparing the (possibly encrypted) password value that was received against the password presented by the user. If there is no match, return null.
  • Acquire a List of the security roles assigned to the authenticated user by selecting from the roles table.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal, passing as constructor arguments: this realm instance, the authenticated username, and a List of the security roles associated with this user.
  • WARNING - Do not attempt to cache and reuse previous GenericPrincipal objects for a particular user, because the information in the directory server might have changed since the last time this user was authenticated.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of JDBCRealm:


Catalina Functional Specifications - JNDIRealm

Catalina Functional Specifications

Catalina Functional Specifications

JNDIRealm
Overview
Introduction

The purpose of the JNDIRealm implementation is to provide a mechanism by which Tomcat 5 can acquire information needed to authenticate web application users, and define their security roles, from a directory server or other service accessed via JNDI APIs. For integration with Catalina, this class must implement the org.apache.catalina.Realm interface.

This specification reflects a combination of functionality that is already present in the org.apache.catalina.realm.JNDIRealm class, as well as requirements for enhancements that have been discussed. Where appropriate, requirements statements are marked [Current] and [Requested] to distinguish them.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

The code in the current version of JNDIRealm, and the ideas expressed in this functional specification, are the results of contributions from many individuals, including (alphabetically):

  • Holman, John <j.g.holman@qmw.ac.uk>
  • Lockhart, Ellen <elockhart@home.com>
  • McClanahan, Craig <craigmcc@apache.org>
External Specifications

The implementation of this functionality depends on the following external specifications:

  • Java Naming and Directory Interface (version 1.2.1 or later)
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Be realized in one or more implementation classes.
  • Implement the org.apache.catalina.Realm interface. [Current]
  • Implement the org.apache.catalina.Lifecycle interface. [Current]
  • Subclass the org.apache.catalina.realm.RealmBase base class.
  • Live in the org.apache.catalina.realm package. [Current]
  • Support a configurable debugging detail level. [Current]
  • Log debugging and operational messages (suitably internationalized) via the getContainer().log() method. [Current]
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for JNDIRealm to operate correctly:

  • The desire to utilize JNDIRealm must be registered in $CATALINA_HOME/conf/server.xml, in a <Realm> element that is nested inside a corresponding <Engine>, <Host>, or <Context> element.
  • If the Administrator Login operational mode is selected, the configured administrator username and password must be configured in the corresponding directory server.
  • If the Username Login operational mode is selected, the corresponding directory server must be configured to accept logins with the username and password that will be passed to JNDIRealm by the appropriate Authenticator.
Container Dependencies

Correct operation of JNDIRealm depends on the following specific features of the surrounding container:

  • Interactions with JNDIRealm will be initiated by the appropriate Authenticator implementation, based on the login method that is selected.
  • JNDIRealm must have the JNDI API classes available to it. For a JDK 1.2 container, that means jndi.jar and the appropriate implementation (such as ldap.jar) must be placed in the server/lib directory.
Functionality
Operational Modes

The completed JNDIRealm must support two major operational modes in order to support all of the required use cases. For the purposes of this document, the modes are called administrator login and Username Login. They are described further in the following paragraphs.

For Administrator Login mode, JNDIRealm will be configured to establish one or more connections (using a connection pool) to an appropriate directory server, using JNDI APIs, under a "system administrator" username and password. This is similar to the approach normally used to configure JDBCRealm to access authentication and access control information in a database. It is assumed that the system administrator username and password that are configured provide sufficient privileges within the directory server to read (but not modify) the username, password, and assigned roles for each valid user of the web application associated with this Realm. The password can be stored in cleartext, or in one of the digested modes supported by the org.apache.catalina.realm.RealmBase base class.

For Username Login mode, JNDIRealm does not normally remain connected to the directory server. Instead, whenever a user is to be authenticated, a connection to the directory server (using the username and password received from the authenticator) is attempted. If this connection is successful, the user is assumed to be successfully authenticated. This connection is then utilized to read the corresponding security roles associated with this user, and the connection is then broken.

NOTE - Username Login mode cannot be used if you have selected login method DIGEST in your web application deployment descriptor (web.xml) file. This restriction exists because the cleartext password is never available to the container, so it is not possible to bind to the directory server using the user's username and password.

Because these operational modes work so differently, the functionality for each mode will be described separately. Whether or not both modes are actually supported by a single class (versus a class per mode) is an implementation detail left to the designer.

NOTE - The current implementation only implements part of the Administrator Lookup mode requirements. It does not support the Username Lookup mode at all, at this point.

Administrator Login Mode Functionality

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • connectionURL - URL of the directory server we will be contacting.
  • contextFactory - Fully qualified class name of the JNDI context factory used to retrieve our InitialContext. [com.sun.jndi.ldap.LdapCtxFactory]
  • Additional configuration properties required to establish the appropriate connection. [Requested]
  • Connection pool configuration properties. [Requested]
  • Configuration properties defining how a particular user is authenticated. The following capabilities should be supported:
    • Substitute the specified username into a string. [Requested]
    • Retrieve the distinguished name (DN) of an authorized user via an LDAP search string with a replacement placeholder for the username, and comparison of the password to a configurable attribute retrieved from the search result. [Current]
  • Configuration properties defining how the roles associated with a particular authenticated user can be retrieved. The following approaches should be supported:
    • Retrieve a specified attribute (possibly multi-valued) from an LDAP search expression, with a replacement placeholder for the DN of the user. [Current]
    • Retrieve a set of role names that are defined implicitly (by selecting principals that match a search pattern) rather than explicitly (by finding a particular attribute value). [Requested]

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • Establish a connection to the configured directory server, using the configured system administrator username and password. [Current]
  • Configure and establish a connection pool of connections to the directory server. [Requested]

The following processing must be performed when the stop() method is called:

  • Close any opened connections to the directory server.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Acquire the one and only connection [Current] or acquire a connection from the connection pool [Requested].
  • Authenticate the user by retrieving the user's Distinguished Name, based on the specified username and password.
  • If the user was not authenticated, release the allocated connection and return null.
  • Acquire a List of the security roles assigned to the authenticated user.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal, passing as constructor arguments: this realm instance, the authenticated username, and a List of the security roles associated with this user.
  • WARNING - Do not attempt to cache and reuse previous GenericPrincipal objects for a particular user, because the information in the directory server might have changed since the last time this user was authenticated.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Username Login Mode Functionality

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • connectionURL - URL of the directory server we will be contacting.
  • contextFactory - Fully qualified class name of the JNDI context factory used to retrieve our InitialContext. [com.sun.jndi.ldap.LdapCtxFactory]
  • Additional configuration properties required to establish the appropriate connection. [Requested]
  • Connection pool configuration properties. [Requested]
  • Configuration properties defining if and how a user might be looked up before binding to the directory server. The following approaches should be supported:
    • No previous lookup is required - username specified by the user is the same as that used to authenticate to the directory server.
    • Substitute the specified username into a string.
    • Search the directory server based on configured criteria to retrieve the distinguished name of the user, then attempt to bind with that distinguished name.
  • Configuration properties defining how the roles associated with a particular authenticated user can be retrieved. The following approaches should be supported:
    • Retrieve a specified attribute (possibly multi-valued) from an LDAP search expression, with a replacement placeholder for the DN of the user. [Current]

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • None required.

The following processing must be performed when the stop() method is called:

  • None required.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Attempt to bind to the directory server, using the username and password provided by the user.
  • If the user was not authenticated, release the allocated connection and return null.
  • Acquire a List of the security roles assigned to the authenticated user.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal, passing as constructor arguments: this realm instance, the authenticated username, and a List of the security roles associated with this user.
  • WARNING - Do not attempt to cache and reuse previous GenericPrincipal objects for a particular user, because the information in the directory server might have changed since the last time this user was authenticated.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of JNDIRealm:


Catalina Functional Specifications - MemoryRealm

Catalina Functional Specifications

Catalina Functional Specifications

MemoryRealm
Overview
Introduction

The purpose of the MemoryRealm implementation is to provide a mechanism by which Tomcat 5 can acquire information needed to authenticate web application users, and define their security roles, from a simple text-based configuration file in XML format. This is intended to simplify the initial installation and operation of Tomcat 5, without the complexity of configuring a database or directory server based Realm. It is not intended for production use.

This specification reflects a combination of functionality that is already present in the org.apache.catalina.realm.MemoryRealm class, as well as requirements for enhancements that have been discussed. Where appropriate, requirements statements are marked [Current] and [Requested] to distinguish them.

The current status of this functional specification is PROPOSED. It has not yet been discussed and agreed to on the TOMCAT-DEV mailing list.

External Specifications

The implementation of this functionality depends on the following external specifications:

  • None
Implementation Requirements

The implementation of this functionality shall conform to the following requirements:

  • Be realized in one or more implementation classes.
  • Implement the org.apache.catalina.Realm interface. [Current]
  • Implement the org.apache.catalina.Lifecycle interface. [Current]
  • Subclass the org.apache.catalina.realm.RealmBase base class.
  • Live in the org.apache.catalina.realm package. [Current]
  • Support a configurable debugging detail level. [Current]
  • Log debugging and operational messages (suitably internationalized) via the getContainer().log() method. [Current]
Dependencies
Environmental Dependencies

The following environmental dependencies must be met in order for MemoryRealm to operate correctly:

  • The desire to utilize MemoryRealm must be registered in $CATALINA_HOME/conf/server.xml, in a <Realm> element that is nested inside a corresponding <Engine>, <Host>, or <Context> element. (This is already included in the default server.xml file.)
Container Dependencies

Correct operation of MemoryRealm depends on the following specific features of the surrounding container:

  • Interactions with MemoryRealm will be initiated by the appropriate Authenticator implementation, based on the login method that is selected.
  • MemoryRealm must have an XML parser compatible with the JAXP/1.1 APIs available to it. This is normally accomplished by placing the corresponding JAR files in directory $CATALINA_HOME/server/lib (to make them visible only to internal Catalina classes) or in directory $CATALINA_HOME/common/lib (to make them visible to Catalina internal classes and installed web applications).
Functionality
Overview of Operation

The main purpose of MemoryRealm is to allow Catalina to authenticate users, and look up the corresponding security roles, from the information found in an XML-format configuration file. The format of this file is described below. When a MemoryRealm instance is started, it will read the contents of this XML file and create an "in memory database" of all the valid users and their associated security roles.

Each time that Catalina needs to authenticate a user, it will call the authenticate() method of this Realm implementation, passing the username and password that were specified by the user. If we find the user in the database (and match on the password), we accumulate all of the security roles that are defined for this user, and create a new GenericPrincipal object to be returned. If the user is not authenticated, we return null instead. The GenericUser object caches the set of security roles that were owned by this user at the time of authentication, so that calls to isUserInRole() can be answered without going back to the database every time.

Detailed Functional Requirements

Configurable Properties

The implementation shall support the following properties that can be configured with JavaBeans property setters:

  • Configurable debugging detail level.
  • Configurable file pathname (absolute or relative to $CATALINA_HOME of the XML file containing our defined users. [conf/tomcat-users.xml].

Lifecycle Functionality

The following processing must be performed when the start() method is called:

  • Open and parse the specified XML file.
  • Create an in-memory database representation of the XML file contents.
  • NOTE - There is no requirement to recognize subsequent changes to the contents of the XML file.

The following processing must be performed when the stop() method is called:

  • Release object references to the in-memory database representation.

Method authenticate() Functionality

When authenticate() is called, the following processing is required:

  • Select the one and only "user" instance from the in-memory database, based on matching the specified username. If there is no such instance, return null.
  • Authenticate the user by comparing the (possibly encrypted) password value that was received against the password presented by the user. If there is no match, return null.
  • Construct a new instance of class org.apache.catalina.realm.GenericPrincipal (if not already using this as the internal database representation) that contains the authenticated username and a List of the security roles associated with this user.
  • Return the newly constructed GenericPrincipal.

Method hasRole() Functionality

When hasRole() is called, the following processing is required:

  • The principal that is passed as an argument SHOULD be one that we returned (instanceof class org.apache.catalina.realm.GenericPrincipal, with a realm property that is equal to our instance.
  • If the passed principal meets these criteria, check the specified role against the list returned by getRoles(), and return true if the specified role is included; otherwise, return false.
  • If the passed principal does not meet these criteria, return false.
Testable Assertions

In addition the the assertions implied by the functionality requirements listed above, the following additional assertions shall be tested to validate the behavior of MemoryRealm:


Catalina Functional Specifications - 目录

Catalina Functional Specifications

Catalina Functional Specifications

目录
Catalina Functional Specifications

This documentation area includes functional specifications for many features supported by the Catalina servlet container portion of Tomcat 5. In most cases, these features are not documented in the underlying Servlet or JSP specifications, so a definition of the expected correct behavior is important both to implementors of those features, and to test writers trying to decide what to test.

The functional specifications are divided into the following categories in the menu (to the left):

  • Administrative Apps - Overall requirements for supporting an ability to configure and operate a Tomcat 5 installation through tools, as well as detailed requirements for the tools themselves.
  • Internal Servlets - Requirements for Catalina features that are implemented as internal, container-managed, servlets.
  • Realm Implementations - Requirements for the implementations of the org.apache.catalina.Realm interface (providing access to collections of users, passwords and roles) that are included in the standard Tomcat 5 distribution.

NOTE - In some cases, the contents of these functional specs has been "reverse engineered" from existing implementations. This exercise is stil useful, because it provides an introduction to what Catalina does, without being as concerned with how this is accomplished.

TODO - Obviously, this area has a long ways to go before it is complete. Contributions are welcome!


Catalina Functional Specifications - Tomcat MBean Names

Catalina Functional Specifications

Catalina Functional Specifications

Tomcat MBean Names
Background

We will be using JMX MBeans as the technology for implementing manageability of Tomcat.

One of the key concepts of JMX (and JSR-77) is that each management bean has a unique name in the MBeanServer's registry, and that management applications can utilize these names to retrieve the MBean of interest to them for a particular management operation. This document proposes a naming convention for MBeans that allows easy calculation of the name for a particular MBean. For background information on JMX MBean names, see the Java Management Extensions Instrumentation and Agent Specification, version 1.0, section 6. In particular, we will be discussing the String Representation of ObjectName instances.

Catalina Object Hierarchy

Tomcat's servlet container implementation, called Catalina, can be represented as a hierarchy of objects that contain references to each other. The object hierarchy can be represented as a tree, or (isomorphically) based on the nesting of configuration elements in the conf/server.xml file that is traditionally used to configure Tomcat stand-alone.

The valid component nestings for Catalina are depicted in the following table, with columns that contain the following values:

  • Pattern - Nesting pattern of XML elements (in the conf/server.xml file) used to configure this component.
  • Cardinality - Minimum and maximum number of occurrences of this element at this nesting position, which also corresponds to the minimum and maximum number of Catalina components.
  • Identifier - Name of the JavaBeans property of this component that represents the unique identifier (within the nested hierarchy), if any.
  • MBean ObjectName - The portion of the MBean object name that appears after the domain name. For now, it should be assumed that all of these MBeans appear in the default JMX domain.

In the MBean ObjectName descriptions, several types of symbolic expressions are utilized to define variable text that is replaced by corresponding values:

  • ${GROUP} - One of the standard MBean names of the specified "group" category. For example, the expression ${REALM} represents the values like JDBCRealm and JAASRealm that identify the various MBeans for possible Realm components.
  • ${name} - Replaced by the value of property name from the current component.
  • ${parent.name} - Replaced by the value of property name from a parent of the current component, with the parent's type identified by parent.
  • ${###} - An arbitrary numeric identifier that preserves order but has no other particular meaning. In general, the server will assign numeric values to existing instances with large gaps into which new items can be configured if desired.
模式 | Cardinality | Identifier | MBean ObjectName
<Server> | 1..1 | (none) | type=${SERVER}
Server / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}
Server / Service | 1..n | name(名称) | type=${SERVICE}, name=${name}
Server / Service / Connector | 1..n | address, port | type=${CONNECTOR}, service=${service}, port=${port}, address=${address}
Server / Service / Connector / Factory | 0..1 | (none) | (Only defined explicitly for an SSL connector, but can be treated as part of the connector component)
Server / Service / Connector / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}, service=${service}, port=${connector.port}, address=${connector.address}
Server / Service / Engine | 1..1 | (none) | type=${ENGINE}, service=${service.name}
Server / Service / Engine / Host | 1..n | name(名称) | type=${HOST}, host=${name}, service=${service.name}
Server / Service / Engine / Host / Context | 1..n | 路径 | type=${CONTEXT}, path=${path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / InstanceListener | 0..n | (none) | type=${INSTANCE-LISTENER}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Loader | 0..1 | (none) | type=${LOADER}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Manager | 0..1 | (none) | type=${MANAGER}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Realm | 0..1 | (none) | type=${REALM}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Resources | 0..1 | (none) | type=${RESOURCES}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Valve | 0..n | (none) | type=${VALVE}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / Wrapper 0..n (none)
j2eeType=Servlet,name=${name},
        WebModule=//${host.name}/${context.name},
        J2EEApplication=${context.J2EEApplication},
        J2EEServer=${context.J2EEServer}
Server / Service / Engine / Host / Context / WrapperLifecycle | 0..n | (none) | type=${WRAPPER-LIFECYCLE}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Context / WrapperListener | 0..n | (none) | type=${WRAPPER-LISTENER}, sequence=${###}, path=${context.path}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Realm | 0..1 | (none) | type=${REALM}, host=${host.name}, service=${service.name}
Server / Service / Engine / Host / Valve | 0..n | (none) | type=${VALVE}, sequence=${###}, host=${host.name}, service=${service.name}
Server / Service / Engine / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###} (FIXME - disambiguate from Server / Service / Listener)
Server / Service / Engine / Realm | 0..1 | (none) | type=${REALM}, service=${service.name}
Server / Service / Engine / Valve | 0..n | (none) | type=${VALVE}, sequence=${###}, service=${service.name}
Server / Service / Listener | 0..n | (none) | type=${LISTENER}, sequence=${###} (FIXME - disambiguate from Server / Service / Engine / Listener)
MBean Groups and Names

The following MBean names shall be defined in the resource file /org/apache/catalina/mbeans/mbeans-descriptors.xml (and therefore available for use within the Administration/Configuration web application for Tomcat):

MBean Name | Group Name | Catalina Interface | Implementation Class
AccessLogValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.AccessLogValve
BasicAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.BasicAuthenticator
CertificatesValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.CertificatesValve
ContextConfig | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.startup.ContextConfig
ContextEnvironment | 资源 | org.apache.catalina.deploy.ContextEnvironment | org.apache.catalina.deploy.ContextEnvironment
ContextResource | 资源 | org.apache.catalina.deploy.ContextResource | org.apache.catalina.deploy.ContextResource
ContextResourceLink | 资源 | org.apache.catalina.deploy.ContextResourceLink | org.apache.catalina.deploy.ContextResourceLink
CoyoteConnector | connector | org.apache.catalina.Connector | org.apache.coyote.tomcat4.CoyoteConnector
DigestAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.DigestAuthenticator
EngineConfig | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.startup.EngineConfig
ErrorReportValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.ErrorReportValve
ErrorDispatcherValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.ErrorDispatcherValve
FormAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.FormAuthenticator
组 | 组 | org.apache.catalina.Group | org.apache.catalina.Group
HostConfig | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.startup.HostConfig
HttpConnector10 | connector | org.apache.catalina.Connector | org.apache.catalina.connector.http10.HttpConnector
HttpConnector11 | connector | org.apache.catalina.Connector | org.apache.catalina.connector.http.HttpConnector
JAASRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.JAASRealm
JDBCRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.JDBCRealm
JDBCUserDatabase | USERDATABASE | org.apache.catalina.users.JDBCUserDatabase | org.apache.catalina.users.JDBCUserDatabase
JNDIRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.JNDIRealm
MBeanFactory | org.apache.catalina.mbeans.MBeanFactory
MemoryRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.MemoryRealm
MemoryUserDatabase | USERDATABASE | org.apache.catalina.users.MemoryUserDatabase | org.apache.catalina.users.MemoryUserDatabase
NamingContextListener | 监听器 | org.apache.catalina.LifecycleListener | org.apache.catalina.core.NamingContextListener
NamingResources | 资源 | org.apache.catalina.deploy.NamingResources | org.apache.catalina.deploy.NamingResources
NonLoginAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.NonLoginAuthenticator
PersistentManager | 管理者 | org.apache.catalina.Manager | org.apache.catalina.session.PersistentManager
RemoteAddrValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.RemoteAddrValve
RemoteHostValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.RemoteHostValve
RequestDumperValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.RequestDumperValve
角色 | 角色 | org.apache.catalina.Role | org.apache.catalina.Role
SingleSignOn | VALVE | org.apache.catalina.Valve | org.apache.catalina.valves.SingleSignOn
SSLAuthenticator | VALVE | org.apache.catalina.Valve | org.apache.catalina.authenticator.SSLAuthenticator
StandardContext | <Context> | org.apache.catalina.Context | org.apache.catalina.core.StandardContext
StandardContextValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardContextValve
StandardEngine | <Engine> | org.apache.catalina.Engine | org.apache.catalina.core.StandardEngine
StandardEngineValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardEngineValve
StandardHost | <Host> | org.apache.catalina.Host | org.apache.catalina.core.StandardHost
StandardHostValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardHostValve
StandardManager | 管理者 | org.apache.catalina.Manager | org.apache.catalina.session.StandardManager
StandardServer | <Server> | org.apache.catalina.Server | org.apache.catalina.core.StandardServer
StandardService | <Service> | org.apache.catalina.Service | org.apache.catalina.core.StandardService
StandardWrapper | 包? | org.apache.catalina.Wrapper | org.apache.catalina.core.StandardWrapper
StandardWrapperValve | VALVE | org.apache.catalina.Valve | org.apache.catalina.core.StandardWrapperValve
用户 | 用户 | org.apache.catalina.User | org.apache.catalina.User
UserDatabaseRealm | <Realm> | org.apache.catalina.Realm | org.apache.catalina.realm.UserDatabaseRealm
WebappLoader | 载入器 | org.apache.catalina.Loader | org.apache.catalina.loader.WebappLoader
JSR-77 Cross Reference

The managed objects in the JSR-77 object hierarchy correspond to the specified MBean names or groups as follows:

JSR-77 Managed Object | MBean Name or Group | 评论，建议
J2EEServer | <Service>
Node | <Service> | Tomcat supports a single node only.
port(端口) | connector
Servlet | 包?
WebModule | <Context>
JSR-88 Cross Reference

The deployment objects in the JSR-88 API object hierarchy correspond to the specified MBean names or groups as follows:

JSR-88 API Object | MBean Name or Group | 评论，建议
DeployableObject | <Context> | Context deployment info plus the corresponding WAR file
目标 | <Host>


Apache Tomcat Configuration Reference - The AJP Connector

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The Context Container

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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:

Attribute Description
description

Optional, human-readable description of this context initialization parameter.

name

The name of the context initialization parameter to be created.

override

Set this to false if you do not want a <context-param> for the same parameter name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

value

The parameter value that will be presented to the application when requested by calling ServletContext.getInitParameter().

Environment Entries

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

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

This is equivalent to the inclusion of the following element in the web application deployment descriptor (/WEB-INF/web.xml):

<env-entry>
  <env-entry-name>maxExemptions</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:

Attribute Description
description

Optional, human-readable description of this environment entry.

name

The name of the environment entry to be created, relative to the java:comp/env context.

override

Set this to false if you do not want an <env-entry> for the same environment entry name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

type

The fully qualified Java class name expected by the web application for this environment entry. Must be 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:

Attribute Description
auth

Specify whether the web Application code signs on to the corresponding resource manager programatically, or whether the Container will sign on to the resource manager on behalf of the application. The value of this attribute must be Application or Container. This attribute is required if the web application will use a <resource-ref> element in the web application deployment descriptor, but is optional if the application uses a <resource-env-ref> instead.

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:

Attribute Description
global

The name of the linked global resource in the global JNDI context.

name

The name of the resource link to be created, relative to the java:comp/env context.

type

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

Transaction

You can declare the characteristics of the UserTransaction to be returned for JNDI lookup for java:comp/UserTransaction. You MUST define an object factory class to instantiate this object as well as the needed resource parameters as attributes of the Transaction element, and the properties used to configure that object factory.

The valid attributes for the <Transaction> element are as follows:

Attribute Description
factory

The class name for the JNDI object factory.


Apache Tomcat Configuration Reference - The Engine Container

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The GlobalNamingResources Component

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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:

Attribute Description
description

Optional, human-readable description of this environment entry.

name

The name of the environment entry to be created, relative to the java:comp/env context.

override

Set this to false if you do not want an <env-entry> for the same environment entry name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

type

The fully qualified Java class name expected by the web application for this environment entry. Must be 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:

Attribute Description
auth

Specify whether the web Application code signs on to the corresponding resource manager programatically, or whether the Container will sign on to the resource manager on behalf of the application. The value of this attribute must be Application or Container. This attribute is required if the web application will use a <resource-ref> element in the web application deployment descriptor, but is optional if the application uses a <resource-env-ref> instead.

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:

Attribute Description
factory

The class name for the JNDI object factory.


Apache Tomcat Configuration Reference - The Host Container

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The HTTP Connector

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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:

Attribute Description
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.


Apache Tomcat Configuration Reference - 概 述

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

概 述

 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)。
  • 嵌套的组件 - 列举哪些嵌套的组件可以被合法地嵌套在这个元素里边。
  • 特别性能 - 描述了被这个界面的标准实现支持的多种特别性能(每个元素类型所特定的)的配置。


Apache Tomcat Configuration Reference - The Loader Component

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The Manager Component

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

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

Attribute Description
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.

Attribute Description
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:

Attribute Description
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:

Attribute Description
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).


Apache Tomcat Configuration Reference - The Realm Component

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

Attribute Description
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:

Attribute Description
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

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

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:

Attribute Description
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

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

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:

Attribute Description
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:

Attribute Description
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:

Attribute Description
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:

Attribute Description
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.


Apache Tomcat Configuration Reference - The Resources Component

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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的所有实现支持下列属性：

Attribute Description
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.


Apache Tomcat Configuration Reference - 服务器组件

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

服务器组件

 Printer Friendly Version
print-friendly
version
Introduction

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

Attributes
Common Attributes

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

Attribute Description
className

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

port

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

shutdown

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

Standard Implementation

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

Attribute Description
Nested Components

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

  • Service - 一个或多个service元素。
  • GlobalNamingResources - 为这个server配置JNDI全球性资源。
Special Features

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


Apache Tomcat Configuration Reference - 服务组件

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

服务组件

 Printer Friendly Version
print-friendly
version
Introduction

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

Attributes
Common Attributes

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

Attribute Description
className

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

name

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

Standard Implementation

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

Attribute Description
Nested Components

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

Special Features

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


Apache Tomcat Configuration Reference - The Valve Component

The Apache Tomcat Servlet/JSP Container

Links

  • Docs Home
  • Config Ref. Home

Top Level Elements

  • Server
  • Service

Connectors

  • HTTP
  • AJP

Containers

  • Context
  • Engine
  • Host

Nested Components

  • Global Resources
  • Loader
  • Manager
  • Realm
  • Resources
  • Valve

Apache Tomcat Configuration Reference

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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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:

Attribute Description
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.


Apache Tomcat Configuration Reference - The AJP Connector

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The AJP Connector
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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The Context Container

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Context Container
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的所有实现支持下列属性：

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

Attribute Description
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:

Attribute Description
description

Optional, human-readable description of this context initialization parameter.

name

The name of the context initialization parameter to be created.

override

Set this to false if you do not want a <context-param> for the same parameter name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

value

The parameter value that will be presented to the application when requested by calling ServletContext.getInitParameter().

Environment Entries

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

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

This is equivalent to the inclusion of the following element in the web application deployment descriptor (/WEB-INF/web.xml):

<env-entry>
  <env-entry-name>maxExemptions</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:

Attribute Description
description

Optional, human-readable description of this environment entry.

name

The name of the environment entry to be created, relative to the java:comp/env context.

override

Set this to false if you do not want an <env-entry> for the same environment entry name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

type

The fully qualified Java class name expected by the web application for this environment entry. Must be 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:

Attribute Description
auth

Specify whether the web Application code signs on to the corresponding resource manager programatically, or whether the Container will sign on to the resource manager on behalf of the application. The value of this attribute must be Application or Container. This attribute is required if the web application will use a <resource-ref> element in the web application deployment descriptor, but is optional if the application uses a <resource-env-ref> instead.

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:

Attribute Description
global

The name of the linked global resource in the global JNDI context.

name

The name of the resource link to be created, relative to the java:comp/env context.

type

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

Transaction

You can declare the characteristics of the UserTransaction to be returned for JNDI lookup for java:comp/UserTransaction. You MUST define an object factory class to instantiate this object as well as the needed resource parameters as attributes of the Transaction element, and the properties used to configure that object factory.

The valid attributes for the <Transaction> element are as follows:

Attribute Description
factory

The class name for the JNDI object factory.


Apache Tomcat Configuration Reference - The Engine Container

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Engine Container
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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The GlobalNamingResources Component

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The GlobalNamingResources Component
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:

Attribute Description
description

Optional, human-readable description of this environment entry.

name

The name of the environment entry to be created, relative to the java:comp/env context.

override

Set this to false if you do not want an <env-entry> for the same environment entry name, found in the web application deployment descriptor, to override the value specified here. By default, overrides are allowed.

type

The fully qualified Java class name expected by the web application for this environment entry. Must be 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:

Attribute Description
auth

Specify whether the web Application code signs on to the corresponding resource manager programatically, or whether the Container will sign on to the resource manager on behalf of the application. The value of this attribute must be Application or Container. This attribute is required if the web application will use a <resource-ref> element in the web application deployment descriptor, but is optional if the application uses a <resource-env-ref> instead.

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:

Attribute Description
factory

The class name for the JNDI object factory.


Apache Tomcat Configuration Reference - The Host Container

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Host Container
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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The HTTP Connector

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The HTTP Connector
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的所有实现支持下列属性：

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

Attribute Description
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:

Attribute Description
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.


Apache Tomcat Configuration Reference - 概 述

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

概 述
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)。
  • 嵌套的组件 - 列举哪些嵌套的组件可以被合法地嵌套在这个元素里边。
  • 特别性能 - 描述了被这个界面的标准实现支持的多种特别性能(每个元素类型所特定的)的配置。


Apache Tomcat Configuration Reference - The Loader Component

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Loader Component
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的所有实现支持下列属性：

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

Attribute Description
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.


Apache Tomcat Configuration Reference - The Manager Component

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Manager Component
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的所有实现支持下列属性：

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

Attribute Description
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.

Attribute Description
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:

Attribute Description
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:

Attribute Description
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).


Apache Tomcat Configuration Reference - The Realm Component

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Realm Component
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的所有实现支持下列属性：

Attribute Description
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:

Attribute Description
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

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

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:

Attribute Description
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

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

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:

Attribute Description
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:

Attribute Description
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:

Attribute Description
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:

Attribute Description
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.


Apache Tomcat Configuration Reference - The Resources Component

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Resources Component
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的所有实现支持下列属性：

Attribute Description
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.


Apache Tomcat Configuration Reference - 服务器组件

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

服务器组件
Introduction

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

Attributes
Common Attributes

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

Attribute Description
className

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

port

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

shutdown

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

Standard Implementation

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

Attribute Description
Nested Components

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

  • Service - 一个或多个service元素。
  • GlobalNamingResources - 为这个server配置JNDI全球性资源。
Special Features

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


Apache Tomcat Configuration Reference - 服务组件

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

服务组件
Introduction

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

Attributes
Common Attributes

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

Attribute Description
className

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

name

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

Standard Implementation

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

Attribute Description
Nested Components

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

Special Features

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


Apache Tomcat Configuration Reference - The Valve Component

The Apache Tomcat Servlet/JSP Container

Apache Tomcat Configuration Reference

The Valve Component
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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 支持下列配置属性：

Attribute Description
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:

Attribute Description
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.


Apache Tomcat 5.5 Servlet/JSP 容器 - Apache可移植运行库 与 Tomcat

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Apache可移植运行库 与 Tomcat
简介

Tomcat can use the Apache可移植运行库 to provide superior scalability, 性能, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).

These features allows making Tomcat a general purpose webserver, will enable much better integration with other native web technologies, and overall make Java much more viable as a full fledged webserver platform rather than simply a backend focused technology.

安装

安装好以下三个主要的本地组件方可支持 APR :

  • APR库
  • 供Tomcat使用APR的JNI包装器 (libtcnative)
  • OpenSSL库

Windows

Windows 二进制 are provided for tcnative-1, which is a statically compiled .dll which includes OpenSSL and APR. It can be downloaded from here as 32bit or AMD x86-64 binaries. In security conscious production environments, it is recommended to use separate shared dlls for OpenSSL, APR, and libtcnative-1, and update them as needed according to security bulletins. Windows OpenSSL binaries are linked from the Official OpenSSL website (see related/binaries).

Linux

Most Linux distributions will ship packages for APR and OpenSSL. The JNI wrapper (libtcnative) will then have to be compiled. It depends on APR, OpenSSL, and the Java headers.

Requirements:

  • APR 1.2+ development headers (libapr1-dev package)
  • OpenSSL 0.9.7+ development headers (libssl-dev package)
  • JNI headers from Java compatible JDK 1.4+
  • GNU development environment (gcc, make)

The wrapper library sources are located in the Tomcat binary bundle, in the bin/tomcat-native.tar.gz archive. Once the build environment is installed and the source archive is extracted, the wrapper library can be compiled using (from the folder containing the configure script):

./configure && make && make install

APR 组件

一旦这些组件正确的安装并且可供java调用 (如果加载失败, 库文件路径将被显示在控制台), Tomcat 连接器将自动使用 APR 功能. APR连接器的配置与普通连接器的配置基本相同， 但是提供了一些扩展的属性供APR组件使用。 注意:默认值已经适用于大多数的应用场景， 额外的调整不是必须的。

当APR可用之后, 以下特性将在Tomcat中可用:

  • Secure session ID generation by default on all platforms (platforms other than Linux required random number generation using a configured entropy)
  • Tomcat进程的内存占用率和CPU占用率将被 status servlet 显示。

APR连接器配置
HTTP

当APR可用之后, HTTP 连接器 will use sendfile for hadling large static files (all such files will be sent ansychronously using high performance kernel level calls), and will use a socket poller for keepalive, increasing scalability of the server.

The following attributes are supported in the HTTP APR connector in addition to the ones supported in the regular HTTP connector:

Attribute Description
firstReadTimeout

The first read of a request will be made using the specified timeout. If no data is available after the specified time, the socket will be placed in the poller. The value of this attribute is in ms. Setting this value to 0 or -1 will increase scalability by always using a poller to handle keepalive, but will have a minor impact on latency (see the related pollTime attribute). The difference is that with 0, the first read of a request will be made using a short timeout, while with -1, the first read will be made using the regular socket timeout that is configured on the connector. Setting this to -2 will cause the connector to not use the poller for keepalive in most situations, emulating the behavior of the java.io HTTP connector. The default value is -1. Note: on Windows, the actual value of firstReadTimeout will be 500 + the specified value, if the specified value is strictly positive.

pollTime

Duration of a poll call. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (5ms).

pollerSize

Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keepalive connections.

useSendfile

Use kernel level sendfile for certain static files. The default value is true.

sendfileSize

Amount of sockets that the poller responsible for sending static files asynchronously can hold at a given time. Extra connections will be closed right away without any data being sent (resulting in a zero length file on the client side). Note that in most cases, sendfile is a call that will return right away (being taken care of "synchonously" by the kernel), and the sendfile poller will not be used, so the amount of static files which can be sent concurrently is much larger than the specified amount. The default value is 1024.

HTTPS

When APR is enabled, the HTTPS connector will use a socket poller for keepalive, increasing scalability of the server. It also uses OpenSSL, which may be more optimized than JSSE depending on the processor being used, and can be complemented with many commercial accelerator components. Unlike the HTTP connector, the HTTPS connector cannot use sendfile to optimize static file processing.

The HTTPS APR connector has the same basic attributes than the HTTP APR connector, but adds OpenSSL specific ones. For the full details on using OpenSSL, please refer to OpenSSL documentations and the many books available for it (见 OpenSSL官方站点). The SSL specific attributes for the connector are:

Attribute Description
SSLEngine

将使用的 SSL引擎名字. off: 不使用 SSL, on: 使用 SSL 但没有指定的引擎. 默认值是 off.

SSLProtocol

Protocol which may be used for communicating with clients. 默认是 "all", 支持的 其它可用值有 "SSLv2", "SSLv3", "TLSv1", and "SSLv2+SSLv3".

SSLCipherSuite

Ciphers which may be used for communicating with clients. The default is "ALL", with other acceptable values being a list of ciphers, with ":" used as the delimiter (see OpenSSL documentation for the list of ciphers supported).

SSLCertificateFile

包含有服务器证书的文件路径。 格式是 PEM-encoded.

SSLCertificateKeyFile

Name of the file that contains the server private key. The format is PEM-encoded. The default value is the value of "SSLCertificateFile" and in this case both certificate and private key have to be in this file (NOT RECOMMENDED).

SSLPassword

Pass phrase for the encrypted private key. If "SSLPassword" is not provided, the callback fonction should prompt for the pass phrase.

SSLVerifyClient

Ask client for certificate. 默认为 "none", meaning the client will not have the opportunity to submit a certificate. Other acceptable values include "optional", "require" and "optionalNoCA".

SSLVerifyDepth

Maximum verification depth for client certificates. 默认为 "10".

SSLCACertificateFile

见 mod_ssl相关文档.

SSLCACertificatePath

见 mod_ssl相关文档.

SSLCertificateChainFile

见 mod_ssl相关文档.

SSLCARevocationFile

见 mod_ssl相关文档.

SSLCARevocationPath

见 mod_ssl相关文档.

下面是SSL连接器定义的一个范例:

    <Connector port="443" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" scheme="https" secure="true"
               SSLEngine="on"
               SSLCertificateFile="${catalina.base}/conf/localhost.crt"
               SSLCertificateKeyFile="${catalina.base}/conf/localhost.key" />

AJP

When APR is enabled, the AJP connector will use a socket poller for keepalive, increasing scalability of the server. As AJP is designed around a pool of persistent (or almost persistent) connections, this will reduce significantly the amount of processing threads needed by Tomcat. Unlike the HTTP connector, the AJP connector cannot use sendfile to optimize static file processing.

The following attributes are supported in the AJP APR connector in addition to the ones supported in the regular AJP connector:

Attribute Description
firstReadTimeout

The first read of a request will be made using the specified timeout. If no data is available after the specified time, the socket will be placed in the poller. The value of this attribute is in ms. Setting this value to 0 or -1 will increase scalability by always using a poller to handle keepalive, but will have a minor impact on latency (see the related pollTime attribute). The difference is that with 0, the first read of a request will be made using a short timeout, while with -1, the first read will be made using the regular socket timeout that is configured on the connector. Setting this to -2 will cause the connector to not use the poller for keepalive in most situations, emulating the behavior of the java.io HTTP connector. The default value is -1. Note: on Windows, the actual value of firstReadTimeout will be 500 + the specified value, if the specified value is strictly positive.

pollTime

Duration of a poll call. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (5ms).

pollerSize

Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keepalive connections.


Apache Tomcat 5.5 Servlet/JSP 容器 - 怎样配置负载均衡

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

怎样配置负载均衡
目录

使用JK 1.2.x 本地连接器
使用 Apache HTTP Server 2.x 和 mod_proxy
使用具有均衡功能的web应用

使用JK 1.2.x 本地连接器
请参考 JK 1.2.x 相关文档.
使用 Apache HTTP Server 2.x 和 mod_proxy
请参考 Apache HTTP Server 2.2.x的mod_proxy有关文档. 它支持 HTTP 或者 AJP 方式的负载均衡. 新版的 mod_proxy 在 Apache HTTP Server 2.0业可以使用, 但 mod_proxy 是从Apache HTTP Server 2.2中分离编译出来的。
使用具有均衡功能的web应用
概要

Tomcat 5.0.15 及以后版本均带有叫做balancer的web应用。这是一个基于规则的负载均衡的简单实现。 它不是设计用来代替其它用于高流量环境的装载均衡机制。相反，它是个简单的，纯Java，易扩展，在多个服务器之间是分担负载的简便方式。

尽管Tomcat自带带均衡器，但它不是Tomcat特有的，它不需要任何修改就能在其他容器上运行。 如果你想通过过滤器来重定向客户端请求，该web应用需要支持Servlet 2.3或其后版本的容器。 如果你想通过servlet来重定向客户端请求，你可以使用任意的servlet容器。

配置范例

默认的均衡器安装使用一个单独的过滤器，BalancerFilter，用来映射所有的请求(url-pattern /*)。 过滤器从web应用部署描述文件(web.xml)里指定的规则文件中读取规则。默认的规则有：

  • URL里含有"News"的请求转向www.cnn.com
  • 把一个带有paramName的参数，参数值是paramValue的请求转向www.yahoo.com。
  • 把所有其它请求转向jakarta.apache.org。
因此，当你安装并启动好tomcat之后，在浏览器中访问http://localhost:8080/balancer，将被转向到http://jakarta.apache.org。 如果浏览器访问http://localhost:8080/balancer/News，将被转向到http://www.cnn.com。 一个http://localhost:8080/balancer/BlahBlah?paramName=paramValue的请求会被转向到http://www.yahoo.com。

负载均衡规则

均衡器系统的规则是一个请求匹配条件，以及相匹配请求的URL重定向的组合。这些规则实现org.apache.webapp.balancer.Rule接口。

均衡器发布包自带许多有用的规则。这个框架被设计成很方便扩展，这样你可以快速编写你自己的规则。 规则必须是标准的JavaBean (公有的无参数构造方法， 属性具有公有的setter 方法，比如 属性xxx的setXXX ), 就象它们被Jakarta Commons Digester实例化那样。关于规则的可使用性或怎样把你的规则包含到发布包中去，请到tomcat-user邮件列表上询问。

规则被组装在RuleChains里边。每个BalancerFilter (或者 Servlet/JSP)在做转向的决定时参考一个RuleChain。 注意，你不是象范例配置里那样被限制只有一个对应于/*的过滤器。你可以使用Servlet Specification里定义的full filter mapping可能性，随意配置多少你想要的过滤器。每个过滤器有它自己的RuleChain。

它是怎么工作的

  1. 首先编写一个包含各种匹配规则和重定向的配置文件。
  2. 在web.xml文件中定义均衡器过滤器，将它映射到你想要的url(通常都是 /*) ，并通过配置文件里的规则来配置。
  3. 服务器启动，初始化过滤器。
  4. 请求传入服务器。过滤器匹配规则链来决定把这个请求转向哪里。规则是按照规则配置文件里定义的顺序来进行匹配的。 找到第一个匹配上的规则后，不再继续匹配，这个请求马上被重定向。

备注

请将问题，评论，建议等发往tomcat-user邮件列表。谢谢。


Apache Tomcat 5.5 Servlet/JSP 容器 - Building Tomcat

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Building Tomcat
Introduction

Building Tomcat from SVN is very easy, and is the first step to contributing to Tomcat. The following is a step by step TODO list.

Download and install a Java Development Kit 1.4.x or later

The default distribution of Tomcat 5.5.x requires a 5.0 or later JDK. Tomcat can be built using a 1.4.x JDK but you will need to copy the contents of the compat directory (created by the build process) to your build directory before Tomcat will start.

The Sun JDK can be downloaded here.

IMPORTANT: Set an environment variable JAVA_HOME to the pathname of the directory into which you installed the JDK release.

Install Apache Ant 1.6.2 or later

Download a binary distribution of Ant 1.6.2 or later from here.

Unpack the binary distribution into a convenient location so that the Ant release resides in its own directory (conventionally named "apache-ant-1.6.x"). For the purposes of the remainder of this document, the symbolic name "${ant.home}" is used to refer to the full pathname of the release directory.

Create an ANT_HOME environment variable to point the directory ${ant.home}, and modify the PATH environment variable to include directory "${ant.home}/bin" in its list. This makes the "ant" command line script available, which will be used to actually perform the build.

Building Tomcat

Download the main build.xml script from here.

Create a new directory, and copy the newly download build.xml to it. This directory will be referred to as the ${tomcat.source} directory in the rest of this document.

Go to that directory, and do:
cd ${tomcat.source}
ant

NOTE: Users accessing the Internet through a proxy must use a properties file to indicate to Ant the proxy configuration. Read below.

WARNING: Running this command will checkout the Tomcat 5 sources from SVN, as well as download binaries to the /usr/share/java directory. Make sure this is appropriate to do so on your computer. On Windows, this usually corresponds to the C:\usr\share\java directory, unless Cygwin is used. Read below to customize the directory used to download the binaries.

The build can be controlled by creating a ${tomcat.source}/build.properties file, and adding the following content to it:
# ----- Proxy setup -----
# Uncomment if using a proxy server.
#proxy.host=proxy.domain
#proxy.port=8080
#proxy.use=on

# ----- Default Base Path for Dependent Packages -----
# Replace this path with the directory path where
# dependencies binaries should be downloaded.
base.path=/usr/share/java

Updating and rebuilding Tomcat sources

It is recommended to regularly update the downloaded Tomcat 5 sources. To do this, execute the following commands:
cd ${tomcat.source}
ant checkout

For a quick rebuild of only modified code you can use:
cd ${tomcat.source}
ant build

Building with Eclipse

Important: This is not a supported means of building Tomcat; this information is provided without warranty :-). The only supported means of building Tomcat is with the "ant build" described above. However, some developers like to work on Java code with a Java IDE, and the following steps have been used by some developers.

Note that you must complete all the above steps to fetch the repositories and build some JAR files the first time. After you have completed the above steps, you can set up a series of Eclipse 4 projects. Note that this will not let you build everything under Eclipse; the build process requires use of Ant for the many stages that aren't simple Java compilations. However, it will allow you to view and edit the Java code, get warnings, reformat code, perform refactorings, run Tomcat under the IDE, and so on.

Use Windows->Preferences and then Java->Build Path->Classpath Variables to add two new Classpath variables:

TOMCAT_LIBS_BASE | the base path where the binary dependencies have been downloaded
ANT_HOME | the base path of Ant 1.6.2 or later

Use File->New Project to create a new Java project for each of the binaries repository (e.g., /usr/share/java), container, connectors, jasper, servletapi. Unless you thought ahead to make the ${tomcat.source} directory be under your Workspace folder, tell Eclipse the external location using "Import/Export...", General->Existing Project into Workspace.

Eclipse .project and .classpath files are provided in each of these directories so Eclipse should find all source trees and jars, and hopefully compile without problems. Note that these files assume you are using Eclipse with a 5.0 or later JDK; also, the connectors module must be built with a compiler compliance level of 5.0.

To run Tomcat without a special IDE plug-in, you can simply use Run->Run... enter "org.apache.catalina.startup.Catalina" as the main class, "start" as program arguments, and "-Dcatalina.home=..." (with the name of your build directory) as VM arguments.

Note also that due to the way the Tomcat source is assembled from several SVN projects, you may not be able to use the Eclipse SVN client to update (nor to commit, if you are a committer). Use the external SVN client of your choice, then use the Eclipse PackageExplorer or Navigator "Refresh" context menu item to tell Eclipse that you've updated the files.

Building with other IDEs

The same caveats apply as for Eclipse, above.

The same general idea should work in most IDEs; it has been reported to work in Idea, for example.


Apache Tomcat 5.5 Servlet/JSP 容器 - 怎样使用CGI

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

怎样使用CGI
简介

CGI (通用网关接口)定义了让web服务器与外部内容生成程序交互的一种方式，也就是通常所说的CGI程序或CGI脚本。

当你使用Tomcat作为你的HTTP服务器，并要求提供CGI支持，你就可以把CGI支持添加到Tomcat里。通常在你还不想要运行一个象Apache httpd这样的web服务器的开发过程中它就已经被实现了。Tomcat的CGI支持在很大程度上与Apache httpd's相兼容，但是存在一定局限(例如，只有一个cgi-bin 目录)。

CGI支持是通过使用servlet类org.apache.catalina.servlets.CGIServlet 来实现的。习惯上，这个servlet与URL映射 "/cgi-bin/*"相对映。

在Tomcat默认不支持CGI。

安装

警告——CGI脚本可以用于执行Tomcat的java虚拟机外部的程序。如果你在使用Java SecurityManager，它可以绕过你在catalina.policy里配置的安全策略。

将$CATALINA_BASE/server/lib/servlets-cgi.renametojar 改名为 $CATALINA_BASE/server/lib/servlets-cgi.jar

将$CATALINA_BASE/conf/web.xml 文件中CGI servlet 和servlet-mapping 配置周围的XML注释去除掉。

配置

以下几个servlet初始化参数可以用来配置CGI servlet的行为。

  • cgiPathPrefix - CGI搜寻路径从web应用程序的根目录 + 文件分割符 + 路径前缀 开始。默认的cgiPathPrefix是/WEB-INF/cgi 。
  • debug - servlet日志信息的调试级别。默认是0。
  • executable - 用来运行script的可执行程序名。默认是perl。
  • parameterEncoding - 与GCI servlet一起使用的参数编码名称。 默认是System.getProperty("file.encoding","UTF-8") 。
  • passShellEnvironment - 是否将shell的环境变量 (任意) 传给 CGI 脚本? 默认为 false.


Apache Tomcat 5.5 Servlet/JSP 容器 - 修订记录

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

修订记录
Tomcat 5.5.21 (fhanik)
Catalina
fix | 29727: If env-entry values in web.xml are changed then ensure new values are applied when context is reloaded. (markt)
fix | 34956: Ensure request and response objects passed to a RequestDispatcher meet the requirements of SRV.8.2 and SRV.14.2.5.1. This is disabled by default. The Java option -Dorg.apache.catalina.STRICT_SERVLET_COMPLIANCE=true is required to enable this test. (markt)
fix | 36274: When including static content with the DefaultServlet also treat content types ending in xml as text. (markt)
fix | 37439: Update documentation for Engine component to add the requirement that the name must be unique. (markt)
fix | 37458: Add syncs to the WebappClassloader to address rare issues when multiple threads attempt to load the same class concurrently. (markt)
fix | 39436: Correct MIME type for SVG. (markt)
fix | 39724: Removing the last valve from a pipeline did not return the pipeline to the original state. Patch provided by David Gagon. (markt)
fix | 36976: Don't use CATALINA_OPTS when stopping Tomcat. This allows options for starting and stopping to be set on JAVA_OPTS and options for starting only to be set on CATALINA_OPTS. Without this fix, some startup options (eg the port for remote JMX) would cause stop to fail. Based on a fix suggested by Michael Vorburger. (markt)
fix | 37070: Update mbean name documentation to include the StandardWrapper. (markt)
fix | 40528: Add missing message localisations as provided by Ben Clifford. (markt)
fix | 40625: Stop CGIServlet swallowing the root cause of an exception. Patch provided by Takayoshi Kimura. (markt)
fix | 40723: Correct table creation example in JavaDoc for JDBCAccessLogValve. (markt)
fix | 40802: Add jsp-api.jar to fileset in catalina-tasks.xml as provided by Daniel Santos. (pero)
fix | 40817: Correct problem where CGI scripts in the root of the ROOT context threw a StringIndexOutOfBoundsException. (markt)
update | Set the SCRIPT_FILENAME environment variable required by PHP when using the CGIServlet to execute PHP.
fix | 40823: Update context doc to clarify use of ROOT.xml, multi-level context paths and to further discourage use of server.xml (markt)
Coyote
fix 40771: Fix implementation of SavedRequestInputFilter.doRead() so POST data may be read using a Valve or Filter. Patch provided by Michael Dufel. (markt)
Webapps
fix | 34952: Clarify that the Windows Installer always installs a Windows service. (markt)
fix | 35968: Make environment entry properties input a text area. Patch provided by Tristan Marly. (markt)
fix | 38048: Fix memory leak assoaciated with use of expression language in JSPs. Patch provided by Taras Tielkes. (markt)
fix | 40633: Remove references to the DefaultContext from the documentation. (markt)
Cluster
add Add better recovery at FastAsyncQueueSender. Made the startegy more robust for temporary connection problems (pero)
Tomcat 5.5.20 (fhanik)
Catalina
fix | Fix logic error in UserDatbaseRealm.getprincipal() that caused user roles assigned via groups to be ignored. (markt)
fix | 40518: Use correct message when a RuntimeException is thrown from the requestInitialized or requestDestroyed method of a listener that implements ServletRequestListener. (markt)
Jasper
fix | 31804: Unnested tags within a tag file are now configured with the Tag represented by the containing tag file as their parent tag. (markt)
fix | 33356: Tag attributes that contained $ followed by 1 or more non-special characters and then a { character caused an exception. (markt)
fix | 33407: The string \$ in template text was reduced to $ when the isELIgnored page directive was set to true. (markt)
fix | 34509: Tag names may now use the full range of characters permitted by xsd:nmtoken. (markt)
Webapps
fix 34399: Disable undeploy for applications that have not been deployed such as those defined in server.xml (markt)
Tomcat 5.5.19 (fhanik)
General
update Add multi attribute setting to jmx:set JMX remote ant task. Patch contributed by Didier Donsez (pero)
Catalina
fix | 30762: Re-fix this bug that was re-introduced by the fix to 37264. (markt)
fix | 37588: Fix JNDI realm creation through JMX. Patch contributed by TerryZhou (fhanik)
fix | 39704: The use of custom classloaders failed when the context was specified in server.xml. Correction of the fault will require setting the new loader attribute useSystemClassLoaderAsParent to false. (markt)
Coyote
fix 40418: APR Endpoint socket evaluation (remm)
Webapps
fix 31339: Admin app threw exceptions if a name other than Catalina was configured for the Engine. Patch based on a suggestion from Amila Suriarachchi. (markt)
Tomcat 5.5.18 (yoavs)
General
update Change MD5 release signature files to have md5 (小写) extension instead of MD5 (大写), 来自 Henk Penning 和 specified 在 ASF 发行出版指导. (yoavs)
Catalina
fix | Fix that ManagerBase increment expireSessions counter at background task two times. (pero)
fix | 39406: 修正StandardSession#getLastAccessedTime()方法使用正确的异常信息, 该建议来自 Takayoshi Kimura. (pero)
add | 39661: 新增关于JULI FileHandler properties的文档. (yoavs)
add | 39657: 如果JSP API 存在于web应用的类加载路径中将提示警告信息 (不再加载该jar) , 该建议来自David Sanchez Crespillo. (yoavs)
add | 39674: 在 service.bat 脚本中支持 JRockit JVM, 该建议来自 lizongbo . (yoavs)
fix | 39711: 更新加载器配置文档, 该建议来自 Stephane Bailliez. (yoavs)
fix | 39865: 新增Open Office的mime类型到conf/web.xml. (markt)
fix | 38814: Align CGI handling of indexed queries, parameters and POST content with other CGI providers. The changes: only provide parameters on the command line for indexed queries; always provide the query string via the QUERY_STRING environment variable; provide POST content unmodified to stdin; and never call getParameters(). (markt)
fix | 34801: Partial fix that adds handling of IOExceptions during long running CGI requests. Based on a patch by Chris Davey. (markt)
fix | 39689: Allow single quotes (') and backticks (`) as well as double quotes (") to be used to delimit SSI attribute values. (markt)
fix | 40053: Correct application deployment documentation so it agrees with the classloader documentation regarding shared lib and CATALINA_BASE. (markt)
fix | 39592: Stop HEAD requests for resources handled by SSI servlet or filter generating stack traces in the logs. (markt)
fix | Improve handling of the ';' character in the URL so that it is now allowed if properly %xx encoded. (remm)
Coyote
fix Fix APR endpoint so that the acceptor thread now only processes socket accepts. (remm)
Webapps
fix | 39813: Correct handling of new line characters in JMX attributes. Patch provided by R Bramley. (markt)
fix | 37781: Make sure that StoreConfig save external referenced war files at context.xml correct. (pero)
fix | 39791: Use correct default for useNaming within a Context. (markt)
fix | Correctly generate re-direct for admin app index.jsp to prevent login page being displayed twice when cookies are disabled. (markt)
Cluster
fix 39473: 集群环境中，Session 超时远小于web.xml 中的配置,该建议来自 Jin Jiang. (pero)
Tomcat 5.5.17 (yoavs)
General
update | 更新至 Xerces 2.8.0 (remm)
update | 更新至 tcnative 1.1.3 (remm)
Catalina
fix | Fix SingleSignOn Valve and add Session.getLastAccessTimeInternal() without session invalidation test. (pero)
fix | 38814: CGIServlet 正确处理 Shift_JIS 输出. (markt)
fix | 新增遗漏的环境变量“REQUEST_URI” 到 CGI 环境中. (markt)
fix | 27617: Sync existing mime types with httpd. (keith)
fix | 38761: Handle relative symlinks to shell scripts as suggested by Adam Murray (keith)
fix | 38795: Associate more closely bind with a finally unbind in StandardContext start and stop, based on a patch by Darryl Miles (remm)
fix | Improve undeployment robustness (remm)
update | Expand the semaphore valve (remm)
fix | 39021: Add back support for authentication only, submitted by Scott Stark (remm)
fix | Revert fix for 38113, which does not seem a legitimate problem, and causes regressions (remm)
fix | 当重新加载web应用时正确的重置监听器(remm)
fix | 38194: Don't fail silently if -force is used without CATALINA_PID, submitted by Matthew Buckett. (yoavs)
fix | 38154: 在web应用取消部署避免FileDirContext中的NPE错误 , 该报告来自 Jamie Maher. (yoavs)
fix | 38217: Added cautionary note about keystore password to SSL HowTo,该建议来自 Ralf Hauser. (yoavs)
fix | 38262: Cleared ambiguity in host documentation,该建议来自 Jeffrey Bennett. (yoavs)
fix | 38476: 修改对空的TLD流的检测,该建议来自 Fabrizio Giustina. (yoavs)
fix | 38052: 使用 userName 作为默认的用户字段名. "User" 在很多数据库中是保留关键字 , 该建议来自 rik. (pero)
fix | 修正对"if-range"头信息不存在的处理 (remm)
fix | 37848: Only output catalina.sh diagnostic messages if we have a TTY, submitted by David Shaw. (yoavs)
fix | 38596: Minor performance optimization in DataSourceRealm, suggested by Sandy McArthur. (yoavs)
Coyote
fix | Make the default cipher suites available for SSL the same as the set of cipher suites enabled by default rather than the set of all cipher suites. This prevents ciphers suites that do not provide confidentiality protection and/or server authentication being used by default. (markt)
fix | Move AprEndpoint.getWorkerThread inside the try/catch for the main accept loop, to guard about an OOM (which would most likely doom the server anyway) (remm)
fix | As exhibited in the ASF's JIRA installation, it seems EINTR is a status code that should be ignored as a result to a poll call (remm)
update | New APR connectors defaults (remm)
update | Add multiple threads for APR pollers, to work around Windows limitations (performance degrades very rapidly if poller sizes over 1024 are allowed when compiling APR) (remm)
update | New modes for firstReadTimeout (-1 being the new default) (remm)
update | 在APR 端点中使用一个简单的数组来替代 java.util.Stack (remm)
fix | tcnative jnilib.c now report correct compile flags for runtime Library.java checks like sendfile support default true/false (pero)
Jasper
fix | 38015: Remove misleading warnings logged in TagLibraryInfoImpl,该建议来自 Andrew Houghton. (yoavs)
fix | 38376: Make sure body content stack is always properly aligned, as submitted by Tony Deigh. (yoavs)
fix | 兼容 JDT 3.2 (remm)
Webapps
fix | 39292: 更新 catalina.policy at demo balancer app. 由 Kerry Sainsbury 提供修正(pero)
fix | 36847: Fixed the manager app copy function to not overwrite fileA with fileB when fileA==fileB. Fix provided by Haroon Rafique (fhanik)
fix | 38508: Several enhancements to Host Manager application, including configurable manager app support and dialog box enhancements. Thanks to George Sexton for the patch. (yoavs)
fix | 37781: 确认上下文配置文件为可写属性, 该建议来自 George Sexton. (yoavs,pero)
Cluster
update | Add at PooledSocketSender the jmx attributes inPoolSize and inUsePoolSize. (pero)
fix | DeltaManager 使用备份方式设置session创建时间. (pero)
update | Add JvmRouteBinderValve documentation at cluster-howto.xml. (pero)
add | JvmRouteBinderValve now supports now sessionid's from request and cookies. Thanks to Brian Stansberry for reporting it. (pero)
fix | 38779 Fix wrong jmx message arg at SimpleTcpCluster at o.a.c.cluster.tcp.mbeans-descriptors.xml, submitted by Pawel Tucholski (pero)
fix | Fix that not after every "Keep Alive Socket close" a log warning is generated at TcpReplicationThread (pero)
fix | 39178: Now ROOT.war deployment with FarmWarDeployer is possible (pero)
fix | ReplicationValve not set primarySession flag when all backup nodes gone (pero)
update | Add DeltaSession.getLastAccessTimeInternal() without session invalidation test. (pero)
Tomcat 5.5.16 (yoavs)
General
update | Updated / enhanced docs to remove old FIXME references. (yoavs)
update | Required tcnative library version upgraded to 1.1.2 (remm)
update | Update to Eclipse JDT 3.1.2 (remm)
Catalina
fix | 23950: Context.listBindings() should return objects not references. (markt)
fix | 38124: Add support for Windows 20xx when reading environment variables in CGIServlet. (markt)
fix | 29214: response.containsHeader() now returns the correct value for Content-Type and Content-Length headers. (markt)
fix | Allow using a custom ContextConfig when using JMX embedding of Tomcat, as is done by the regular deployer. (remm)
add | Add JMX serverInfo attribute to Server MBean, that we can identify the tomcat release remotely. (pero)
fix | Fix the JMX MBeanFactory.createStandardHost signature at mbean-descriptors.xml (pero)
fix | Fix some cases (for example with realm usage) where the container logger for a context would be retrieved using the wrong classloader (remm)
fix | HttpSession.getId will no longer throw an ISE when the session is invalid (remm)
fix | More detailed errors for naming issues (remm)
docs | Add documentation for the Transaction element (remm)
update | Add getContextPath to the internal servlet context implementation (remm)
fix | Only null instances loaded by the webapp CL, submitted by Matt Jensen (remm)
update | Deploy folders which don't have a WEB-INF, and return an error when a context file does not contain a Context element (remm)
fix | 38653: Fix property name (remm)
fix | Slightly modify the timing of the manager start, so that it is not started by a listener (remm)
fix | Refresh loggers used by the digester (remm)
fix | Use sendError instead of setStatus to send the 401 code. (billbarker)
fix | Don't append the port for an SSL redirect if it is the default port. (billbarker)
Coyote
fix | Log errors when setting socket options with debug priority rather than error. (remm)
fix | 38100: Make certain that a valid Host name is set, or none at all. (billbarker)
fix | 38485: Fix minor regression setting connection timeout (as well as linger and no delay) where the default value was always used when using the regular HTTP connector (remm)
update | Pass along more of the SSL related fields to OpenSSL (remm)
update | CharChunk now implements CharSequence (remm)
fix | Fix coding error which could cause a rare crash when a poller error occurred and sockets where pending being added to the keepalive poller (remm)
fix | Fix potential sync issues when restarting a poller (remm)
fix | Update APR error reports, including the error codes (remm)
fix | 38726: Remove duplicate request group field causing blank statistics for the HTTP connector (remm)
fix | Fix invalid length used by some AJP packets for the AJP APR connector, which could cause corruption, submitted by Rudiger Plum (jim)
fix | 38346: Fix problems with request.getReader().readLine(). Patch by Rainer Jung (billbarker)
update | Local address reuse for APR Endpoints (via APR_SO_REUSEADDR) now enabled (jim)
fix | Don't write out the shutdown secret file if shutdown is disabled (the default) (billbarker)
fix | Fix NPE when no sink is supplied. (billbarker)
update | APR Endpoints now IPv6 aware (jim)
update | Downgrade "Response already committed" logging entry to DEBUG. (billbarker)
fix | 38113: Return the empty String for an empty query-string instead of null. (billbarker)
Jasper
fix | 38389: Set correct JDT Compiler option to java 1.5 compliance. Patch from Olivier Thomann and Paul Hamer (pero)
update | Add some useful hints to jasper-howto. (pero).
fix | 38776: Fix source file attribute, submitted by Olivier Thomann (remm)
Cluster
fix | Update DeltaManager session access stats (pero)
fix | DeltaSession getId will no longer throw an ISE when the session is invalid (pero)
update | Resurrected the "suspect" property so that the logs don't fill up with errors when member disappears or a connection is lost. Only useful for pooled mode (fhanik)
add | 35710: Add session replication for cross context session changes. The portlet api need this support, see refactored ReplicationValve. (pero)
update | ReplicationValve reset DeltaSession when cluster node has no backup node. (pero)
update | DataSender close connection and throw exception also even if waitForAck is false. (pero)
fix | Active cluster junit test again. (pero)
Webapps
fix | Fix some XSS issues in the JSP examples. (markt)
fix | Fix logos in the manager webapp (remm)
Tomcat 5.5.15 (yoavs)
General
fix 32081: Remove the JDK requirement from the Win32 scripts. (keith)
Catalina
fix | 37852: Fix regression where the magic role '*' was denying all access. Patch by xrcat (billbarker)
fix | 37934: Don't ask for authentication if deny-from-all is in effect. (billbarker)
fix | 15570: auth-constraint of * was interpretted as all authenticated users rather than as all roles defined in web.xml. (markt)
fix | Remove leftover static logger which was used to log application level messages in ApplicationContextFacade (remm)
fix | 38012: Where a CGI script sets a response code, use it. (markt)
fix | 37854: Extension-List checking was too strict. (markt)
Coyote
fix | Report binding errors in the APR endpoint as strings rather than platform specific status codes (remm)
fix | 37934: Don't ask for authentication if deny-from-all is in effect. (billbarker)
fix | 38047: Handle the case where the Servlet attempts to read the Request body from the AJP/1.3 Connector, in the case that no body was sent. (billbarker)
fix | 38030: Unconditionally return EOS for an attempt to read the body of any request that doesn't send CL or TE. (remm, billbarker).
Jasper
fix | 35351: Fix problem using an inner class for a <jsp:useBean />. (kinman).
fix | 37929: Don't stop on the generic attribute methods just because the session is invalid. Patch by Pierre Delisle. (billbarker)
update | Add system properties org.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER and org.apache.jasper.runtime.JspFactoryImpl.USE_POOL to allow configuring Jasper memory usage (remm)
fix | 37933: Restrict <jsp:getAttribute /> to only look in PAGE_SCOPE. (billbarker)
Cluster
fix | 37808: Fix ArrayIndexOutOfBoundsException inside XByteBuffer. Reported by Dietmar Mueller (pero)
update | 37896DataSender starts new Socket after IOException. (pero)
update | Reduce memory usage at membership service. (pero)
Tomcat 5.5.14 (yoavs)
General
update | Update optional native APR connector version to 1.1.1. (mturk)
update | Update build.properties.default to get native connector from new location. (yoavs)
Catalina
fix 13040: Fix getContext() when used to obtain a context that is a sub-context of the current context. Ported from TC4. (markt)
Jasper
fix 37746: Remove extra space from StringTokenizer pattern in JspC,该建议来自 Eric Hedstrom. (yoavs)
Coyote
fix | 36863: Strip quotes when parsing Cookie values, even for v0 Cookies. (billbarker)
fix | 37803: Don't claim that we have a string value in MessageBytes until we actually do. Patch by Doug Rand (billbarker)
Tomcat 5.5.13 (yoavs)
General
fix | 36711: Unused line of code. (yoavs)
update | Removed unused SAXPath, Jaxen dependencies. (yoavs)
update | Update log4j dependency to version 1.2.12, Struts to 1.2.7. (yoavs)
update | Removed JDBC 2.0 StdExt dependency (only class from there is javax.sql.XADataSource, which is present in JDK 1.4 and later. (yoavs)
fix | 37039: typo on JK Quick configuration how-to. (yoavs)
add | 37035: Add a placeholder file in the temp directory for WinZip tar.gz handling. (yoavs)
update | Update JAF dependency to 1.0.2, JTA to 1.0.1b and JavaMail to 1.3.3_01. (markt)
add | Added Eclipse .project, .classpath, and associated files to make building Tomcat from Eclipse significantly easier. (markt)
add | 37284: Guess JSE 5.0 location on Mac OS X, patch by Stepan Koltsov. (yoavs)
fix | : Wrong class name in antlib.xml for JkStatusUpdateTask. (yoavs)
Catalina
fix | 36802: Fix problem of double-init when JMX-deploying a Context into a started Host. (billbarker)
fix | 36840: Provide information as to which web.xml is being processed on startup to help debug parsing errors. (yoavs)
add | 34724: Ability to set domain for Single-Sign-On cookie. Patch by Oliver Rossmueller. (yoavs)
fix | 37044: RealmBase.hasResourcePermission needs to access the GenericPrincipal as set by the realm unless hasRole is overriden, which was no longer being done properly for the JAAS realm (remm)
fix | 37264: JNDI resources were no longer available when stopping listeners, submitted by Bogdan Calmac (remm)
fix | 37150: Turn off directory listing by default and add a warning regarding enabling listing of directories with many entries. (markt)
update | Add configurability for the amount of time that the container will wait for requests to complete when unloading servlets, using the unloadDelay property. (remm)
update | Add code to set to null fields in loaded classes when stopping a web application, as a possible workaround for suspicious garbage collection behavior. (remm)
update | Update messages and stack traces for classloading errors which may occur when removing a web application, and for stopped web applications. (remm)
fix | 37319: Fix catalina.bat reference to CATALINA_BASE for logging.properties. Thanks to Pierre-Yves Benzaken. (yoavs)
fix | 36852: Custom classloaders don't honor Contet privileged attribute. Thanks to Matt Brinkley for the analysis and patch. (yoavs)
fix | Fix for a couple of (mostly silly) edge-cases in testing auth. Thanks to Nam T. Nguyen for the report. (billbarker)
fix | 37060: Actually copy the Request headers when replaying after Form auth. (billbarker)
fix | 37591: Typo in Engine configuration reference. (yoavs)
fix | 37668: Added note about JSP recompilation to Context configuration documentation. (yoavs)
fix | 37132: Have DigestAuthenticator Handle user names with commas. Thanks to Robert Wille for the patch. (yoavs)
fix | 37212: Better error reporting in Connector.java. Thanks to Ralf Hauser for the patch. (yoavs)
Coyote
fix | Gracefully handle the case where some Socket options are disabled at the OS level for the AJP/1.3 Connector. (billbarker)
fix | 36366: Use rewritten deployer-howto page by Allistair Crossley. (remm)
add | 36630: Added extra log output for class instantiation failure. (yoavs)
fix | 37121: Sendfile always needs to be given the length of data to write, which fixes ranged requests. (remm)
fix | Optimized direct byte buffers association with the socket for APR connectors. (mturk)
fix | Fix hidden NPEs when using the APR connectors and there's no host header. (pero, remm)
fix | Http11Protocol now register RequestProcessor at JMX and show current usage inside manager app. (pero)
add | JkStatus Ant tasks for mod_jk 1.2.15. (pero)
update | Connection Timeout is normal, so reduce logging to DEBUG (billbarker)
fix | Fix crash which could occur with the HTTP APR connector when accessing request JMX objects outside of the processing of the said request (remm)
fix | 37627: Fix buffering issue in the HTTP APR connector when a large buffer size was used for servlets (remm)
fix | 37673: Fix implementation of getLocalPort and getLocalAddr in the HTTP APR connector (remm)
Jasper
fix | 35252: Jasper PageDataImpl outputs malformed XML. Patch by Rahul Akolkar. (yoavs)
add | 37062: Helpful JSP exception message containing file, line numbers. Patch by Tim Fennell at http://www.tfenne.com/jasper/. (yoavs)
fix | 37407: File descriptor leak in JspReader. Thanks to Fred for the patch. I also did some minor cleanup in the class. (yoavs)
add | 37612: Add file location to JSP Validator error message. Thanks to Renaud Bruyeron for the patch. (yoavs)
Cluster
fix | Fix that session replace messages are logged after node recovery get all session from master node. (pero)
fix | 37896 Fix that sendMessage signature at all DataSender subclasses must be changed. Now pooled and async modes working as expected. (pero)
fix | Fix that socket at o.a.c.cluster.tcp.FastAsyncSocketSender can be disconnect/connect. (pero)
fix | Fix cluster module build.xml script for new svn repository structure (pero)
fix | Fix closed socket exceptions at normal server shutdown, reported by Olve Hansen (pero)
fix | Fix closed socket exceptions inside async message transfer modes (pero)
fix | 34984: HttpSessionBindingEvent.getValue() get correct value (pero)
fix | 35916: send sessionCreated to SessionListener after cluster node recovery (pero)
fix | 36541: Used also Hashtable at DeltaSession (pero)
fix | Better support cluster at engine level. (pero)
fix | 36866: Correct attribute name in conf/server.xml documentation for Cluster element. (yoavs)
fix | 37261: Allow xerces to know where the web.xml file is so that relative entities can be resolved.
fix | 37529: Fixed race condition in ReplicationLister#stopListening. Thanks to Chris Walker for the patch. (yoavs)
Webapps
fix | Remove obsolete TagPlugin file from JSP examples (billbarker)
fix | 36019: Made clear the Host-Manager HowTo is coming soon, not ready yet. (yoavs)
fix | 36336: Check WAR extension in both upper and lower case,该建议来自 A. Grasoff. (yoavs)
fix | 35982: Can't delete mail sessions in admin webapp. (yoavs)
fix | 36673: Similar to the one above, for data sources. (yoavs)
Tomcat 5.5.12 (yoavs)
General
fix | Remove uneeded files in conf. (remm)
update | Change distribution file names from jakarta-* to apache-*. (remm)
Catalina
add | Add JMX Remote create and unregister ant tasks (pero)
fix | 36343: Only normalize out backslash on Windows platforms. (billbarker)
fix | Allow configuring standard stream redirection. (remm)
add | 36088: Add RUNNING.txt and RELEASE-NOTES.txt to fulldocs distro. (yoavs)
fix | 36534: fix equals for URLs returned by ServletContext.getResource() (luehe)
fix | 36558: Clear IntrospectionUtils cache when stopping a webapp, as it could leak to keeping a reference to the classloader (remm)
fix | 36113: Session persistence for objects with primitive types could fail in some rare cases (remm)
fix | 36541: Full synchronization for session objects attributes collections (remm)
fix | 35609: service.bat echo command when wrong arguments given [patch by Robert Longson] (yoavs)
fix | 34749: jsessionid dropped on trailing slash (/) redirect (remm)
Coyote
update Add support for secret for AJP APR (remm)
Jasper
fix | Fix NPE with an error message when no Java compiler is available (remm)
fix | Restrict System err stream capture to the Ant compiler, as the Eclipse compiler does not need it (remm)
update | JSP compilation speed improvement using tag library information caching, submitted by Xingbo Gao (remm)
add | Initial contribution of JSTL tag plugins supporting the core tag library of JSTL, submitted by Jing Li (remm)
Cluster
fix | 36541: Sync all session attribute access (read and write) at DeltaSession (pero)
fix | 36518: Classname typos for senders, submitted by Christoph Bachhuber-Haller (remm)
add | 35613: Added FAQ question and answer about tcpListenAddress="auto" and /etc/hosts (yoavs)
update | Moved FAQ section for Clustering from Clustering HowTo page to its own FAQ page. (yoavs)
Webapps
docs | 36319: Fix broken link to DBCP docs, submitted by Xavier Poinsard (remm)
docs | Brand new deployer specs, submitted by Allistair Crossley (remm)
Tomcat 5.5.11 (yoavs)
General
update | Update to Xerces 2.7.1 (remm)
add | Add ready to build bin/tomcat-native.tar.gz for the APR JNI wrapper library (remm)
fix | 35930: Bad logging config used by the Tomcat Windows service (remm)
add | 33261: Windows installer now checks the user type and warns non-admins as needed. (yoavs)
update | The Windows installer will now optionally download a (32bit) Windows .dll for Tomcat native from HEAnet (remm)
fix | Declaration of jspc Ant task to fix the deployer package (remm)
Catalina
add | Add concurrency control valve (o.a.c.valves.SemaphoreValve). As the Tomcat distribution is not built for Java 5, the valve will have to be compiled from the sources using Java 5 (remm)
fix | 35880: Ignore JSSE15SocketFactory when generating JavaDoc, as it breaks the JDK 1.4 JavaDoc tool. (yoavs)
fix | 35865: setclasspath.sh cannot be excutive under cygwin. (funkman)
fix | 33267: Set working path in service installer,该建议来自 Dominik Drzewiecki. (yoavs)
update | 34794: Update connector documentation to include clientAuth attribute. (yoavs)
fix | 35894, 36228: Fix CNFE when starting in a sandbox. (billbarker, remm)
fix | Add version check for Tomcat native so that incompatible API changes are detected early (remm)
fix | 36020: Allow MemoryUserDatabase to work better on write protected mediums, submitted by Rainer Jung (remm)
fix | 35978: Bad handling of single range requests greater than 2GB in the DefaultServlet (remm)
fix | 35984: Client abort exceptions will now use getCause (remm)
fix | Fix handling of non-file based includes with SSI, submitted by David Becker (markt)
Coyote
fix | Fix default ports for http and https which are set in the request when the parsed hostname does not specify the port, and which were inverted (https was set as 80 and http as 443). (remm)
fix | Add missing tomcatAuthentication attribute to the AJP APR implementation. (remm)
fix | Check filename sendfile attribute only if sendfile is enabled. (remm)
fix | Fix output buffering for APR AJP implementation. (remm)
fix | 35941: Fix getRemoteAddr for APR AJP implementation. (remm)
fix | 35942: Fix NPE retriving cipher suite attribute when no certificate was submitted (for example with no SSL). (remm)
fix | Internationalization and code cleanups for APR AJP implementation. (remm)
fix | Security exception in APR AJP implementation when running with the security manager enabled. (remm)
fix | 36173: Add missing sync in FastHttpDateFormat.formatDate, submitted by Alexei Krainiouk (remm)
fix | Disable HTTP compression when sendfile is used for a resource (remm)
fix | AJP secret attribute report only at trace level. (pero)
Jasper
fix 36127: Validation compatibility with Xerces 2.7.1, submitted by Florent Benoit (remm)
Cluster
fix | Fix NPE when cluster stops (pero)
fix | 36218: MemoryRealm now support also GenericPrincipal, but JAASRealm with cluster replication still has a problem, detected by Dirk Dekok (pero)
Webapps
Tomcat 5.5.10 (yoavs)
General
add | Add JMX remote ant task to control tomcat MBeanserver via ant scripts. Ant lib is included at "server/lib/catalina-ant-jmx.jar" and documentation is added to Monitoring and Managing Tomcat How-To (pero)
fix | 34361: Integrate better antlib and import support for catalina manager tasks [Modified patch from Daniel Santos] (pero)
fix | StoreConfig save now the Connector.sslProtocol attribute. (pero)
update | Change log dir at service.bat to "$CATALINA_BASE/logs" for better multi instance support. (pero)
update | 34237: Added note and links to context and host configuration references in JNDI DataSources HowTo to aid the clueless. (yoavs)
update | 34248: Update JavaMail download instructions to include JAF. (yoavs)
update | Update to JDT from Eclipse 3.1, with support for Java 5 (remm)
update | Refactoring, redesign and extend the cluster module - Cluster can be configured as subelement from Engine and Host. - Optimized performance and reduce memory usage - Better JMX support - add a lot of JMX stats attribute for better monitoring - add a single element default cluster configuration - more config options LifecycleListener ClusterListener more than one cluster valves - better subclass support - change a lot of existing cluster API's (pero)
add | Add Apache Portable Runtime JNI wrapper and helper API (mturk)
update | Update JULI to provide support for taking over java.util.logging bootstrap configuration, and move the default properties file to ${catalina.base}/conf/logging.properties (remm)
fix | 34746: Updated catalina.properties instructions per Bill Edwards' suggestion. (yoavs)
fix | 35090: Minor documentation typo fix. (yoavs)
fix | 34931: Rewrote ROOT/index.jsp to be XHTML strict compliant, per Richard Beton's patch. (yoavs)
Catalina
fix | 20380: Access log timestamps now take account of Daylight Saving Time (DST). (markt)
add | 34220: Provide better error message when server.xml can't be located. [Modified patch from Ralf Hauser] (yoavs)
add | Add MessageListener and LifecylceListener cluster saving to storeconfig module (<Cluster ... ><ClusterListener className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" >) (pero)
fix | 33743: Add additional synchronization in webapp classloader to avoid possible race condition when defining a class (remm)
fix | 33711: Add events on passivate and activate to cleanup SSO, and recycle session objects when removing them from a manager (so that anyone keeping references to it would leak a minimal amount of memory) (remm)
update | Re-add patch causing Session.getId to throw an ISE, and make all internal components use a safe getIdInternal method (remm)
update | Store principal to be exposed for Request.getUserPrincipal inside the GenericPrincipal, to remove hacks from the JAAS realm (remm)
fix | 10385: SSI Servlet now includes better support for files that use character encodings other than the platform default.(markt)
fix | Remove CopyParentClassLoader rule, which doesn't seem to be doing anything useful anymore. (remm)
add | Provide an ServletFilter implementation of Server Side Includes (SSI). This was submitted by David Becker under 33106. (markt)
add | Add sendfile support to default servlet, with a sendfileSize configuration attribute. (remm)
update | If APR as well as Tomcat's JNI wrapper for APR are present, use APRized protocol handlers instead of the regular ones (remm)
fix | 22617: When used with an EJB container and a realm that supports the concept of an unauthenticated user (J2EE.3.4.3) BASIC authentication was always authenticating users as the unauthenticated user without giving them a chance to supply a username and password. (markt)
fix | Prevent facade objects cloning (remm)
update | Add missing CGI variables to SSI servlet. Patch submitted by Fritz Schneider. (markt)
fix | 34578: Updated JNDIRealm comment. (yoavs)
fix | 34273: Better Bootstrap warning message. [Path from Ralf Hauser] (yoavs)
update | 34675: Updated Proxy-HowTo page with Servlet API calls. (yoavs)
fix | 34546: Fix problem where the "first" Valve couldn't be removed from a Pipeline. (billbarker)
fix | Fix NPE when POST size exceeds limit defined by maxPostSize. (markt)
fix | Fix FORM authentication so POSTed parameters are not assumed to be encoded with platform default encoding. A side effect of this fix is that the bodies of POST requests that require FORM authentication are now buffered and made available after a sucessful login. (markt)
fix | 34840: Better handling of external WARs redeployment, and ignore docBase specified in context file if within the Host appBase (remm)
fix | Fix handling of symbolic links when the DefaultServlet is generating directory listings. (markt)
fix | 35769: Correct implementation of javax.naming.Context.composeName( Name, Name) in multiple places. Patch provided by Laurent Simon. (markt)
add | 34805: Add warning for suspicious security patterns,该建议来自 Ralf Hauser. (yoavs)
fix | 35819: Use getWorkPath for deleting work directory on context destroy, as suggested by Rob Steele. (yoavs)
Coyote
update | Add support for using "Smart Cards" as trust/keyStore. (billbarker)
update | Add some Mbean attributes and operations to ChannelSocket (pero)
add | Apache Portable Runtime based HTTP/1.1 protocol handler, with SSL support (remm)
add | Add support for simple file-based CRLs under JDK 1.5 (billbarker)
add | Add experimental NIO-Socket channel for the AJP/1.3 Connector (billbarker)
add | 34648: Add configuration option to enable IP-based Virtual Hosts. (billbarker)
update | Refactor the AJP/1.3 Connector to be able to handle more advanced Actions. (billbarker)
fix | Fix connector initialisation so sslProtocol is not required for SSL. (markt)
add | Add bufferSize option to the AJP/1.3 Java connector to control output buffering. (billbarker)
add | Apache Portable Runtime based AJP/1.3 protocol handler (remm)
fix | Delay reading the inital request body packet by default for the AJP/1.3 Java connector. (billbarker)
Jasper
fix | 18477: Allow symbolic links when precompiling JSPs (markt)
add | 34272: Allow specifying the Option class used by the Jasper engine, submitted by Scott Stark (remm)
add | Support for Java 5.0 in JSPs (remm)
update | Java 5 will be the source and target for JSPs when running on Java 5 (remm)
update | 34652: Add the ability to get SMAPs when precompiling, submitted by Daryl Robbins (remm)
fix | 34465: Jspc failure if there is no web.xml (remm)
fix | 35696: Make certain that release is called for custom tags when tag-pooling is disabled. (billbarker)
fix | 35386: Make useBean resources use consistent spelling, from Kurt Huwig. (yoavs)
update | 33522: Update jasper-howto to reflect use of javac switch. (yoavs)
add | 35114: Add failOnError flag to JspC, by ziweth. (yoavs)
fix | 35410: Fixed NPE in JspWriterImpl. (yoavs)
add | 35571: JspC resolved uriRoot relative to Ant project basedir, if any, as suggested by Jason Pettiss. (yoavs)
Cluster
add | Add that cluster can configure as Engine and Host element. (pero)
add | Add single cluster default configuration element - discussed at JAX 2005 conference Cluster Workshop. (pero)
fix | Fix resend GET_ALL_SESSIONS when wait ACK failed at receiver side (pero)
fix | ClusterValve now remove from container element when cluster stops and added with next start again. (pero)
add | Set timestamp only at first time inside SessionMessageImpl (pero)
add | Set timestamp from findsessions method call, when handling GET_ALL_SESSION to all SEND_SESSION_DATA and TRANSFER complete messages. (pero>
add | Drop all received message inside GET_ALL_SESSION message queue before state transfer message timestamp. (pero)
add | Cluster ping now transfer cluster domain information and DeltaManager only send and receive message from same domain members (pero)
add | JMX Support for McastService (Membership) (pero)
add | Redesign SimpleTcpCluster message receiving to ClusterReceiverBase (pero)
add | Cluster transfer all attributes to the generate session manager at addManager. Remove some unused attributes at SimpleTcpCluster and ReplicationTransmitter (pero)
update | Refactor DeltaManager: - createSession call now ManagerBase super class method - extract some long methods - send GET_ALL_SESSION with session blocks - don't sync sessions map when send all sessions (pero)
update | Add developer actions at to-do.txt (Proposal of changes) (pero)
update | Small refactorings at FastAsyncSocketSender (pero)
update | Redesign cluster message sending to lesser cpu and memory usage. Set at ReplicationTransmitter#compress=false as default. Change API from ClusterSender, ReplicaitonTransmitter, DataSender, SimpleTcpCluster (pero)
add | DeltaManager has now JMX expireAllLocalSessions and processExipre operation for better cluster node shutdown handling (usefull for testing only) (pero)
add | DataSender doWaitAckStats for better understanding wait ack problems (pero)
update | Refactor DeltaManager and add counter for cluster message send/receive message (pero)
fix | 34389:Porting Clustering fix pack to 5.5.10 code base. Remove synchonized from DataSender.pushMessage(). Very offen the complete cluster blocking after replicated a bulk of new session messages under heavy load. All cluster node standing for a lot of time and made nothing. Fix it for pooled, asynchronous and fastasyncqueue replication mode. Very bad thing, sorry! (pero)
add | Add notifySessionListenersOnReplication attribute to SimpleTcpCluster to stop notify event to SessionListener at backup nodes from create and destroy replicated session (pero)
add | Add compress attribute to ClusterSender and ClusterReceiver interface. Now compress config transfer from sender to receiver at SimpleTcpCluster. (pero)
add | Add ClusterValve interface and implement it as ReplicationValve and JvmRouteBinderValve. Now both Valves can be directly configured at server.xml Host/Cluster/Valve subelements. Also this configuration are correctly handled with the StoreConfig module. (pero)
update | Deactivate DataSender keepAliveMaxRequestCount change default to -1. Cluster replication sockets are fast and very stable! (pero)
update | Setup JvmRouteBinderValve as host valve instead context valve. Refactor the API a little bit. (pero)
fix | Don't increment open socket counter before socket is really open. Add socket open failures counter (pero)
add | Add MessageListener support to cluster server.xml element (ClusterListener) to register your own cluster message receiver (pero)
add | Add LifecycleListener support to cluster server.xml element (Listener) and notify those listener from start/stop cluster, add/remove session manager, sending fault and start/stop member (pero)
add | Add active backgroundProcess keepAlive timeout and request count socket close check at ReplicationTransmitter. Check frequency can be change with attribute processSenderFrequency (default 2). (pero)
add | Remove useless Jdk13ReplicationListener,Jdk13ObjectReader. Add SocketReplicationListener and SocketObjectReader to have nativ socket ClusterReceiver. Also extract ClusterReceiverBase superclass for SocketReplicationListener and ReplicationListener (pero)
update | Add and update some API and the cluster howto documentation (pero)
update | Refactor ReplicationValve for better understanding and small optimization (pero)
add | Starting a unit test suite for cluster module - very much todo (pero)
fix | Fix ant build.xml to direct compile at cluster module directory (pero)
fix | Fix some I18N messages, but a lot of work is waiting for fix (pero)
add | Add ReplicationValve Mbeans stats attribute getter and resetStatistics operation (pero)
Webapps
fix | 35758: Admin webapp mishandling digest attribute of JDBCDataSourceRealm. (yoavs)
add | 34250: Admin webapp Commit Changes button now asks for confirmation. (yoavs)
add | 34818: Alternating row for apps in HTML manager,该建议来自 Jeff Domeyer. (yoavs)
add | 35379: Added commons-logging to build path of manager and host-manager apps, to make them build with Jikes,该建议来自 Aaron Isotton. (yoavs)
Tomcat 5.5.9 (yoavs)
General
add | Add JULI, a java.util.logging implementation, used to provide sane defaults and configurability equivalent to Tomcat 4.0 for Tomcat 5.5 logging (remm)
docs | Add JULI documentation to the logging page (remm)
add | Add host manager webapp (remm)
add | Add ant JkStatusUpdateTask for remote status worker handling ( >=mod_jk 1.2.9) (pero)
add | 33739: Add reference to RUNNING.txt in setup.html. (yoavs)
fix | 33719: Update reference to Ant download page. (yoavs)
fix | 33883: Bad options in SSL-HowTo. (yoavs)
update | Update to MX4J 3.0.1 (pero)
update | 34139: Updated Realm-HowTo to specify JMX, Commons-Logging jars for RealmBase. (yoavs)
add | 33325: Added top-level clean target to Netbuild build.xml file. (yoavs)
update | 33755: Clarified Postgresql JNDI datasource example. [patch submitted by Tom Witmer] (yoavs)
Catalina
fix | Remove some instances of expanded folder removal (remm)
fix | Don't call mkdirs if we're not going to save the configuration in StandardContext (remm)
fix | Fix context classloader binding during loader initialization (it was set to null before) (remm)
fix | The webapp logger should only be retrieved when the context classloader is set to the webapp's classloader (remm)
fix | 34170: Add back retry logic in JDBC realm in case of a connection failure (remm)
fix | 22041: Support dynamic proxies as session objects. (markt)
fix | Fix logger names for wrappers (remm)
fix | 34006: If antiResourceLocking was used, HostConfig considered the path as external, and web application resources were not correctly removed or tacked; also simplify the code a lot (remm)
fix | 34016: Save and restore docBase when using antiResourceLocking, for compatibility with the admin webapp (remm)
add | 33636: Set lastModified attribute when expanding WAR files. (yoavs)
add | 32938: Allow Salted SHA (SSHA) passwords in JNDIRealm. (yoavs)
add | 31288: Allow SMTP authentication for JNDI MailSessionFactory. (yoavs)
update | Harmonize processing of the context.xml defaults with the way web.xml is processed (remm)
fix | Ignore ';' if it is in the query string (remm)
fix | private to protected for the webapp classloader (remm)
fix | Improve logging of filters and listeners startup errors (remm)
fix | 33774: Retry once in JNDI realm authenticate failure regardless of the exception message (remm)
fix | 33961: Don't encode '~' in context paths (remm)
fix | 32866: Propagate distributable property from context to manager (yoavs)
fix | 32867: Reset distributable attribute in context for clean reload handling (yoavs)
update | Fix some RealmBase/JNDIRealm log.isXXXEnabled (pero)
fix | 34161: Harmonize StandardContext.stop with ContainerBase.stop (remm)
Coyote
fix | 33971: Set remoteHost to null when Apache doesn't send one. (billbarker)
fix | Fix calculation of threadRatio for the ms thread pool, and fix setting the updated timeout value (remm)
update | Update the ms thread pool so that we allocate a worker before accepting a new socket, and wait a little if the pool is exhausted; this should make low maxThreads values work a lot better (remm)
update | 33857: Update information on automatic mod_jk configuration in Apache-HowTo (yoavs)
fix | Fix sync block placement in Mapper.addContext (remm)
fix | 32741: Fix spelling of "committed" [patch from Ben Souther] (yoavs)
fix | 34133: Make setHeader clear multi-valued headers (billbarker)
Jasper
fix | 34034: Jasper does not respect external entities (billbarker)
fix | 33810: Incorrect recycling of BodyContent if close is called (remm)
update | Per instance loggers in Jasper (remm)
Cluster
fix | Fix JvmRouteBinderValve primary failover attribute to org.apache.catalina.cluster.session.JvmRouteOrignalSessionID (pero)
fix | Change attribute name waitForAck to sendAck at ReplicationListener (pero)
add | Integrate new fastasyncqueue cluster sender mode. Support queue size limitation, get all queued objects and send it to the backup node, no queue thread lock contention under high replication load, submitted by Rainer Jung (pero)
add | Add compress attribute to Sender and Receiver to transfer data uncompressed. At high cluster load this option consume lesser cpu and memory. Implement the compress handling to ReplicationTransmitter, ReplicationListener, XByteBuffer and Jdk13ReplicationListener (pero)
add | Add doProcessingStats to synchronous, asynchronous and fastqueueasync sender modes to get min, avg, max processing times as IDataSender JMX MBeans (pero)
fix | TcpThreadPool use constant ACK byte array instead create new 3 byte buffer for every message ack (pero)
update | Refactor ReplicationTransmitter and ReplicationListener (pero)
update | add getCatalinaCluster() to ClusterReceiver and SimpleTcpCluster (pero)
update | Update the Api documentation (pero)
Webapps
update | Use the standard struts taglib URIs in admin JSPs. (billbarker)
add | Add more host parameters to create new host with host-manager (pero)
fix | 34033: Fix quoting related bugs (remm)
fix | 33713: Add Struts init code in frameset.jsp as well (remm)
Tomcat 5.5.8 (yoavs)
General
fix | 33204: Fixed SSL HowTo page. (yoavs)
fix | 33351: Fix silent uninstallation. (remm)
fix | 33489: Missing space in uninstaller message. (yoavs)
Catalina
fix | Unregister host mbean and all context mbeans at remove a host, s. StandardHost.destroy() and MBeanFactory.createStandardHost/removeHost(,) detected by Thorsten Kamann (pero)
fix | make it possible to restart connector, now serversocket recreated after stop,start (pero)
fix | change mbean names from Mapper and ProtocolHandler to connector naming style (pero)
update | Add some log.isXXXEnabled (pero)
fix | Deregister MapperListener after remove connector (pero)
fix | Remove host only at own domain with same name at all services, detected by Thorsten Kamann (pero)
fix | 33187: Remove any logging of the password in the JAAS realm, submitted by Andrew Jaquith (remm)
fix | 33033: Don't do anything to the response in the ErrorReportValve if data has already been written (remm)
update | Add charset support for the URLs used by the tasks, to remove deprecation (remm)
fix | 26135: Workaround for memory leak when reloading Struts based web applications by clearing the bean instrospector cache of the JVM on classloader stop, submitted by Tobias Lofstrand. (remm)
fix | Ensure that if CLASSPATH is declared on startup - it is not used. (funkman)
fix | Add back use of deployOnStartup in HostConfig (remm)
docs | Ant tasks docs patches, submitted by Gabriele Garuglieri. (remm)
update | Use NIO for the raw copying operation, as it is faster (a little under 30%), and decreases a little the impact of antiResourceLocking. (remm)
fix | 33357: Fix connection leaks with the DataSourceRealm, as well as improve efficiency, submitted by Dominik Drzewiecki. (remm)
update | Improve a little logging of servlet exceptions, which should all log the root cause. (remm)
update | Add new Manager.createSession(sessionId) method, allowing the client to "specify" the session id which should be used using a cookie when using emptySessionPath="true". This fixes session tracking in this case. (remm)
fix | 33368: Fix memory leak in swallowOutput feature which occurred when the thread pool size is reduced, submitted by Rainer Jung. (remm)
fix | StoreConfig: can't save cluster Membership element (pero)
add | StoreConfig: suppress default jkHome attribute at connector (pero)
add | StoreConfig: Save new dymanic properties from ReplicationTransmitter (pero)
fix | 33463: Remove attributes after context destroy. (remm)
fix | 33572: context.xml should be a redeploy resource, and add prioritization for redeploy resources. (remm)
Coyote
fix | PoolTcpEndpoint recreate ServerSocket after start,stop,start connector (pero)
update | Add some log.isXXXEnabled (pero)
add | JkMX: make log4j mbean configurable with attribute log4jEnabled (pero)
fix | When Tomcat runs on Windows and IE is uploading data to the server, the first read must be at least 8KB, otherwise upload speed is extremely low, submitted by Noel Rocher (remm)
Jasper
fix | 33223: pageContext.forward and jsp:include result in StringIndexOutOfBoundsException (luehe)
fix | 33373: Fix handling of context classloader in jspc (remm)
fix | 33538: Ignore example and tag-extension elements in TagLibraryInfoImpl. (yoavs)
fix | 33539: Better error message when an unknown element is encountered in the tag file. (yoavs)
fix | 33219: Minor JspServletWrapper code cleanup. (yoavs)
Cluster
fix | Add instance based ReplicationValve statistics to Mbean descriptor (pero)
fix | Better I18N support to cluster session and tcp classes (pero)
add | Support optional primaryIndicator at ReplicationValve to mark that request processing to existing session is at primary cluster node. Easy failover detection, when mark is not at configurable primaryIndicator attribute, submitted by Rainer Jung (pero)
update | Refactor all implementation from interface IDataSenders (pero)
add | Add some usefull attributes and operations to the all sender MBeans. (pero)
add | Add keepAlive and waitForAck handling to AsyncSocketSender and factor out a DataSender base class.(pero)
add | ReplicationTransmitter: Enable and Disable autoreconnect sender and waitForAck. (pero)
add | ReplicationTransmitter: transfer all properties to socket sender from server.xml configuration. (pero)
Webapps
fix Fix create and remove Host for Admin app. (pero)
Tomcat 5.5.7 (remm)
General
add | Add installer for mod_jk on IIS. (mturk)
add New store config module for better server.xml saving support.
Add <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener" /> to your server.xml (pero)
update | 32081: Remove the JDK requirement from the Unix scripts, submitted by Ben Souther (remm)
fix | 32953: SERVLETAPI: XSS Issues, submitted by Mark Thomas (jfarcand)
update | Update to commons-digester 1.6, JDT 3.0.1, MX4J 2.1.0, Struts 1.2.6 (remm)
Catalina
update | First integration at StoreConfig to StandardServer (pero)
fix | 32714 : Don't make the AccessLogValve final (funkman)
fix | 32694: Fix bad code to make docBase path aboslute in antiLocking method. (remm)
fix | 32713: Fix resource-env-ref handling. (remm)
fix | 31201: Improve i18n support in DefaultServlet. This was causing problems with JSP include actions and static files. (markt)
fix | Add some log.isXXXEnabled to o.a.c.core.StandardHost StandardEngine, StandardService (pero)
add | Feature addition to add Redirector and failOnError support for all Catalina Ant tasks, submitted by Gabriele Garuglieri (remm)
fix | 31198: Fix FORM and DIGEST authentication for non-ASCII usernames and passwords. (markt)
fix | Reimplement charset mapper (remm)
fix | Add logging of exception which could occur when retrieving the password in JDBCRealm (remm)
fix | 25889: Don't execute queries twice, submitted by Tom Anderson (remm)
fix | 32832: request.getSession(false) fails to return null (luehe)
fix | 28222: request.getRequestURL() in forwarded jsp/servlet returns original url rather than new url as per SRV8.4 (markt)
fix | 33157: Fix handling of the buffer length for basic authentication parsing (remm)
Coyote
fix | 32708: Better handling of bad encoding with the string cache. (remm)
fix | 32781: Fix bad initialization of the "scheme" field of the request object, which would cause getScheme to return "http" for the first request. (remm)
fix | Content length should be ignored if there is chunking (remm)
fix | Remove most deprecation problems for the AJP connector (remm)
Jasper
fix 32746: Avoid JAR locking when loading classes and improve loading performance by taking advantage of caching, submitted by Dominik Drzewiecki. (remm)
Cluster
fix | correct JvmRouteSessionIDBinderListener MBean name to <domain>:type=Listener,name=JvmRouteSessionIDBinderListener,host=<host> (pero)
add | JMX support to SimpleTcpCluster, ReplicationTransmitter and all senders (pero)
Webapps
fix | Fix the webDAV servlet so it can be used via any arbitrary mapping (eg /webdav/*) to edit the contents of a web application. (markt)
fix | 32729: Stop is optional and may fail, so it needs to be in a separate try/catch (remm)
update | Remove the remove method of the manager servlet, and use the undeploy method instead (remm)
fix | 32777: Fail if application isn't configured properly, submitted by Gabriele Garuglieri (remm)
fix | 32771: Cannot undeploy/deploy misconfigured app after tomcat startup, submitted by Gabriele Garuglieri (remm)
fix | 28867: Correct manager documentation to document correct way to reference the ROOT context. Submitted by Stephane Bailliez. (markt)
fix | 33085: Add support for setting privileged attribute of context to admin webapp. (markt)
fix | 33117: Fix Open bugs link broken on default homepage. Patch supplied by Sander Temme. (markt)
fix | Improve javadoc generation for Catalina. (remm)
Tomcat 5.5.6 (yoavs)
General
update | 32532: updated logging documentation. (yoavs)
update | 32382: Index page and packaed WAR for sample webapp. (yoavs)
fix | 32603: Updated host.xml to reflect appBase resolution. (yoavs)
Catalina
fix | Add child to the map of the parent before starting it. (remm)
fix | Decouple usage of the scheme and secure attributes from enabling SSL. (remm)
fix | 32502: memory leak in DigestAuthenticator. (yoavs)
fix | 28709: javax.servlet.http.HttpServletRequest.isRequestedSessionIdValid() returns true for an invalidated session. (luehe)
fix | 32137: Possible thread-safety issue in RealmBase. (yoavs)
Coyote
fix | 32585: Better handling for content length greater than Integer.MAX_VALUE in response. (markt)
update | Allow ApacheConfig and friends to live under an Engine. (billbarker)
update | Syncronize access to the Jk Request registration count. (billbarker)
update | Speed the MsgContext on its way to GC. (billbarker)
fix | Keep correct thread counts in Thread pool when thread ends in an exception (billbarker)
Jasper
update Updated Jasper-HowTo section on using Jikes, changed conf/web.xml JSPServlet to refer people to Jasper-HowTo so that we don't have these instructions in two places. (yoavs)
Webapps
fix 32505: Fix handling of an empty context parameter (which occurred every time the HTML manager was used to deploy a local war without specifying also a context file). (remm)
Tomcat 5.5.5 (yoavs)
General
update | 32235: Sync conf/web.xml MIME types with Apache httpd. (yoavs)
fix | 31132: Better -x/-r support for OS/400 in startup scripts. (yoavs)
update | 22679: Added misc note on accessing session ID to SSL-HowTo. (yoavs)
update | 32249: Updated logging documentation. (yoavs)
update | 32282: Modify Windows Uninstaller to only remove webapps/ROOT and webapps if user asks to remove everything. (yoavs)
fix | 32371: outdated introduction.xml page. (yoavs)
fix | 32373: outdated installation.xml page. (yoavs)
update | 32454: amended JNDI documentation for JavaMail/JavaActivationFramework usage. (yoavs)
Catalina
fix | 32130: Add safety check to FileStore#keys method. (yoavs)
update | 32276: Add developer info to Realm How-To. (yoavs)
fix | 32082: Added protected getPrincipals method to MemoryRealm for easier extension. (yoavs)
fix | 32023: CGIServlet fails to handle post message with multipart/form data. (yoavs)
fix | 32269: JNDIRealm fails with InvalidNameException to authenticate users if LDAP distinguished name (DN) contains slash or double quote character(s). (yoavs)
fix | Move processExpiresFrequency check to ManagerBase and reflect change to all subclasses (StandardManager, PersientManagerBase, DeltaManager). (pero)
update | Add DIGEST authentication support to the JDBC and DataSource realms. Supports both digested and cleartext passwords. (markt)
fix | 32429: CGIServlet calculates number of lines received on stderr incorrectly. (markt)
fix | 32431: Fix typo in code that passes data to CGI script. (markt)
fix | 32430: Class cast exception in toString() method within CGI servlet. (markt)
fix | Add some log.isXXXEnabled checks at StandardContext and HostConfig (pero)
fix | Remove the last DefaultContext artifacts (pero)
fix | 32031: using createConnector with "http" protocol (remm)
fix | Add configFile attribute in JMX descriptors (remm)
fix | Fix autodeployer handling of a war which includes a /META-INF/context.xml, so that it is correctly registered and can be reloaded correctly (remm)
fix | 32137: Use of MessageDigest should be synced in DIGEST (remm)
fix | Add info log when the autodeployer reloads a context (remm)
Coyote
update | Small HTTP/1.1 optimizations: replace usage of Strings with constant byte arrays, and simplify the code converting Strings to bytes (remm)
update | Greatly reduce the amount of recycle method calls on the buffers (remm)
fix | Add null OName check for Request unregistration in Jk, to remove exception under JDK 1.5. (billbarker)
fix | 32292: Don't send keep-alive header when the protocol can't be parsed. (billbarker)
Jasper
update | Updated JspC usage messages to include recently added configurable parameters. (yoavs)
fix | 32330: JspC changes context classloader. (yoavs)
Cluster
add | JvmRouteBinderValve/JvmRouteSessionIDBinderListener to bind cluster session after primary node failure at first calling backup node. This was an option to have session stickyness after cluster node crashed. Work only with JESSIONID cookies. (pero)
add | Better log support to DeltaManager to see detail information at debug level. (pero)
fix | Fix FarmWarDeployer based on new HostConfig deployer. (pero)
fix | FarmWarDeployer controlled WarWatcher with engine backgroundProcess call. Added processDeployFrequency attribute to Deployer server.xml element. (pero)
Webapps
update | 32019: Remove maxlength=64 restriction on env entry values in admin webapp. (yoavs)
fix | Fix various problems in realm docs, submitted by Phil Mocek. (remm)
update | Add log4j docs submitted by Allistair Crossley. (remm)
fix | 32381: Fix problem where EL expression is used as a place holder in the admin webapp. Submitted by Allistair Crossley. (billbarker)
Tomcat 5.5.4 (yoavs)
General
update | 31671: Update web.xml files to 2.4 schema where applicable. (yoavs)
update | 31912: Add PNG and CSS file types to replication filter default. (yoavs)
Catalina
fix | Add processExpiresFrequency to PersistentManagerBase and made some small JDBCStore optimizations (pero)
fix | Register JSP monitoring mbean for each servlet that declares a jsp-file in web.xml. (luehe)
fix | 31578: Update Manager configuration documentation. (yoavs)
fix | 31273: Add support for derefaliases in JNDIRealm. (markt)
fix | 31623: Better OS400 support in setclasspath.sh. (yoavs)
add | Extend background processing to most container components. (remm)
fix | Remove all MX4J related code. (remm)
fix | Update JAR list in TldConfig. (remm)
add | Register datasources with JMX. With DBCP, this is enough to provide JMX management and monitoring. It might work well with many other data sources which might not register themselves in JMX but do expose their stuff in a java bean fashion. (remm)
update | Add the ability to force session cookies to be set to the root path "/". This should not be used on large servers, otherwise tons of cookies may be sent. (remm)
fix | Workaround for client socket exceptions occurring while running a CGI, which could cause the external process to hang. (remm)
update | Optimize session cookie IDs conversion to String, since this is an unavoidable and uncacheable operation. (remm)
fix | Add explicit error message if temp dir does not exist, and remove useless calls to initDirs. (remm)
add | Add an optimized access log valve, supporting hardcoded support for the common and combined patterns, and doing a majority of its write-to-logfile operations asynchronously. (remm)
update | Register an MBean to monitor and manage the StringCache, and allow invoking the reset operation. (remm)
fix | 31677: Log warning if work dir for context can't be determined. (yoavs)
fix | 31903: Fix condition which seems to not have been properly updated after adding entry.binaryContent = null a little below, submitted by Joe Zhou. (remm)
fix | Prevent silent NPEs during StandardContext.start dealing with JMX registration of realm, submitted by Keith Wannamaker. (remm)
fix | 31592: Support other encodings for digests. (yoavs)
update | 31739: Minor realm-howto and AJP connector doc updates. (yoavs)
fix | 31753: Minor inconsistency between JDBC and DataSourceRealm#authenticate. (yoavs)
update | 31683: Minor clarifications to realm documentation. (yoavs)
Coyote
fix | Improve i18n in TCP endpoint, and add a better error message when an exception occurs in setSocketOptions. (remm)
fix | 31663: Use interval field as the delay for monitor thread. (remm)
fix | Remove bad shutdown logic for ms pool strategy. (remm)
fix | Sync with Cookie, by adding ' ' as a special char. If a special char is present, the string will be quoted. If the client doesn't support it, the String will no be quoted anyway and no IAE will be thrown. (remm)
add | Add an optional String cache for ByteChunk.toString and CharChunk.toString. The cache is unsynchronized during most of its operation, and is static after a training period. An operation is provided to allow resetting the cache. (remm)
update | String caching is enabled by default for ByteChunk. (remm)
fix | 31090: Use a URL encoded path when setting session cookies. (remm)
add | Add getAttributeName() to ProtocolHandler to get all attributes at runtime (pero)
Jasper
update Exposed compilerSourceVM and compilerTargetVM options to JspC. (yoavs)
Cluster
fix | DeltaManager and SimpleTcpReplicationManager generate double jvmRoute (pero)
add | Add some missing Getters and log.isXXXEnableds (pero)
Webapps
fix | 31707: Broken JavaScript confirmation in HTML manager. (yoavs)
fix | Remove hard-coded admin context path from admin's banner.jsp. (yoavs)
update | Major connector docs update. (remm)
fix | 31732: Fix Japanese localization of Manager's list output. (yoavs)
Tomcat 5.5.3 (yoavs)
General
fix | 30568: Incomplete setup.html documentation for launching jsvc. (yoavs)
update | Repackage naming features. (remm)
fix | Fix deployer packaging. (remm)
fix | Fix embed packaging. (remm)
Catalina
fix | Fix memory leak when Security Manager is turned on. (jfarcand)
fix | When checking status codes for error handling, only check if Response.isError() is true. This way, users may use setStatus() to set their own error status without having the error page invoked. (in which case, the user should've use sendError()) (funkman)
update | Remove Digester code for Xerces workaround. (jfarcand)
fix | Give proper permission to the balancer app when running under the security manager. (jfarcand)
fix | 30869: Make sure JAAS realm name is legal. (yoavs)
update | md5Helper, md5Encoder, and normalize are used by WebdavServlet, not DefaultServelt so move them into WebdavServlet.
fix | 31277: Clarified automatic application deployment section of Host configuration page. (yoavs)
fix | 28631: JAASRealm enhancements to support custom user and role classes use Commons-Logging. (yoavs)
fix | 31364: Missing resource in org.apache.catalina.core.LocalString.properties. (yoavs)
fix | 31362: Missing -Xdebug in catalina.bat when launching with JPDA and Security. (yoavs)
fix | 31356: Duplicates not counted in session generation. (yoavs)
fix | 30949: Make sure ApplicationDispatcher unwraps request/response even if include error occurs. (yoavs)
fix | Fixed StandardContext.getStartTime() to return actual start time/date instead of time (startupTime) it took to start context. (luehe)
update | getRequest/getResponse should return the most relevant interface, to avoid casts. (remm)
update | Add check for directory before considering something is a compressed WAR. (remm)
docs | Update the connector documentation. (remm)
fix | When parsing a context file, ignore the "path" attribute: the only place where it is acceptable is in server.xml. (remm)
fix | Digester handling fixes: always call reset in a finally block after using a digester. (remm)
update | Remove many fields from Connector, and tie the creation of the Connector to the creation of the protocol handler. (remm)
update | Remove package triggers from the classloader, which seem useless when using Java 5. (remm)
fix | Realms will now use set attribute to set themselves in their container when using JMX. (remm)
fix | Fix JMX related operations with the Connector. (remm)
fix | Fix save-to-XML for naming resources. (remm)
fix | Remove authenticator "debug" attributes from the descriptors. (remm)
update | Refactor org.apache.catalina.deploy.ContextXXX to use new super class ResourceBase. (pero)
fix | Enable Connector.findLifecycleListener that we can listen start/stop Connector events and save the listener to xml. (pero)
update | Remove Watchdog references, as it is no longer used. (yoavs)
fix | 31511: Don't call setenv.bat if not found, in *using-launcher scripts. (yoavs)
fix | 31549: Add name to WebappClassLoader's stopped message. (yoavs)
Coyote
update | Allow customized server header for Standalone. (funkman)
fix | Digester.reset now removes the error handler, the root and calls clear, to prevent any memory leak. (remm)
update | Remove useless stuff in digester. (remm)
update | In HTTP, add a utility method to convert strings to byte arrays, and output the server header directly as bytes. (remm)
add | Add a master slave thread pool based on the code from Tomcat 4.0. It is less exotic than the default one, and might fare better on some picky systems, such as Redhat 9. The two threadpools will likely be removed once we use the Java 5 API, although more investigation is needed. (remm)
fix | Fix issue with getProperty in IntrospectionUtils. (remm)
update | Remove attribute translation for SSL in the HTTP protocol handler: it will now be done in the Catalina Connector class. (remm)
fix | Fix handling of the "timeout" attribute of the HTTP protocol handler. (remm)
Jasper
fix | 31171: Wrap to avoid ClassCastException in PageContextImpl. (yoavs)
fix | 31257: Added specification of endorsed dirs if forking. Note that this is fairly useless for now in 5.5 since it uses JDT and not javac by default. (yoavs)
docs | Document new Jasper defaults, and update the production configuration. (remm)
fix | Copied XML encoding detection logic into JASPER, so we're no longer dependent on Xerces. (luehe)
fix | Fix cosmetic issue where extra CRLF would be inserted during each precompilation in web.xml. (remm)
update | Allow configuring the interval following a compilation during which a JSP will not be checked for modifications. (remm)
fix | 31465: Ensure that the compiler reads the .java file using the same encoding as that with which it was written. (markt)
fix | 31510: Null out response in JspWriterImpl#recycle to aid in JBoss memory leak. (yoavs)
Cluster
update | Added flag to the cluster (notifyListenersOnReplication) to enable/disable the notifications of attribute/context listeners upon replication of a session delta Works only with the DeltaManager (fhanik)
update | Added flag to the cluster (Cluster/Sender/ackTimeout) to set the timeout in milliseconds for a synchronous request to go through, defaults to 15000ms (fhanik)
Webapps
fix | 29485: I broke the HTML manager when adding JavaScript confirmation, fixed now ;) (yoavs)
fix | 31058: Ensure StatusTransformer escapes query string for XML. (yoavs)
update | Added contexts' start time (available from 'startTime' MBean attribute of StandardContext) to status page (luehe)
fix | 31264: the deploy task should now behave correctly. (remm)
update | Refactor the manager servlet to make calls to the deployer more robust. (remm)
fix | Use the more robust String.valueOf in the form edit action of the connector. (remm)
Tomcat 5.5.2 (yoavs)
General
fix The installer will now use the system's JRE. (remm)
Catalina
fix | Fix URL generation for classloaders on Windows, causing common/classes and shared/classes to be unusable (remm)
fix | 31110: Fix resource packaging bug for servlets (remm)
fix | Fix 5.5 regression where going through the authenticator would create a session each time. (remm)
fix | Fix classname of the connector in Embedded, and remove the socket factory. (remm)
Coyote
fix | Redo server header handling again. (remm)
update | Cleanup a little access to the headers using a local variable and use setValue for Server and Date headers. (remm)
Jasper
fix | Remove maxTagNesting and curTagNesting since they are unused. (funkman)
fix | Fix tag files handling with JDT, which were ususable, and refactor the lifecycle handling of the page loader. (remm)
Cluster
Webapps
Tomcat 5.5.1 (yoavs)
General
update | Tomcat 5.5 可通过 JDK 5.0.构建 (yoavs)
fix | 完善Windows 安装版本. (mladen, remm)
update | 移除对Jakarta regexp的依赖 . (remm)
Catalina
fix | 允许重载默认的上下文环境文件位置,类似默认的web.xml. (remm)
update | Backport if-else logic for SSI servlet from 4.1 (funkman)
fix | 移除digester 规则中的 DefaultContext元素. (remm)
fix | 修正对 ResourceLink 的处理. (remm)
fix | Modify the auto deployer to get along with contexts which are statically defined in server.xml. (remm)
fix | Externalize constant strings defining the location of deployment related resources. (remm)
fix | 31052: BeanFactory swallows root cause of exception. (yoavs)
fix | Allow using deploy Ant task with just config attribute, submitted by Michael Schuerig. (remm)
add | Added longest time an expired session had been alive to set of monitorable session manager attributes. (luehe)
add | Added average time an expired session had been alive to set of monitorable session manager attributes. (luehe)
fix | Clear a reference in the digester where a context would be referenced for more time than it needed, until the next context deployment operation. (remm)
Coyote
fix 31018: Race condition in SystemLogHandler. (yoavs)
Jasper
fix | 使用 "compiler" 参数允许指定Ant可使用的编译器. (remm)
fix | 忽略 JDT 编译器的警告. (remm)
add | 新增 compilerTargetVM 选项, "1.4" 为默认值. (yoavs)
Cluster
fix 修正新增的集群阀, 实现真正的 session 复制. (fhanik)
Webapps
update | Major documentation update with current Tomcat 5.5 changes. (remm)
update | Added JavaScript confirmation dialog to "dangerous" Manager servler links. (yoavs)
Tomcat 5.5.0 (yoavs)
General
update | 大量的更新和修正JavaDocs. (yoavs)
update | 在J2SE 5.0 (aka JDK 1.5)上设计并测试Tomcat. (everyone)
update | 绑定 Eclipse JDT (新的依赖) 允许 Tomcat 只在 JRE 上即可运行, 也就是说. JDK 不再是必需的. (remm)
update | Repackage commons-dbcp and its dependencies as a sigle smaller WAR, with renamed packages. (remm)
update | Removed dependencies on commons-digester, commons-beanutils, and commons-collections. The relevant digester functionality is now merged in tomcat-util. (remm)
Catalina
update | 移除 org.apache.catalina.Logger 的使用, 全面增加commons-logging 的使用. (remm)
update | 重构类加载器的代码来更好的处理JAR和一般资源锁定. (remm)
update | Written JMX-related code to play nicely with J2SE 5.0 built-in JMX abilities. (remm, costin)
update | Extensively profiled and optimized the server startup performance as well as the request mapping and processing pipeline. (remm)
update | The container will now always process a /META-INF/context.xml resource, unless the webapp has a specified external context file. (remm)
update | New default configuration mechanism for web applications, replacing DefaultContext. This uses a shared context file located in conf/context.xml. (remm)
update | Revamped deployer, alloying full hotdeploy (note: on Windows, this requires the anti file locking features). (remm)
update | Remove verbosity from the JNDI resources configuration, by allowing arbitrary attributes on the Resource element. (remm)
update | 更简单的 阀 接口, to allow smaller stack traces and reducing the amount of method calls. (remm)
Coyote
Jasper
update | Eclipse JDT 现在作为Jasper 默认的 Java 编译器 . 源代码依赖现在通过容器的类加载器进行载入, 编译速度提高了. (remm)
update | Jasper 的开发模式 现在对大量访问的页面提供了可接受的性能优化. 预编译 JSPs 十分高效快速. (remm)
Cluster
Webapps


Apache Tomcat 5.5 Servlet/JSP 容器 - Class Loader HOW-TO

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Class Loader HOW-TO
Quick Start

程序开发员和部署员要决定在哪里放置类和资源文件以便它们可以被网络程序使用, 95%的这些决定由下面的这些条例覆盖:

  • 对于某个网络程序所特有的类和资源,把这些未包装的类和资源放置在你的网络程序档案/WEB-INF/classes目录下面，或者把包含这些类和资源的JAR文件放置在你的网络程序档案/WEB-INF/lib目录下面。
  • 对于必须被所有网络程序所共享的类和资源，把未包装的这些类和资源放置在$CATALINA_BASE/shared/classes下面，或者把包含这些类和资源的JAR文件放置在$CATALINA_BASE/shared/lib下面。
Overview

象许多服务器程序一样，Tomcat 5安装各种不同类型的类loaders(那就是，实现java.lang.ClassLoader的类)来允许容器的不同部分，以及运行在容器上的网络程序，可以访问不同贮存部分的类和资源。这个机制是用来提供Servlet Specification, 2.4版——特别是9.4 和 9.6章节里定义的功能。

In a J2SE 2 (that is, J2SE 1.2 or later) environment, class loaders are arranged in a parent-child tree. Normally, when a class loader is asked to load a particular class or resource, it delegates the request to a parent class loader first, and then looks in its own repositories only if the parent class loader(s) cannot find the requested class or resource. The model for web application class loaders differs slightly from this, as discussed below, but the main principles are the same.

当Tomcat 5启动后，它产生一组类装载器，这些类装载器被组织成如下的父子关系，父类装载器在子类装载器之上：

Bootstrap
|
System
|
Common
/ \
Catalina Shared
/ \
Webapp1 Webapp2 ...

每一个类装载器的特征，包括可被使用的类和资源的来源，在下面的章节有详细讨论。

Class Loader Definitions

如上面的图表显示，Tomcat 5在它启动时产生如下的类装载器：

  • Bootstrap - 这个类装载器包含Java虚拟器提供的基本的运行时间类，加上在System Extensions 目录( $JAVA_HOME/jre/lib/ext )里的JAR文件中所有的类。注意——有些Java虚拟器(JVMs)也许把它作为不止一个类装载器用，或者作为一个类装载器用。
  • System - 这个类装载器通常是以CLASSPATH环境变量的内容为基础来初始化的。所有的这些类既可被Tomcat内部classes使用，又可被网络程序使用。不过，标准的Tomcat 5启动脚本( $CATALINA_HOME/bin/catalina.sh or %CATALINA_HOME%\bin\catalina.bat )完全忽略了CLASSPATH环境变量自身的内容，相反从下面的贮藏室去建造系统类装载器：
    • $CATALINA_HOME/bin/bootstrap.jar - 包含用来初始化Tomcat 5服务器的main()方法，以及它所依赖的类装载器执行类。
    • $JAVA_HOME/lib/tools.jar - 包含用来把JSP页面转换成servlet类的"javac"编译器。
    • $CATALINA_HOME/bin/commons-logging-api.jar - Jakarta commons 记录应用程序界面。
    • $CATALINA_HOME/bin/commons-daemon.jar - Jakarta commons daemon API.
    • jmx.jar - JMX 1.2 执行。
  • Common - This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications. Normally, application classes should NOT be placed here. All unpacked classes and resources in $CATALINA_HOME/common/classes, as well as classes and resources in JAR files under the $CATALINA_HOME/commons/endorsed, $CATALINA_HOME/commons/i18n and $CATALINA_HOME/common/lib directories, are made visible through this class loader. By default, that includes the following:
    • commons-el.jar - Jakarta commons el, 执行Jasper使用的表达语言。
    • jasper-compiler.jar - The JSP 2.0 编译器。
    • jasper-compiler-jdt.jar - The Eclipse JDT Java compiler.
    • jasper-runtime.jar - The JSP 2.0 运行时间。
    • jsp-api.jar - The JSP 2.0 应用编程界面(API)。
    • naming-common.jar - 被Tomcat 5用来代表in-memory命名contexts的JNDI实现。
    • naming-factory.jar - 被Tomcat 5用来决定企业资源索引(EJB, connection pools)的JNDI实现。
    • naming-factory-dbcp.jar - Jakarta commons DBCP, providing a JDBC connection pool to web applications. The classes have been moved out of their default org.apache.commons package.
    • naming-java.jar - Handler for the java: namespace.
    • naming-resources.jar - The specialized JNDI naming context implementation used to represent the static resources of a web application. This is not related to the support of the J2EE ENC, and cannot be removed.
    • servlet-api.jar - The Servlet 2.4 API.
    • tomcat-i18n-**.jar - Optional JARs containing resource bundles for other languages. As default bundles are also included in each individual JAR, they can be safely removed if no internationalization of messages is needed.
  • Catalina - 这个类装载器被初始化后包含执行Tomcat 5自身必须的所有类和资源。这些类和资源完全可被网络程序使用。所有的在$CATALINA_HOME/server/classes里未包装的类和资源，以及$CATALINA_HOME/server/lib下JAR文件里的类和资源，通过这个类装载器可被使用。在默认的情况下，有下面的这些：
    • catalina.jar - Tomcat 5的执行Catalina servlet容器部分。
    • catalina-ant.jar - Some Ant tasks which can be used to manage Tomcat using the manager web application.
    • catalina-optional.jar - Some optional components of Catalina.
    • commons-modeler.jar - A model MBeans implementation used by Tomcat to expose its internal objects through JMX.
    • servlets-xxxxx.jar - 与每个内部servlet相关联的类，这些内部servlet提供一部分Tomcat的功能。它们是分离开的，这样一来，如果相应的服务不需要的话，它们就可以完全被删除，或者它们需要特别的安全管理员许可。
    • tomcat-coyote.jar - Coyote API.
    • tomcat-http11.jar - 独立的Java HTTP/1.1 连接器。
    • tomcat-ajp.jar - Classes for the Java portion of the AJP web server connector, which allows Tomcat to run behind web servers such as Apache and iPlanet iAS and iWS.
    • tomcat-util.jar - 一些Tomcat必需的Utility类。
  • Shared - 这个类装载器是放置被所有网络程序共享的类和资源的地方(除非Tomcat内部classes也需要访问它们，要是这样，你就得把它们放在Common这个类装载器)。所有的在$CATALINA_BASE/shared/classes 里未包装的类和资源，以及$CATALINA_BASE/shared/lib 下JAR文件里的类和资源，通过这个类装载器可被使用。如果多个Tomcat实例使用同样的$CATALINA_BASE环境变量运行，那么这个类装载器的储藏室就和$CATALINA_BASE有关，而不是和$CATALINA_HOME有关。
  • WebappX - 为在单个Tomcat 5实例中被部署的每一个网络程序所产生的类装载器。在你的网络程序档案/WEB-INF/classes目录里所有的未包装的类和资源，以及网络程序档案/WEB-INF/lib目录下JAR文件里的类和资源，可被这个Webapp里的程序使用，而不能其他程序使用。

As mentioned above, the web application class loader diverges from the default Java 2 delegation model (in accordance with the recommendations in the Servlet Specification, version 2.3, section 9.7.2 Web Application Classloader). When a request to load a class from the web application's WebappX class loader is processed, this class loader will look in the local repositories first, instead of delegating before looking. There are exceptions. Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in J2SE 1.4+), the J2SE 1.4 endorsed feature can be used (see the common classloader definition above). Last, any JAR containing servlet API classes will be ignored by the classloader. All other class loaders in Tomcat 5 follow the usual delegation pattern.

因此，从一个网络程序的角度来看，类和资源的装载以这样的顺序在下列贮藏室进行查找：

  • 你的JVM的Bootstrap类
  • 系统类装载器类(描述如上)
  • 你的网络程序的/WEB-INF/classes
  • 你的网络程序的/WEB-INF/lib/*.jar
  • $CATALINA_HOME/common/classes
  • $CATALINA_HOME/common/endorsed/*.jar
  • $CATALINA_HOME/common/i18n/*.jar
  • $CATALINA_HOME/common/lib/*.jar
  • $CATALINA_BASE/shared/classes
  • $CATALINA_BASE/shared/lib/*.jar
XML Parsers and J2SE 1.4

Among many other changes, the J2SE 1.4 release packages the JAXP APIs, and a version of Xerces, inside the JRE. This has impacts on applications that wish to use their own XML parser.

In previous versions of Tomcat 5, you could simply replace the XML parser in the $CATALINA_HOME/common/lib directory to change the parser used by all web applications. However, this technique will not be effective when you are running on J2SE 1.4, because the usual class loader delegation process will always choose the implementation inside the JDK in preference to this one.

JDK 1.4支持被称为"Endorsed Standards Override Mechanism" 的机制，来允许替代在JCP以外产生的APIs(例如DOM 和W3C里的SAX)。也可以使用它来更新XML语法分析式执行。更多信息，请参看 http://java.sun.com/j2se/1.4/docs/guide/standards/index.html 。

Tomcat通过在启动容器的命令行里加入系统属性设置-Djava.endorsed.dirs=$CATALINA_HOME/common/endorsed 来利用这个机制。因此，你可以取代安装在这个目录里的语法分析式，它甚至可以在JDK 1.4系统上使用。

Running under a security manager

当在一个安全管理者下面运行时，从什么地方来的类可以被装载依赖于你的政策文件的具体内容。更多信息请参看Security Manager HOW-TO。


Apache Tomcat 5.5 Servlet/JSP 容器 - 怎样配制集群/Session复制

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

怎样配制集群/Session复制
快速入门

要在Tomcat 5.5容器里进行session复制，必须完成下列步骤：

  • 你的所有会话属性值必须实现java.io.Serializable
  • 把server.xml文件里的群集(Cluster)元素的注释取消(Uncomment)
  • 把server.xml文件里的Valve(ReplicationValve)元素注释取消(Uncomment)
  • 如果有多个Tomcat实例在一台机器上运行，确保每个实例的tcpListenPort属性值是不冲突的。
  • 确定 web.xml 中含有 <distributable/> 元素， 或者设置 <Context distributable="true" />
  • 确定设置好Engine元素的 jvmRoute 的属性值： <Engine name="Catalina" jvmRoute="node01" >
  • 确定所有节点拥有相同的时间， 并且通过网络时间服务(NTP)同步操作系统的时间！
  • 确定负载均衡器已经配置为黏性会话模式.

负载均衡可以有很多种方式实现，请参考负载均衡章节。

注意：记住你的会话状态是被一个cookie跟踪的，所以你的URL从外面看必须是相同的，否则一个新的session就会被产生。

注意：集群支持目前需要JDK 1.4或其后版本。

概要

要在Tomcat里实现会话session复制，下面三种方法都可以实现相同效果：

  1. 使用session 持久化, 并将 session 保存到一个共享的文件系统(持久管理器 + 文件存储)(PersistenceManager + FileStore)
  2. 使用session 持久化, 并将 session 保存到一个共享的 数据库 (持久管理器 + JDBC存储) (PersistenceManager + JDBCStore)
  3. 使用in-memory-replication，使用和Tomcat 5自带的SimpleTcpCluster(server/lib/catalina-cluster.jar)

In this release of session replication, Tomcat performs an all-to-all replication of session state. This is an algorithm that is only efficient when the clusters are small. For large clusters, the next release will support a primary-secondary session replication where the session will only be stored at one or maybe two backup servers. Currently you can use the domain worker attribute (mod_jk > 1.2.8) to build cluster partitions with the potential of very scaleable cluster solution. In order to keep the network traffic down in an all-to-all environment, you can split your cluster into smaller groups. This can be easily achieved by using different multicast addresses for the different groups. A very simple setup would look like this:

DNS 轮询
|
负载均衡器
/ \
集群1  集群2
/ \ / \
Tomcat1 Tomcat2 Tomcat3 Tomcat4

What is important to mention here, is that session replication is only the beginning of clustering. Another popular concept used to implement clusters is farming, ie, you deploy your apps only to one server, and the cluster will distribute the deployments across the entire cluster. This is all capabilities that can go into with the FarmWarDeployer (s. cluster example at server.xml)

下一章将深入讨论session复制是怎样实现的，以及怎样配置它。

它是怎样工作的

为了便于理解集群是怎样工作的,我们将用一系列的场景来描述. 在这个场景中，我们只计划使用两个tomcat 实例 TomcatA 和 TomcatB. 我们将覆盖下面连续的事件:

  1. TomcatA 启动
  2. TomcatB 启动 (等待TomcatA 启动完成)
  3. TomcatA 接受一个请求，session S1 被产生。
  4. TomcatA 崩溃停止
  5. TomcatB 接受一个session S1的请求
  6. TomcatA 启动
  7. TomcatA 接受一个请求，session ( S1 )失效。
  8. TomcatB 接受一个新的session ( S2 )的请求。
  9. TomcatA 因为没有活动session S2过期失效。

好了, 现在我们有了一个很好的顺序,我们将告诉你在session复制代码里发生的所有事情

  1. TomcatA 启动

    Tomcat 标准方式启动. 当 Host 对象被创建之后, 一个 cluster 对象与它关联. 当上下文被解析完, 如果 web.xml中有distributable元素， Tomcat 通过 Cluster class (in this case SimpleTcpCluster)为支持复制的上下文创建一个管理器. 因此通过设置web.xml中的distributable来启用集群。 Tomcat 将为上下文创建 DeltaManager莱取代 StandardManager. cluster class 将启动 a membership service (multicast) 和 a replication service (tcp unicast). More on the architecture further down in this document.

  2. TomcatB 启动

    当TomcatB启动时，除了一个例外以外，它按照TomcatA一样的顺序启动。群集被启用，并将建立一组会员(TomcatA,TomcatB)。TomcatB现在将要request已经存在于群集里的服务器的会话状态，在这里这个服务器是TomcatA。TomcatA回应TomcatB的请求，并且在TomcatB开始为HTTP requests监听之前，这个状态已经由TomcatA传递给TomcatB了。在TomcatA不回应的情况下，TomcatB在60秒后中断，并发出一个日志记录。对于每个已经分布在web.xml里的web应用程序，会话状态会被转移。注意：要有效地使用会话复制，你的所有tomcat实例要配置成一样的。

  3. TomcatA 接受一个请求，session S1 被产生。

    TomcatA对待传递来的请求与对待没有会话复制一样。当请求完成以后，活动就开始了，ReplicationValve在回应被返回到用户那里之前会截断这个请求。在这时，它发现会话被修改过，它就用TCP把这个会话复制给TomcatB。一旦这个分段的数据被递交给操作系统TCP logic，请求就通过valve pipeline返回给用户。对于每个请求，整个会话都被复制，这允许在不调用setAttribute 或 removeAttribute情况下，在会话中修改属性的代码被复制。配置参数useDirtyFlag可以被用来优化会话复制的次数。

  4. TomcatA 崩溃停止

    当TomcatA崩溃时，TomcatB会收到通知说TomcatA已经退出群集。TomcatB把TomcatA从它的会员列单中删除掉，TomcatB里有任何更改也不会再通知TomcatA。装载均衡器会把对TomcatA的请求引向TomcatB以及所有当前活动会话。

  5. TomcatB 接受一个session S1的请求

    TomcatB像处理其他任何请求一样处理这个请求。

  6. TomcatA 启动

    TomcatA启动时，在它接受新的请求以及让它自己可被使用之前，它要按照上面 1) 2)中所描述的顺序进行启动。它会加入群集，与TomcatB联系，了解所有会话的当前状态。一旦它接受到会话状态，它就完成装载并打开它的HTTP/mod_jk ports。所以在TomcatA接受到来自TomcatB的会话状态之前，不会对它发出请求。

  7. TomcatA 接受一个请求，session ( S1 )失效。

    失效的呼叫被拦截，这个会话就加入到失效的会话行列。在这个请求完成以后，它向TomcatB发出一个"expire"信息，TomcatB也把这个会话变为失效。

  8. TomcatB 接受一个新的session ( S2 )的请求。

    与步骤3)情形一样。

  9. TomcatA 因为没有活动session S2过期失效。

    就如一个会话由用户让它无效一样，invalidate呼叫被拦截到，这个会话就加入失效的会话行列。这一点上，除非另一个请求通过系统来检查失效行列，会话失效不会在其他地方重复。

Phuuuhh! :)

Membership Clustering membership可以通过使用非常简单的multicast pings被建立。每个Tomcat实例定期会发出multicast ping，在ping message里，这个实例会散布它的IP 及 TCP 监听端口以用于复制。如果一个实例在所给的时间范围内还没有收到这样的ping，这个会员就被认为是不存在了。很简单，也很有效。当然，你需要在你的系统上让multicasting可被使用。

TCP Replication，在收到一个multicast ping以后，会员就被添加到群集里。在下一个复制请求时，发出请求的实例将使用host和port信息来建立一个TCP socket。通过使用这个socket，它把分段的数据发送过去。我选择TCP sockets 的原因是它具备有流量控制，并确保发送到位。因此，我知道，当我发送数据时，这个数据就会被送到。

Distributed locking and pages using frames： Tomcat 并没有让会话实例在群集之间保持一致。这个逻辑的实现需要太大空间，也会带来很多问题。如果你的客户使用多个请求同时访问同一个会话，那么最后一个请求会覆盖群集里的其它会话。

Cluster Architecture

组件层次：

         Server
           |
         Service
           |
         Engine
           |  \
           |  --- Cluster --*
           |
         Host
           |
         ------
        /      \
     Cluster    Context(1-N)
        |             \
        |             -- Manager
        |                   \
        |                   -- DeltaManager
        |
     -----------------------------
     |          |         |       \
   Receiver    Sender   Membership  \
     \                               -- Valve
     -- SocketReplicationListener    |      \
     -- ReplicationListener          |       -- ReplicationValve
                                     |       -- JvmRouteBinderValve
                                     |
                                     -- LifecycleListener
                                     |
                                     -- ClusterListener
                                     |      \
                                     |       -- ClusterSessionListener
                                     |       -- JvmRouteSessionIDBinderListener
                                     |
                                     -- Deployer
                                            \
                                             -- FarmWarDeployer

   Sender
    \
    -- ReplicationTransmitter
             |
             ---------
                      \
                   IDataSender
                          \
                          |
                          --- (sync)
                          |  \
                          |   -- PooledSocketSender   (pooled)
                          |   -- SockerSender         (synchronous)
                          |
                          --- (async)
                             \
                              -- AsyncSocketSender     (asynchronous)
                              -- FastAsyncSocketSender (fastasyncqueue)

Cluster Configuration

群集配置在样品server.xml 文件里有描述。需要指出的是以mcastXXX开头的是关于会员成分multicast ping的属性，以tcpXXX开头的是关于TCP replication的属性。

会员成分是通过在相同的multicast IP 和 port上的所有tomcat实例建立的。TCP listen port是从其他会员那里来的会话复制在这它里被接收到的端口。

复制阀被用来发现请求什么时候被完成，并启动复制。

One of the most important performance considerations is the synchronous (pooled or not pooled) versus asynchronous replication mode. In a synchronous replication mode the request doesn't return until the replicated session has been sent over the wire and reinstantiated on all the other cluster nodes. There are two settings for synchronous replication. Pooled or not pooled. Not pooled (ie replicationMode="fastasnycqueue" or "synchronous") means that all the replication request are sent over a single socket. Using synchronous mode can potentially becomes a bottleneck when a lot of messages generated, You can overcome this bottleneck by setting replicationMode="pooled" but then you worker threads blocks with replication . What is recommended here is to increase the number of threads that handle incoming replication request. This is the tcpThreadCount property in the cluster section of server.xml. The pooled setting means that we are using multiple sockets, hence increases the performance. Asynchronous replication, should be used if you have sticky sessions until fail over, then your replicated data is not time crucial, but the request time is, at this time leave the tcpThreadCount to be number-of-nodes-1. During async replication, the request is returned before the data has been replicated. async replication yields shorter request times, and synchronous replication guarantees the session to be replicated before the request returns.

The parameter "replicationMode" has four different settings: "pooled", "synchronous", "asynchronous" and "fastasyncqueue"

Simple Cluster Configuration

Simple one line configuration

   <Server                 port="8011"
                       shutdown="SHUTDOWN" >
    <GlobalNamingResources>
    <Resource              name="UserDatabase" auth="Container"
                           type="org.apache.catalina.UserDatabase"
                    description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
    <Service              name="Catalina">
        <Connector        port="9012"
                      protocol="AJP/1.3"
        <Connector         port="9013"
                     maxThreads="100"
                minSpareThreads="4"
                maxSpareThreads="4"
        />
        <Engine            name="Catalina"
                   defaultHost="localhost"
                        jvmRoute="node01">
        <Realm        className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase" />
            <Host          name="localhost"
                        appBase="webapps">
             <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"/>
            </Host>
        </Engine>
    </Service>
</Server>

The default mode configuration setup a fastasyncqueue mode cluster configuration with following parameters:
  • Open Membership receiver at 228.0.0.4 and send to multicast udp port 8012
  • Send membership every 1 sec and drop member after 30sec.
  • Open message receiver at default ip interface at first free port between 8015 and 8019.
  • Receiver message with SocketReplicationListener
  • Configure a ReplicationTransmitter with fastasyncqueue sender mode.
  • Add ClusterSessionListener and ReplicationValve.

NOTE: Use this configuration when you need very quick a test cluster with at your developer machine. You can change the default attributes from cluster sub elements. Use following cluster attribute prefixes sender., receiver., service., manager., valve. and listener..
Example configure cluster at windows laptop with network connection and change receiver port range

<Cluster                 className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
          service.mcastBindAddress="127.0.0.1"
            receiver.tcpListenPort="9070"
         receiver.tcpListenMaxPort="9075" />

WARNING: When you add you sub elements, there overwrite the defaults complete.
Example configure cluster with cluster failover jsessionid support. In this case you need also the defaultmode Cluster listener ClusterSessionListener and ReplicationValve.
<Cluster                 className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
          service.mcastBindAddress="127.0.0.1"
            receiver.tcpListenPort="9070"
         receiver.tcpListenMaxPort="9075" >
       <ClusterListener  className="org.apache.catalina.cluster.session.ClusterSessionListener" />
       <ClusterListener  className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" />
       <Valve            className="org.apache.catalina.cluster.tcp.ReplicationValve"
                            filter=".*\.gif;.*\.js;.*\.css;.*\.png;.*\.jpeg;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"
                  primaryIndicator="true" />
       <Valve            className="org.apache.catalina.cluster.session.JvmRouteBinderValve"
                          enabled="true"  />
<Cluster/>

Simple Engine Cluster Configuration for all hosts

Simple one line engine configuration

   <Server                 port="8011"
                       shutdown="SHUTDOWN" >
    <GlobalNamingResources>
    <Resource              name="UserDatabase" auth="Container"
                           type="org.apache.catalina.UserDatabase"
                    description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
    <Service              name="Catalina">
        <Connector        port="9012"
                      protocol="AJP/1.3"
        <Connector         port="9013"
                     maxThreads="100"
                minSpareThreads="4"
                maxSpareThreads="4"
        />
        <Engine            name="Catalina"
                   defaultHost="localhost"
                        jvmRoute="node01">
        <Realm        className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase" />
        <Cluster      className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"/>
            <Host          name="localhost"
                        appBase="webapps"/>
        </Engine>
    </Service>
</Server>

See default mode configuration description as simple host cluster example before.

Complex Cluster Configuration

Example Configure cluster with complete sub elements. Activate this node as master farm delopyer. Message receiver is NIO based ReplicationListener with six parallel worker threads.

       <Server                 port="8011"
                       shutdown="SHUTDOWN" >
    <GlobalNamingResources>
    <Resource              name="UserDatabase" auth="Container"
                           type="org.apache.catalina.UserDatabase"
                    description="User database that can be updated and saved"
                        factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                        pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
    <Service              name="Catalina">
        <Connector        port="9012"
                      protocol="AJP/1.3"
        <Connector         port="9013"
                     maxThreads="100"
                minSpareThreads="4"
                maxSpareThreads="4"
        />
        <Engine            name="Catalina"
                   defaultHost="localhost"
                        jvmRoute="node01">
        <Realm        className="org.apache.catalina.realm.UserDatabaseRealm"
                   resourceName="UserDatabase" />
            <Host          name="localhost"
                        appBase="webapps">
                <Cluster                  className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
                                       doClusterLog="true"
                                     clusterLogName="clusterlog"
                                  manager.className="org.apache.catalina.cluster.session.DeltaManager"
                   manager.expireSessionsOnShutdown="false"
               manager.notifyListenersOnReplication="false"
        manager.notifySessionListenersOnReplication="false"
                            manager.sendAllSessions="false"
                        manager.sendAllSessionsSize="500"
                    manager.sendAllSessionsWaitTime="20">
                  <Membership
                                          className="org.apache.catalina.cluster.mcast.McastService"
                                          mcastAddr="228.0.0.4"
                                   mcastBindAddress="127.0.0.1"
                                 mcastClusterDomain="d10"
                                          mcastPort="45564"
                                     mcastFrequency="1000"
                                      mcastDropTime="30000"/>
                  <Receiver
                                           className="org.apache.catalina.cluster.tcp.ReplicationListener"
                                    tcpListenAddress="auto"
                                       tcpListenPort="9015"
                                  tcpSelectorTimeout="100"
                                      tcpThreadCount="6"
                  <Sender
                                           className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
                                     replicationMode="fastasyncqueue"
                                      recoverTimeout="5000"
                                      recoverCounter="6"
                        doTransmitterProcessingStats="true"
                                   doProcessingStats="true"
                                      doWaitAckStats="true"
                                       queueTimeWait="true"
                                        queueDoStats="true"
                                      queueCheckLock="true"
                                          ackTimeout="15000"
                                          waitForAck="true"
                                    keepAliveTimeout="80000"
                            keepAliveMaxRequestCount="-1"/>
                  <Valve                   className="org.apache.catalina.cluster.tcp.ReplicationValve"
                                              filter=".*\.gif;.*\.js;.*\.css;.*\.png;.*\.jpeg;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"
                                    primaryIndicator="true" />
                  <Valve                    className="org.apache.catalina.cluster.session.JvmRouteBinderValve"
                                             enabled="true" />
                  <ClusterListener         className="org.apache.catalina.cluster.session.ClusterSessionListener" />
                  <ClusterListener         className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" />
                  <Deployer                className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
                                            tempDir="${catalina.base}/war-temp"
                                          deployDir="${catalina.base}/war-deploy/"
                                           watchDir="${catalina.base}/war-listen/"
                                       watchEnabled="true"/>
                  </Cluster>
            </Host>
        </Engine>
    </Service>
</Server>

Cluster Configuration for ReplicationTransmitter

List of Attributes
属性 | 描述 | Default value
replicationMode | replication mode (synchronous, pooled, asynchronous or fastasyncqueue) | pooled
processSenderFrequency | Control the sender keepalive status and drop sender socket connection after timeout is reached. Check every processSenderFrequency value engine background ticks. | 2
compress | compress bytes before sending (consume memory, but reduce network traffic - GZIP) | false
ackTimeout | acknowledge timeout and only usefull it waitForAck is true | 15000 msec
waitForAck | Wait for ack after data send | false
autoConnect | is sender disabled, fork a new socket | false
doTransmitterProcessingStats | create processing time stats | false

Example to get statistic information, wait for ack at every message send and transfer at compressed mode

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="fastasyncqueue"
      compress="true"
      doTransmitterProcessingStats="true"
      ackTimeout="15000"
      waitForAck="true"
      autoConnect="false"/>

Cluster Configuration for ReplicationTransmitter (fastayncqueue - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
doProcessingStats | create Processing time stats | false
doWaitAckStats | create waitAck time stats | false
resend | resend message after failure, can overwrite at message | false
recoverTimeout | recover Timeout after push message failure | 5000 msec
recoverCounter | number of recover tries | 0
queueDoStats | activated queue stats | false
queueCheckLock | check to lost locks | false
queueAddWaitTimeout | queue add wait time (tomcat connector thread waits) | 10000 msec
queueRemoveWaitTimeout | queue remove wait time (queue thread waits) | 30000 msec
maxQueueLength | max queue length (default without limit) | -1
threadPriority | change queue thread priority (1-10 ; 5 is normal) | 5

Example to get a lot of statistic information, wait for ACK and recover after connection failure (wait 5 secs and 6 trails (==30 secs Mcast Timeout)

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="fastasyncqueue"
      recoverTimeout="5000"
      recoverCounter="6"
      doTransmitterProcessingStats="true"
      doProcessingStats="true"
      queueTimeWait="true"
      queueDoStats="true"
      queueCheckLock="true"
      waitForAck="true"
      autoConnect="false"
      keepAliveTimeout="320000"
      keepAliveMaxRequestCount="-1"/>

Cluster Configuration for ReplicationTransmitter ( asynchronous - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
doProcessingStats | create Processing time stats | false
doWaitAckStats | create waitAck time stats | false
resend | resend message after failure, can overwrite at message | false

Example to get a processing statistic information, resend after failure and wait for ACK

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="asynchronous"
      doProcessingStats="true"
      doWaitAckStats="true"
      waitForAck="true"
      ackTimeout="30000"
      resend="true"
      keepAliveTimeout="320000"
      keepAliveMaxRequestCount="-1"/>

Cluster Configuration for ReplicationTransmitter ( synchronous - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
doProcessingStats | create Processing time stats | false
doWaitAckStats | create waitAck time stats | true
resend | resend message after failure, can overwrite at message | false

Example to get a no processing statistic information, no wait for ACK, after 10000 request renew socket and autoconnect before first request is send.

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="synchronous"
      autoConnect="true"
      keepAliveTimeout="-1"
      keepAliveMaxRequestCount="100000"/>

Cluster Configuration for ReplicationTransmitter ( pooled - mode)

List of Attributes
属性 | 描述 | Default value
keepAliveTimeout | active socket keep alive timeout | 60000 msec
keepAliveMaxRequestCount | max request over this socket | -1
maxPoolSocketLimit | max pooled sockets (Sender Sockets) | 25
resend | resend message after failure, can overwrite at message | false

Example to get a no processing statistic information, wait for ACK, after 10000 request renew socket, only 10 SockerSender available and autoconnect before first request is send.

    <Sender
      className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
      replicationMode="pooled"
      autoConnect="true"
      maxPoolSocketLimit="10"
      keepAliveTimeout="-1"
      keepAliveMaxRequestCount="10000"
      waitForAck="true" />

Cluster Configuration for ReplicationTransmitter ( DeltaManager Attribute)

List of Attributes
属性 | 描述 | Default value
expireSessionsOnShutdown | When server stopped, expire all sessions also at backup nodes (only for testing) | false
maxActiveSessions | Number of active sessions. (Default is no limit) | -1
notifyListenersOnReplication | Notify application session listener to session creation and expiring events at backup nodes | true
notifySessionListenersOnReplication | Notify application session listener to attribute changes at backup nodes | true
stateTransferTimeout | Timeout that session state transfer is complete. Is attribute stateTransferTimeout == -1 then application wait that other node send the complete session state | 60 sec
sendAllSessions | Flag to send sessions as splited blocks | true
sendAllSessionsSize | Number of serialize sessions inside a send block session message. Only useful when sendAllSessions==false | 1000
sendAllSessionsWaitTime | wait time between two session send blocks. | 2000 msec
sendClusterDomainOnly | Send all session messages only to member inside same cluster domain (value od Membership attribute mcastClusterDomain). Also don't handle session messages from other domains. | true
stateTimestampDrop | DeltaManager queued Sessions messages when send GET_ALL_SESSION to other node. with stateTimestampDrop all messages before state transfer message creation date (find session) are dropped. Only other GET_ALL_SESSION events are handle with date before state transfer message. | true

Example send all sessions at separate blocks. Serialize and send 100 session inside one block. Wait maximale two minutes before the complete backup sessions are loaded inside tomcat boot process. Between send blocks wait 5 secs to transfers the session block to other node. This save memory when you use the async modes with queues.

    <Cluster className="org.apache.catalina.tcp.SimpleTcpCluster"
      managerClassName="org.apache.catalina.cluster.session.DeltaManager"
      manager.stateTransferTimeout="120"
      manager.sendAllSessions="false"
      manager.sendAllSessionsSize="100"
      manager.sendAllSessionsWaitTime="5000"
      "/>

注意
As Cluster.defaultMode=true you can configure the manager attributes with prefix manager..
注意
With Cluster.setProperty(<String>,<String>) you can modify attributes for all register managers. The method exists as MBeans operation.

Bind session after crash to failover node

As you configure more then two nodes at same cluster for backup, most loadbalancer send don't all your requests after failover to the same node.

The JvmRouteBinderValve handle tomcat jvmRoute takeover using mod_jk module after node failure. After a node crashed the next request going to other cluster node. The JvmRouteBinderValve now detect the takeover and rewrite the jsessionid information to the backup cluster node. After the next response all client request goes direct to the backup node. The change sessionid send also to all other cluster nodes. Well, now the session stickyness work directly to the backup node, but traffic don't go back too restarted cluster nodes!
As jsessionid was created by cookie, the change JSESSIONID cookie resend with next response.

You must add JvmRouteBinderValve and the corresponding cluster message listener JvmRouteSessionIDBinderListener. As you add the new listener you must also add the default ClusterSessionListener that receiver the normal cluster messages.

<Cluster className="org.apache.catalina.tcp.SimpleTcpCluster" >
...
     <Valve className="org.apache.catalina.cluster.session.JvmRouteBinderValve"
               enabled="true" sessionIdAttribute="takeoverSessionid"/>
     <ClusterListener className="org.apache.catalina.cluster.session.JvmRouteSessionIDBinderListener" />
     <ClusterListener className="org.apache.catalina.cluster.session.ClusterSessionListener" />
...
<Cluster>

Hint:
With attribute sessionIdAttribute you can change the request attribute name that included the old session id. Default attribuite name is org.apache.catalina.cluster.session.JvmRouteOrignalSessionID.

Trick:
You can enable this mod_jk turnover mode via JMX before you drop a node to all backup nodes! Set enable true on all JvmRouteBinderValve backups, disable worker at mod_jk and then drop node and restart it! Then enable mod_jk Worker and disable JvmRouteBinderValves again. This use case means that only requested session are migrated.

通过 JMX 监控集群

Monitoring is a very important question when you use a cluster. Some of the cluster objects are JMX MBeans

Add the following parameter to your startup script with Java 5:

set CATALINA_OPTS=\
-Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=%my.jmx.port% \
-Dcom.sun.management.jmxremote.ssl=false \
-Dcom.sun.management.jmxremote.authenticate=false

在 JDK 1.4中启用JMX:

  1. 安装 compat 包
  2. 安装 mx4j-tools.jar 到 common/lib (使用与tomcat发布版相同的mx4j版本)
  3. Configure a MX4J JMX HTTP Adaptor at your AJP Connector

    <Connector port="${AJP.PORT}"
   handler.list="mx"
   mx.enabled="true"
   mx.httpHost="${JMX.HOST}"
   mx.httpPort="${JMX.PORT}"
   protocol="AJP/1.3" />
  4. 启动Tomcat,然后再浏览器中访问 http://${JMX.HOST}:${JMX.PORT}
  5. 通过连接参数 mx.authMode="basic" mx.authUser="tomcat" mx.authPassword="strange"可以控制访问权限!

集群 Mbeans 列表
name(名称) | 描述 | MBean ObjectName - Engine | MBean ObjectName - Host
集群 | The complete cluster element | type=Cluster | type=Cluster,host=${HOST}
ClusterSender | Configuration and stats of the sender infrastructure | type=ClusterSender | type=ClusterSender,host=${HOST}
ClusterReceiver | Configuration and stats of the recevier infrastructure | type=ClusterReceiver | type=ClusterReceiver,host=${HOST}
ClusterMembership | Configuration and stats of the membership infrastructure | type=ClusterMembership | type=ClusterMembership,host=${HOST}
IDataSender For every cluster member it exist a sender mbeans. It exists speziall MBeans to all replication modes
type=IDataSender,
        senderAddress=${MEMBER.SENDER.IP},
        senderPort=${MEMBER.SENDER.PORT}

type=IDataSender,host=${HOST},
        senderAddress=${MEMBER.SENDER.IP},
        senderPort=${MEMBER.SENDER.PORT}
DeltaManager | This manager control the sessions and handle session replication | type=Manager,path=${APP.CONTEXT.PATH}, host=${HOST} | type=Manager,path=${APP.CONTEXT.PATH}, host=${HOST}
ReplicationValve | This valve control the replication to the backup nodes | type=Valve,name=ReplicationValve | type=Valve,name=ReplicationValve,host=${HOST}
JvmRouteBinderValve | This is a cluster fallback valve to change the Session ID to the current tomcat jvmroute. | type=Valve,name=JvmRouteBinderValve, path=${APP.CONTEXT.PATH} | type=Valve,name=JvmRouteBinderValve,host=${HOST}, path=${APP.CONTEXT.PATH}

常见问题

请参考 集群常见问题.


Apache Tomcat 5.5 Servlet/JSP 容器 - 配置连接

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

配置连接
简介

Choosing a connector to use with Tomcat can be difficult. This page will list the connectors which are supported with this Tomcat release, and will hopefully help you make the right choice according to your needs.

HTTP

HTTP connector 是Tomcat默认设置的 , 可直接使用. This connector features the lowest latency and best overall performance.

为支持集群, a HTTP load balancer with support for web sessions stickiness must be installed to direct the traffic to the Tomcat servers. Tomcat 支持 mod_proxy (在 Apache HTTP Server 2.x 版本中可用, Apache HTTP Server 2.2 默认自带) 作为负载均衡器. It should be noted that the performance of HTTP proxying is usually lower than the performance of AJP, so AJP clustering is often preferable.

AJP

When using a single server, the performance when using a native webserver in front of the Tomcat instance is most of the time significantly worse than a standalone Tomcat with its default HTTP connector, even if a large part of the web application is made of static files. If integration with the native webserver is needed for any reason, an AJP connector will provide faster performance than proxied HTTP. AJP clustering is the most efficient from the Tomcat perspective. It is otherwise functionally equivalent to HTTP clustering.

支持Tomcat发行版的本地AJP连接器有:

  • JK 1.2.x 及其所支持的服务器
  • Apache HTTP Server 2.x 上的 mod_proxy (Apache HTTP Server 2.2 默认自带),并启用AJP支持

其它支持AJP的本地连接可能仍然能正常工作，但是不再被提供支持。


Apache Tomcat 5.5 Servlet/JSP 容器 - 默认 Servlet 参考手册

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

默认 Servlet 参考手册
简介
这里讨论不同的操纵默认servlet的方法。讨论的话题有：
  • 什么是DefaultServlet?
  • 它在什么地方被声明的？
  • 我能做什么样的改变？
  • 我怎样定制目录列表？
  • 我怎样保护目录列表的安全性？
什么是DefaultServlet
默认的servlet是既服务于静态资源又服务于目录列表(如果允许目录列表的话)的servlet。
它在什么地方被声明的？
它在$CATALINA_HOME/conf/web.xml中被全局声明。默认形式的声明是这样的： $CATALINA_HOME/conf/web.xml
&lt;servlet&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;servlet-class&gt;
org.apache.catalina.servlets.DefaultServlet
&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;debug&lt;/param-name&gt;
&lt;param-value&gt;0&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;listings&lt;/param-name&gt;
&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

...

&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
因此在默认的情况下，默认servlet在webapp启动时被装载，目录列表可被使用，日志调试功能被关掉。 （翻译者备注：在Tomcat 5.5.13之后的版本，已经将listings默认设置为false,默认是禁止目录列表了 参见 http://issues.apache.org/bugzilla/show_bug.cgi?id=37150）
我能做什么样的改变？
DefaultServlet允许以下初始化参数：
debug | 日志级别。如果你不是tomcat开发人员，这对你没有什么用处。目前，有用的值是0, 1, 11, 1000。
listings 如果没有欢迎文件，要不要显示目录列表？值可以是true 或 false。
欢迎文件是servlet api的一部分。
警告:列表显示包含太多记录的目录是非常消耗服务性能的 . 大量请求访问大目录列表会吃掉服务器大部分的资源.
readmeFile | 如果允许目录列表，可能有一个readme文件和这个列表在一起。这个文件包含HTML被插入。默认值是null。
globalXsltFile | 如果你希望定制你的目录列表显示效果，你可以使用一个XSL转换(transformation)。这个值是一个可用于所有目录列表的绝对路径文件名。它可以被每个webapp 重新自定义使用，或者通过在你局部webapp的web.xml文件里声明默认servlet取消使用。这个xml文件的格式在下面有显示。
localXsltFile | 你还可以在每个目录通过配置localXsltFile定制你的目录列表。它应该是在产生列表的目录里的一个相对路径文件名。它覆盖globalXsltFile。如果这个值存在，但是文件不存在，那么就使用globalXsltFile。如果globalXsltFile也不存在，那么默认的目录列表就会被显示出来。
input | 在读取用于服务的资源时的输入缓冲容量(in bytes)。[2048]
output | 在读取用于服务的资源时的输出缓冲容量(in bytes)。[2048]
readonly | 这个上下文否"read only"，因此如PUT 和 DELETE的HTTP命令将被拒绝执行？ [true]
fileEncoding | 文件编码用于读取静态资源时. [平台默认值]
sendfileSize | 如果连接器支持 sendfile, 这个参数表示sendfile将用到的最小文件大小（以KB为单位） . 使用负数 可以禁止使用sendfile. [48]
我怎样定制目录列表？

你可以用你自己的实现(implementation)来覆盖DefaultServlet，并在你的web.xml声明里使用它。如果你能理解刚刚所讲的，我们假设你可以阅读DefaultServlet servlet的代码，并能做适当的调整(如果不行，这个方法对你不适用)。

你可以使用localXsltFile或globalXsltFile，DefaultServlet将会产生一个xml文件，并通过一个基于localXsltFile和globalXsltFile所提供的xsl转换来执行。首先检查localXsltFile，然后是globalXsltFile，再后是默认行为。

格式

&lt;listing&gt;
&lt;entries&gt;
&lt;entry type='file|dir' urlPath='aPath' size='###' date='gmt date'&gt;
fileName1
&lt;/entry&gt;
&lt;entry type='file|dir' urlPath='aPath' size='###' date='gmt date'&gt;
fileName2
&lt;/entry&gt;
...
&lt;/entries&gt;
&lt;readme&gt;&lt;/readme&gt;
&lt;/listing&gt;
  • 如果 type='dir' ，size将不存在
  • Readme是一个CDATA输入

下面的是一个xsl文件示例，它模拟默认的tomcat行为：
&lt;?xml version="1.0"?&gt;

&lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"&gt;

&lt;xsl:output method="xhtml" encoding="iso-8859-1" indent="no"/&gt;

&lt;xsl:template match="listing"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;
Sample Directory Listing For
&lt;xsl:value-of select="@directory"/&gt;
&lt;/title&gt;
&lt;style&gt;
h1{color : white;background-color : #0086b2;}
h3{color : white;background-color : #0086b2;}
body{font-family : sans-serif,Arial,Tahoma;
color : black;background-color : white;}
b{color : white;background-color : #0086b2;}
a{color : black;} HR{color : #0086b2;}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Sample Directory Listing For
&lt;xsl:value-of select="@directory"/&gt;
&lt;/h1&gt;
&lt;hr size="1" /&gt;
&lt;table cellspacing="0"
width="100%"
cellpadding="5"
align="center"&gt;
&lt;tr&gt;
&lt;th align="left"&gt;Filename&lt;/th&gt;
&lt;th align="center"&gt;Size&lt;/th&gt;
&lt;th align="right"&gt;Last Modified&lt;/th&gt;
&lt;/tr&gt;
&lt;xsl:apply-templates select="entries"/&gt;
&lt;/table&gt;
&lt;xsl:apply-templates select="readme"/&gt;
&lt;hr size="1" /&gt;
&lt;h3&gt;Apache Tomcat/5.0&lt;/h3&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="entries"&gt;
&lt;xsl:apply-templates select="entry"/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="readme"&gt;
&lt;hr size="1" /&gt;
&lt;pre&gt;&lt;xsl:apply-templates/&gt;&lt;/pre&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="entry"&gt;
&lt;tr&gt;
&lt;td align="left"&gt;
&lt;xsl:variable name="urlPath" select="@urlPath"/&gt;
&lt;a href="{$urlPath}"&gt;
&lt;tt&gt;&lt;xsl:apply-templates/&gt;&lt;/tt&gt;
&lt;/a&gt;
&lt;/td&gt;
&lt;td align="right"&gt;
&lt;tt&gt;&lt;xsl:value-of select="@size"/&gt;&lt;/tt&gt;
&lt;/td&gt;
&lt;td align="right"&gt;
&lt;tt&gt;&lt;xsl:value-of select="@date"/&gt;&lt;/tt&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/xsl:template&gt;

&lt;/xsl:stylesheet&gt;
我怎样保护目录列表的安全性？
在每一个webapp里使用web.xml 。参看Servlet 规范中关于安全的相关章节。


Apache Tomcat 5.5 Servlet/JSP 容器 - Tomcat Web Application Deployment

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Tomcat Web Application Deployment
Table of Contents
  • 简介
  • 安 装
  • A word on Contexts
  • Deployment on Tomcat startup
  • 在运行的Tomcat服务器上部署（Deploying on a running Tomcat server ）
  • Deploying using the Tomcat Manager
  • Deploying using the Tomcat Client Deployer
Introduction

Deployment is the term used for the process of installing a web application (either a 3rd party WAR or your own custom web application) into the Tomcat server.

Web application deployment may be accomplished in a number of ways within the Tomcat server.

  • Statically; the web application is setup before Tomcat is started
  • Dynamically; in conjunction with the Tomcat Manager web application or manipulating already deployed web applications

The Tomcat Manager is a tool that allows URL-based web application deployment features. There is also a tool called the Client Deployer, which is a command shell based script that interacts with the Tomcat Manager but provides additional functionality such as compiling and validating web applications as well as packaging web application into web application resource (WAR) files.

Installation

There is no installation required for static deployment of web applications as this is provided out of the box by Tomcat. Nor is any installation required for deployment functions with the Tomcat Manager, although some configuration is required as detailed in the Tomcat Manager manual. An installation is however required if you wish to use the Tomcat Client Deployer (TCD).

The TCD is not packaged with the Tomcat core distribution, and must therefore be downloaded separately from the Downloads area. The download is usually labelled jakarta-tomcat-5.5.x-deployer.

TCD has prerequisites of Apache Ant 1.6.2+ and a Java installation. Your environment should define an ANT_HOME environment value pointing to the root of your Ant installation, and a JAVA_HOME value pointing to your Java installation. Additionally, you should ensure Ant's ant command, and the Java javac compiler command run from the command shell that your operating system provides.

  1. Download the TCD distribution
  2. The TCD package need not be extracted into any existing Tomcat installation, it can be extracted to any location.
  3. Read Using the Tomcat Client Deployer
A word on Contexts

In talking about deployment of web applications, the concept of a Context is required to be understood. A Context is what Tomcat calls a web application.

In order to configure a Context within Tomcat a Context Descriptor is required. A Context Descriptor is simply an XML file that contains Tomcat related configuration for a Context, e.g naming resources or session manager configuration. In earlier versions of Tomcat the content of a Context Descriptor configuration was often stored within Tomcat's primary configuration file server.xml but this is now discouraged (although it currently still works).

Context Descriptors not only help Tomcat to know how to configure Contexts but other tools such as the Tomcat Manager and TDC often use these Context Descriptors to perform their roles properly.

The locations for Context Descriptors are;

  1. $CATALINA_HOME/conf/[enginename]/[hostname]/context.xml
  2. $CATALINA_HOME/webapps/[webappname]/META-INF/context.xml
If a Context Descriptor is not provided for a Context, Tomcat automatically creates one and places it in (1) with a filename of [webappname].xml although if manually created, the filename need not match the web application name as Tomcat is concerned only with the Context configuration contained within the Context Descriptor file(s).

Deployment on Tomcat startup

If you are not interested in using the Tomcat Manager, or TCD, then you'll need to deploy your web applications statically to Tomcat, followed by a Tomcat startup. The location you deploy web applications to for this type of deployment is called the appBase which is specified per Host. You either copy a so-called exploded web application, i.e non-compressed, to this location, or a compressed web application resource .WAR file.

The web applications present in the location specified by the Host's (default Host is "localhost") appBase attribute (default appBase is "$CATALINA_HOME/webapps") will be deployed on Tomcat startup only if the Host's deployOnStartup attribute is "true".

The following deployment sequence will occur on Tomcat startup in that case:

  1. Any Context Descriptors will be deployed first.
  2. Exploded web applications not referenced by any Context Descriptor will then be deployed. If they have an associated .WAR file in the appBase and it is newer than the exploded web application, the exploded directory will be removed and the webapp will be redeployed from the .WAR
  3. 部署WAR文件

Note again that for each deployed web application, a Context Descriptor will be created unless one exists already.

Deploying on a running Tomcat server

It is possible to deploy web applications to a running Tomcat server.

If the Host autoDeploy attribute is "true", the Host will attempt to deploy and update web applications dynamically, as needed, for example if a new .WAR is dropped into the appBase. For this to work, the Host needs to have background processing enabled which is the default configuration.

autoDeploy set to "true" and a running Tomcat allows for:

  • Deployment of .WAR files copied into the Host appBase.
  • Deployment of exploded web applications which are copied into the Host appBase.
  • Re-deployment of a web application which has already been deployed from a .WAR when the new .WAR is provided. In this case the exploded web application is removed, and the .WAR is expanded again. Note that the explosion will not occur if the Host is configured so that .WARs are not exploded with a unpackWARs attribute set to "false", in which case the web application will be simply redeployed as a compressed archive.
  • Re-deployment of a web application if the /WEB-INF/web.xml file (or any other resource defined as a WatchedResource) is updated.
  • Re-deployment of a web application if the Context Descriptor file from which the web application has been deployed is updated.
  • Re-deployment of a web application if a Context Descriptor file (with a filename corresponding to the Context path of the previously deployed web application) is added to the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory.
  • Undeployment of a web application if its document base (docBase) is deleted. Note that on Windows, this assumes that anti-locking features (see Context configuration) are enabled, otherwise it is not possible to delete the resources of a running web application.

Note that web application reloading can also be configured in the loader, in which case loaded classes will be tracked for changes.

Deploying using the Tomcat Manager

The Tomcat Manager is covered in its own manual page.

Deploying using the Client Deployer Package

Finally, deployment of web application may be achieved using the Tomcat Client Deployer. This is a package which can be used to validate, compile, compress to .WAR, and deploy web applications to production or development Tomcat servers. It should be noted that this feature uses the Tomcat Manager and as such the target Tomcat server should be running.

It is assumed the user will be familar with Apache Ant for using the TCD. Apache Ant is a scripted build tool. The TCD comes pre-packaged with a build script to use. Only a modest understanding of Apache Ant is required (installation as listed earlier in this page, and familiarity with using the operating system command shell and configuring environment variables).

The TCD includes Ant tasks, the Jasper page compiler for JSP compilation before deployment, as well as a task which validates the web application Context Descriptor. The validator task (class org.apache.catalina.ant.ValidatorTask) allows only one parameter: the base path of an exploded web application.

The TCD uses an exploded web application as input (see the list of the properties used below). A web application that is programatically deployed with the deployer may include a Context Desciptor in /META-INF/context.xml.

The TCD includes a ready-to-use Ant script, with the following targets:

  • 编译(compile)(默认default)：编译并确认网络应用程序。这个目标可以单独使用，并不需要一个运行的Tomcat服务器。因为由Jasper产生的代码依赖于它的运行组件，这个被编译过的程序只能运行在相关的Tomcat 5.0.x发行版服务器上, 不能保证能在其他发行版服务器上运行。还须注意，这个目标还会自动 编译位于 /WEB-INF/classes 文件夹里的Java 源文件。
  • 部署(deploy)：把网络程序(编译过的或未编译过的)部署到Tomcat服务器上。
  • 反部署(undeploy)：反部署网络应用程序。
  • 启动(start)： 启动一个web程序。
  • 重新装载(reload)：重新装载web应用程序。
  • 停止(stop)：停止运行web应用程序。

In order for the deployment to be configured, create a file called deployer.properties in the TCD installation directory root. In this file, add the following name=value pairs per line:

Additionally, you will need to ensure that a user has been setup for the target Tomcat Manager (which TCD uses) otherwise the TCD will not authenticate with the Tomcat Manager and the deployment will fail. To do this, see the Tomcat Manager page.

  • 构造(build)：build文件夹可以以默认的形式${build}/webapp${path}使用。当编译(compile)目标执行完之后，WAR程序就被放置在${build}/webapp${path}.war。
  • webapp: The directory containing the exploded web application which will be compiled and validated. By default, the folder is myapp.
  • 路径(path)：被部署的网络程序的上下文路径，默认名称是/myapp 。
  • url: Absolute URL to the Tomcat Manager web application of a running Tomcat server, which will be used to deploy and undeploy the web application. By default, the deployer will attempt to access a Tomcat instance running on localhost, at http://localhost:8080/manager.
  • username: Tomcat Manager username (user should have a role of manager)
  • password: Tomcat Manager password.


Apache Tomcat 5.5 Servlet/JSP 容器 - Tomcat 开发人员

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Tomcat 开发人员
当前开发人员

这个列表大致罗列了最有兴趣的开发者。被列到这个列表里是免费的 :) 这些 开发者的邮件地址是[login]@apache.org。 请 不要 直接联系这些开发者询问有官方支持的版本的问题 (请将问题发送到tomcat-users 邮件列表， 或者其他的资源; 一些组织和个人顾问也提供tomcat的技术支持, 部分列表 vendors page 在Jakarta的网页上).

  • Amy Roh (amyroh): Catalina, Admin webapp
  • Bill Barker (billbarker): Connectors
  • Costin Manolache (costin): Catalina, Connectors
  • Filip Hanik (fhanik): Clustering, Release Manager
  • Glenn Nielsen (glenn): Catalina, Connectors
  • Henri Gomez (hgomez): Connectors
  • Jan Luehe (luehe): Jasper
  • Jean-Francois Arcand (jfarcand): Catalina
  • Jean-Frederic Clere (jfclere): Connectors
  • Kin-Man Chung (kinman): Jasper
  • Mark Thomas (markt): CGI, SSI, WebDAV, bug fixing
  • Mladen Turk (mturk): Connectors
  • Peter Rossbach (pero): Catalina, Clustering, JMX
  • Rainer Jung (rjung): Catalina, Clustering, Connectors
  • Remy Maucherat (remm): Catalina, Connectors, Docs
  • Tim Funk (funkman): Catalina, Docs
  • Yoav Shapira (yoavs): Docs, JMX, Catalina, balancer
曾经参与过的开发人员


Apache Tomcat 5.5 Servlet/JSP 容器 - 文件目录

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

文件目录
Introduction

这里是关于Apache Jakarta Tomcat/JSP容器的文件一个顶层进入点。 Tomcat 5.5版起用 了Java Community Process 的Servlet 2.4 和 Java Server Page (JSP) 2.0 版的规范，同时又添加了许多特性。 这使它成为一个十分 有用的开发和部署，网络应用和web服务的平台

你可从（左边的）目录中选择一个链接来查询详细的内容。下面的每个链接都有更为 详细的描述。

Apache Tomcat User Guide

下面的文件帮助你下载、安装Apache Tomcat 5，以及使用Apache Tomcat 的许多特性。

  1. 简介- 关于Apache Tomcat的 简短，高层位概貌。
  2. 安装 - 怎样在一系列不同的平台上 安装和运行Apache Tomcat 。
  3. 简单网络应用- 简单 介绍Servlet 2.3 规则里制定的关于网络应用的概念。覆盖面包括基本的网络应用 的资源树，网络应用存档结构，以及网络应用部署描述符的简介 （/WEB-INF/web.xml)。
  4. 部署者- 操作Apache Tomcat 部署者来部署,预编译, 和验证网络应用程序。
  5. 管理者- 在 Apache Tomcat 运行时，由管理员(manager)程序来部署， 取消部署（undeploy)， 再部署 (redeploy)各类应用程序。
  6. 域和访问控制： 描述 怎样配置域(用户，密码和相关功能的数据库)来使用关于容器管理安全 性的网络应用程序。
  7. 安全管理： 配置和使用Java安全管理器来支持对网络程序行为的细致控制。
  8. JNDI 资源：在每个 网络程序的JNDI命名上下文里的配置标准以及客户资源。
  9. JDBC数据源：用数据库的连接池来配置JNDI数据源。有许多 流行的数据库实例。
  10. (类加载)- 关于Apache Tomcat 5里类的加载信息，包括在什么地方放置类程序，使他们有效。
  11. JSPs - 关于Jasper配置和 JSP编译器的使用信息。
  12. SSL - 安装和配置SSL支持，这样 Apache Tomcat 就可以应用https协定来服务需求。
  13. SSI - Apache Tomcat里服务器端 的应用。
  14. CGI - 在Apache Tomcat里如何 使用公用网关接口CGI。
  15. Proxy Support - 配置 Apache Tomcat 5通过代理器(或者作为代理器的web服务器)提供服务。
  16. MBean描述符 - 配置客户部件的 MBean描述符文件。
  17. Default Servlet - 配置 缺省servlet以及自定义用户目录列表。
  18. Apache Tomcat 集群- 在Tomcat 环境里使session复制成为可能。
  19. 负载均衡器: 配置,使用, 扩充加载均衡器的应用程序。
  20. 链接器 - Apache Tomcat支持的 链接访问方式，和本地服务器搭配。
  21. 监视和管理 - 启动JMX远程支持，并且使用工具来监视和管理Apache Tomcat。
  22. 日志 - 配置Apache Tomcat的日志
Reference

下面的文献是针对负责安装，配置和操作Apache Tomcat 5服务器的系统管理员的。

  • 版本信息 - 了解Apache Tomcat的发行版本。
  • Apache Tomcat 服务器配置参考 - 记录了可能被放置在Apache Tomcat 5 conf/server.xml 文件里面所有 可被使用的元素和属性的参考手册。
  • JK 文档 -JK 本地web服务器的全面文档和指南，用于Apache Tomcat同其他服务器，例如： Apache HTTPd, IIS 等等的联合使用。
  • Servlet API Javadocs - The Servlet 2.4 API Javadocs.
  • JSP API Javadocs - The JSP 2.0 API Javadocs.
Apache Tomcat Developers

下面的文献是提供给那些希望参与开发Apache Tomcat 项目的Java程序员的。

  • 从源文件构建 - 列举了下载 Apache Tomcat 5 源程序（包括其他关联程序包）的下载，和如何从这些 源码中构建一个二进制版本。
  • 变更日志 - 详细列出Apache Tomcat 不同版本的变化情况。
  • 进程 - Apache Tomcat 的开发进程。
  • 开发者 - Apache Tomcat 的开发者们。.
  • 功能说明书 - Apache Tomcat 5所使用的 Catalina servlet容器的必需的功能说明。
  • Catalina Javadocs - Catalina servlet容器和其附属部件的Javadoc API文档。
  • Jasper Javadocs - Apache Tomcat 5所使用的 Jasper JSP 容器的Javadoc API 文档。
  • Apache Tomcat 体系结构 - Apache Tomcat 服务器的体系结构文档。


Apache Tomcat 5.5 Servlet/JSP 容器 - 简介

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

简介
介绍

不管是系统管理员还是web开发人员， 在开始使用Tomcat之前要先熟悉一些重要的信息。 这里对Tomcat容器背后的一些概念和术语进行简单介绍。同时，也告诉你在需要时到 哪里去寻找帮助。

名词术语

在阅读本文的过程中，你会遇到一些名词， 有的是Tomcat 特有的，有的是 Servlet 和 JSP 规范(specifications)里 定义的。

  • context(上下文)--概括地说, a Context 就是一个网络应用程序。
  • Term2 - This is it.
  • Term3 - This is it!
Directories and Files

在整个文献中，你会注意到许多地方提到 $CATALINA_HOME。 它代表Tomcat安装(installation)的根目录。 当我们说“你可以在 $CATALINA_HOME/README.txt文件里找到这些信息"，我们是指去Tomcat安装根目录 读README.txt文件。

下面是一些关键的Tomcat目录, 它们都和$CATALINA_HOME有关系。

  • /bin -- 启动，关闭和其它脚本文件。以*.sh 结束 的文件(Unix系统)是与*.bat文件(Window 系统)功能相同的复本。因为 Win32 命令行缺少一些功能,这里附上一些额外的文件。
  • /conf --配置文件(configuration file) 和相关的 DTDs（文档类型定义）。 最重要的文件是server.xml。 这是tomcat里面最重要的配置文件。
  • / logs --Log文件默认存放目录。
  • /webapps--这里存放你的网络应用程序。
配置 Tomcat

这一部分使你熟悉一些在容器配置(configurations of the container)时需要的基本信息。

所有配置文件的信息都是在启动时加载的（read at startup), 这就是说任何对文件的 更改都需要重新启动这个容器才会生效。

在哪获得更多帮助信息？

尽管我们努力确保这些文档易读和易懂，但还是有可能疏漏了一些东西。 如果你遇到 问题，可参看下面提供的各种网址和邮件列表。

因为 Tomcat 5 是 Tomcat 的新发行版，所以有些问题和解答会与Tomcat 4.x 版有所 不同。 当你在网上查找时，有些文档是针对于3.x 和 4.x 版本，而不适用于 Tomcat 5。 把 3.x 和 4.x 版本的配置用在 Tomcat 5 上， 在大多数情况下会行不通， 因为（Tomcat 5）在很多地方同tomcat 3.x4.x不同，比如说 server.xml 文件。

  • 当前文章－－大部分疑难问题的文档都包含在此。一定要充分阅读相关的资料，这样会 节省你不少时间和劳力。什么都比不上搜遍整个网络去找一直摆在你面前的答案最让人 难受了。
  • Tomcat FAQ，由开发人员维护。
  • Tomcat WIKI
  • 在 jGuru上的Tomcat FAQ
  • Tomcat 邮件列表存档－　许多网站有Tomcat的邮件列表的存档。因为这些链接(links)经常改变， 可以点击 Google 去查找。
  • Tomcat 用户邮件列表- 可以从这里 申请。如果你没有得到回音，很有可能你的问题已经在存档或ＦＡＱ中得到解答。尽管 一些普通的程序问题会被问到，也会被解答，但是你的问题最好更加细致或特别一些。
  • Tomcat -开发人员邮件列表- 可以从这里 申请。这个列表是专门保留给开发Tomcat讨论用的。关于Tomcat配置 的问题，或者在运行程序中遇到问题，最好去TOMCAT用户邮件列表。

如果你认为有什么内容有必要列在这里，请尽可能在TOMCAT开发人员邮件列表让我们知道， 或者给任何一个文档作者发电子邮件。


Apache Tomcat 5.5 Servlet/JSP 容器 - Jasper 2 JSP Engine How To

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Jasper 2 JSP Engine How To
Table of Contents

简介
配 置
生产配置
网络应用程序编译
使用 Jikes

Introduction

Tomcat 5.0使用Jasper 2 JSP Engine来实现 JavaServer Pages 2.0规范。

Jasper 2被重新设计后，它的性能比原来的Jasper有极大的改善。除了基本的代码改进 以外，还有下面这些变化：

  • JSP Custom Tag Pooling - Java对象例示的JSP客户自定义标签 (JSP Custom Tags)现在可以被汇集起来重新使用。这极大地提高了使用客户自定义 标签的JSP页面的性能。
  • Background JSP compilation - 如果你更改了已经被编译过的JSP 页面，Jasper 2可以在后台重新编译这个页面。先前编译过的JSP页面还是被用来提供 服务。一旦新的页面被编译好了，它就可以取代旧的页面。这有助于提高你的JSP页面 在生产服务器上的可使用性。
  • Recompile JSP when included page changes - Jasper 2现在可以 在编译时探测到什么时候JSP里的一个页面被更改过，并重新编译父JSP。
  • JDT used to compile JSP pages - Eclipse的JDT Java编译器现在 用来完成JSP中java源代码的编译工作。这个编译器加载源代码依赖于容器的类加载器。 Ant和javac依旧可以使用。

Jasper是通过使用servlet类org.apache.jasper.servlet.JspServlet来 实现的。

Configuration

默认的Jasper是被配置用来开发web应用程序的。关于使用于Tomcat生产服务器上的 Jasper配置信息，参看生产配置( Production Configuration)这一章。

用来实现Jasper的servlet是通过使用你的全局 $CATALINA_BASE/conf/web.xml文件里面的参数来配置的。

  • checkInterval - 如果development设置为false，reloading设置为 true，后台编译就可以实现了。checkInterval是检查一个JSP页面是否需要被重新编译 的秒数间隔。默认值是300秒。
  • compiler - 推荐使用Ant来编译JSP页面。具体信息请查阅Ant的 文档。如果没有被赋值，则默认的Eclipse JDT Java编译器将被用来代替Ant。 没有默认值。
  • classdebuginfo - 类文件在编译时是否显示排错(debugging)提示信息？ true 或false，默认是true。
  • classpath - 在编译产生的servlets时，应该使用什么class path呢？ 默认的classpath是基于当前web应用程序动态地产生的。
  • compilerSourceVM - 编译源文件时采用的JDK版本是什么？(默认是 JDK 1.4)
  • compilerTargetVM - 生成文件是采用的JDK版本是什么？(默认是 JDK1.4)
  • development - Jasper是否处于开发模式(将在每一次存取时检查JSP 是否被修改)？true 或 false，默认值是true 。
  • enablePooling - 确定标签处理池(tag handler pooling)是否可被 使用。true 或 false，默认值是true 。
  • engineOptionsClass - 允许指定的类来配置Jasper。如果没有指定， 则使用默认的Servlet内置参数(EmbeddedServletOptions)。
  • ieClassId - 当使用&lt;jsp:plugin&gt;标签时要发送给Internet Explorer的class-id值. 默认形式是clsid:8AD9C840-044E-11D1-B3E9-00805F499D93 。
  • fork - 是否让Ant把JSP页面编译进行分叉(fork)，这样一来编译就 可以在与Tomcat在不同的JVM里执行? true 或 false，默认值是true 。
  • javaEncoding - 用来产生java源文件的Java文件编码。默认是UTF8。
  • genStringAsCharArray - 是否把字符串转换为字符数组？在某些 情况下会用到。默认 false.
  • keepgenerated - 是否应该保留为每一页产生的Java源代码，而 不是把它删除掉？true 或 false , 默认值是true 。
  • mappedfile - 是否应该为每一行输入打印一个静态说明，来使排错 变得容易？true 或 false , 默认值是true 。
  • modificationTestInterval - Checks for modification for a given JSP file (and all its dependent files) will be performed only once every specified amount of seconds. Setting this to 0 will cause the JSP to be checked on every access. Default is 4 seconds.
  • reloading - Should Jasper check for modified JSPs? true or false, default false.
  • scratchdir - 在编译JSP页面的时候，应该使用什么scratch目录？默认的目录是当前web应用程序的工作目录。
  • trimSpaces - 样板本文里actions或指令之间的空白空间是否应该被修剪？默认值是false 。

The Java compiler from Eclipse JDT in included as the default compiler. It is an advanced Java compiler which will load all dependencies from the Tomcat class loader, which will help tremendously when compiling on large installations with tens of JARs. On fast servers, this will allow sub-second recompilation cycles for even large JSP pages. This new compiler will be updated to support the Java 5 syntax as soon as possible.

Apache Ant, which was used in previous Tomcat releases, can be used instead instead of the new compiler by simply removing the common/lib/jasper-compiler-jdt.jar file, and placing the ant.jar file from the latest Ant distribution in the common/lib folder. If you do this, you also need to use the "javac" argument to catalina.sh.

Production Configuration

The main JSP optimization which can be done is precompilation of JSPs. However, this might not be possible (for example, when using the jsp-property-group feature) or practical, in which case the configuration of the Jasper servlet becomes critical.

在生产Tomcat服务器里使用Jasper 2时，你应该考虑在默认的配置上进行下列修改。

  • development - To disable on access checks for JSP pages compilation set this to false.
  • genStringAsCharArray - To generate slightly more efficient char arrays, set this to true.
  • modificationTestInterval - If development has to be set to true for any reason (such as dynamic generation of JSPs), setting this to a high value will improve performance a lot.
  • trimSpaces - To remove useless bytes from the response, set this to true.

Web Application Compilation

Using Ant is the preferred way to compile web applications using JSPC. Use the script given below (a similar script is included in the "deployer" download) to precompile a webapp:

<project name="Webapp Precompilation" default="all" basedir=".">

  <target name="jspc">

    <taskdef classname="org.apache.jasper.JspC" name="jasper2" >
      <classpath id="jspc.classpath">
        <pathelement location="${java.home}/../lib/tools.jar"/>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/server/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
      </classpath>
    </taskdef>

    <jasper2
             validateXml="false"
             uriroot="${webapp.path}"
             webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
             outputDir="${webapp.path}/WEB-INF/src" />

  </target>

  <target name="compile">

    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    <mkdir dir="${webapp.path}/WEB-INF/lib"/>

    <javac destdir="${webapp.path}/WEB-INF/classes"
           optimize="off"
           debug="on" failonerror="false"
           srcdir="${webapp.path}/WEB-INF/src"
       excludes="**/*.smap">
      <classpath>
        <pathelement location="${webapp.path}/WEB-INF/classes"/>
        <fileset dir="${webapp.path}/WEB-INF/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/common/classes"/>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/shared/classes"/>
        <fileset dir="${tomcat.home}/shared/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
      </classpath>
      <include name="**" />
      <exclude name="tags/**" />
    </javac>

  </target>

  <target name="all" depends="jspc,compile">
  </target>

  <target name="cleanup">
      <delete>
        <fileset dir="${webapp.path}/WEB-INF/src"/>
        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
      </delete>
  </target>

</project>

下面的命令行可以用来运行这个script(用Tomcat基础路径和指向应该被预编译的webapp的路径来代替那些记号)。

$ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>

然后,对于在预编译过程中产生的servlets的声明和映射必须被加入到网络程序部署描述符里去。把${webapp.path}/WEB-INF/generated_web.xml插入到${webapp.path}/WEB-INF/web.xml文件应该被放置的地方。重新启动web程序(使用the manager)，并测试它以验证预编译过的servlets能正常运行。网络程序部署描述符里适当的标记(token)也可以被用来通过Ant过滤功能自动插入所产生servlets声明和映射。事实上这就是Tomcat发布的所有webapps作为build过程的一部分是怎样自动被编译的。

At the jasper2 task you can use the option addWebXmlMappings for automatic merge the ${webapp.path}/WEB-INF/generated_web.xml with the current web application deployment descriptor at ${webapp.path}/WEB-INF/web.xml. When you want to use Java 5 feature inside your jsp's, add the following javac compiler task attributes: source="1.5" target="1.5". For live application you can also compile with optimize="on" and without debug info debug="off".

When you don't want to stop the jsp generation at first jsp syntax error, use failOnError="false"and with showSuccess="true" all successfull jsp to java generation are printed out. Sometimes it is very helpfull, when you cleanup the generate java source files at ${webapp.path}/WEB-INF/src and the compile jsp servlet classes at ${webapp.path}/WEB-INF/classes/org/apache/jsp.

Hints:

  • When you switch to another tomcat release, then regenerate and recompile your jsp's with this version again!
  • Use java system property at server runtime to disable tag pooling org.apache.jasper.runtime.JspFactoryImpl.USE_POOL=false. and limit the buffering with org.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true. Note that changing from the defaults may affect performance, but depending on the application.

Using Jikes

如果你想要使用 Jikes来编译JSP页面：

  • From your Ant installation, copy ant.jar and (if it's available: Ant 1.5 and later) ant-launcher.jar to $CATALINA_BASE/common/lib.
  • 下载并安装jikes。jikes必须支持-encoding选项。执行jikes -help 来证实jikes被建造能支持-encoding。
  • 把init参数编译器设置为jikes 。
  • 在启动Tomcat时，定义属性-Dbuild.compiler.emacs=true， 把它加入到你的CATALINA_OPTS环境变量中。这改变了jikes输出错误信息的方式，使它与Jasper相兼容。
  • 如果你得到一个错误报告说jikes不能使用UTF8编码，去试试把init参数javaEncoding设置为ISO-8859-1。


Apache Tomcat 5.5 Servlet/JSP 容器 - JNDI Datasource HOW-TO

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

JNDI Datasource HOW-TO
Table of Contents

简介
数据库连接池(DBCP)配置
非DBCP解决办法
Oracle 8i with OCI client
常见问题

Introduction

JNDI数据源配置在JNDI-Resources-HOWTO里面有详尽的说明，tomcat用户反馈回来的信息显示个别的特殊配置可能会很易出错。

这里为tomcat用户展示了一些通用数据库配置的例子，以及数据库使用的一些通常的提示。

因为这些注解是从tomcat用户反馈的配置信息派生而来，所以如果你有其他测试过的配置并且觉得能对更多其他用户会有用处，或者你觉得我们可以对这一部分有所改进，请让我们知道。

Please note that JNDI resource configuration has changed somewhat between Tomcat 5.0.x and Tomcat 5.5.x. You will most likely need to modify your JNDI resource configurations to match the syntax in the example below in order to make them work in Tomcat 5.5.x.

Also, please note that JNDI DataSource configuration in general, and this tutorial in particular, assumes that you have read and understood the Context and Host configuration references, including the section about Automatic Application Deployment in the latter reference.

Database Connection Pool (DBCP) Configurations

DBCP对JDBC 2.0提供支持。 使用1.4 JVM DBCP的系统会支持JDBC 3.0。如果你已经使用过1.4 JVM DBCP以及JDBC 3.0特性，请让我们知道。

See the DBCP documentation for a complete list of configuration parameters.

Installation

DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:

  • Jakarta-Commons DBCP 1.0
  • Jakarta-Commons Collections
  • Jakarta-Commons Pool
These libraries are located in a single JAR at $CATALINA_HOME/common/lib/naming-factory-dbcp.jar. However, only the classes needed for connection pooling have been included, and the packages have been renamed to avoid interfering with applications.

Preventing dB connection pool leaks

一个数据库连接池产生并管理一系列与数据库的连接。再回收和再利用现存的数据库连接比打开一个新的连接要有效率的多。

连接池也有一个问题。那就是网络程序必须专门关闭ResultSet's, Statement's, 和 Connection's 。 网络程序若没有关闭这些资源，会造成这些资源再也不能被重新使用，产生数据库连接池“泄露”的后果。如果没有别的连接可被使用，最终会造成你的网络程序数据库连接失败。

对于这个问题有一个解决办法。Jakarta-Commons DBCP可以被配置来追踪和修复这些被遗弃的数据库连接。它不仅可以修复它们，而且可以对那些打开这些资源但又从来没有关闭它们的代码展开一层层追踪。

To configure a DBCP DataSource so that abandoned dB connections are removed and recycled add the following attribute to the Resource configuration for your DBCP DataSource:

            removeAbandoned="true"
当可被利用的数据库连接降到很低，DBCP会修复并回收它能发现的被放弃的数据库连接。默认值是false 。

Use the removeAbandonedTimeout attribute to set the number of seconds a dB connection has been idle before it is considered abandoned.

            removeAbandonedTimeout="60"
删除被放弃的连接的默认时间是300秒。

The logAbandoned attribute can be set to true if you want DBCP to log a stack trace of the code which abandoned the dB connection resources.

            logAbandoned="true"
默认值是false 。

MySQL DBCP Example

简介

下面这些的MySQL和JDBC驱动的版本可以运作：

  • MySQL 3.23.47, MySQL 3.23.47 using InnoDB,, MySQL 3.23.58, MySQL 4.0.1alpha
  • Connector/J 3.0.11-stable (the official JDBC Driver)
  • mm.mysql 2.0.14 (an old 3rd party JDBC Driver)

在你开始之前，别忘记复制一份JDBC驱动的jar文件到$CATALINA_HOME/common/lib里面。

MySQL 配置

你一定要遵循这些指导说明，因为变动会产生问题。

产生一个新的测试用户，一个新的数据库和一个测试表格。你的MySQL用户必须要有个指派的密码。如果你试图用空密码连接，驱动会失败。

mysql&gt; GRANT ALL PRIVILEGES ON *.* TO javauser@localhost
-&gt; IDENTIFIED BY 'javadude' WITH GRANT OPTION;
mysql&gt; create database javatest;
mysql&gt; use javatest;
mysql&gt; create table testdata (
-&gt; id int not null auto_increment primary key,
-&gt; foo varchar(25),
-&gt; bar int);
注意：当测试完成以后，上面的用户应该被删除掉。

下一步，在testdata表格中加入一些测试数据。

mysql&gt; insert into testdata values(null, 'hello', 12345);
Query OK, 1 row affected (0.00 sec)

mysql&gt; select * from testdata;
+----+-------+-------+
| ID | FOO | BAR |
+----+-------+-------+
| 1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)

mysql&gt;

server.xml 配置

通过向$CATALINA_HOME/conf/server.xml里面加入一个声明来在Tomcat里配置JNDI DataSource。

Add this in between the </Context> tag of the examples context and the </Host> tag closing the localhost definition. If there is no such tag, you can add one as illustrated in the Context and Host configuration references, and repeated below for your convenience.

<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

    <!-- maxActive: Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to 0 for no limit.
         -->

    <!-- maxIdle: Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->

    <!-- maxWait: Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->

    <!-- username and password: MySQL dB username and password for dB connections  -->

    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
         -->

    <!-- url: The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->

  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/>

</Context>

web.xml 配置

现在为这个测试程序产生一个WEB-INF/web.xml 文件。

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

测试代码

现在产生一个简单的test.jsp页面供以后使用。

&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %&gt;
&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt;

&lt;sql:query var="rs" dataSource="jdbc/TestDB"&gt;
select id, foo, bar from testdata
&lt;/sql:query&gt;

&lt;html&gt;
&lt;head&gt;
&lt;title&gt;DB Test&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h2&gt;Results&lt;/h2&gt;

&lt;c:forEach var="row" items="${rs.rows}"&gt;
Foo ${row.foo}&lt;br/&gt;
Bar ${row.bar}&lt;br/&gt;
&lt;/c:forEach&gt;

&lt;/body&gt;
&lt;/html&gt;

JSP页面利用JSTL 's SQL 和 Core taglibs 。你可以从Sun's Java Web Services Developer Pack 得到它，或者从Jakarta Taglib Standard 1.1 project 得到它——确保你拿到的是1.1.x发行版。当你有了JSTL以后，把jstl.jar和standard.jar复制到你的网络程序的WEB-INF/lib目录里。

最后把你的网络程序作为DBTest.war的warfile形式，或以名叫DBTest的子目录形式部署到$CATALINA_HOME/webapps 里面。

当部署完成后，在一个浏览器里指向http://localhost:8080/DBTest/test.jsp就可以看到你辛勤劳动的成果了。

Oracle 8i, 9i & 10g

简介

Oracle requires minimal changes from the MySQL configuration except for the usual gotchas :-)

Drivers for older Oracle versions may be distributed as *.zip files rather than *.jar files. Tomcat will only use *.jar files installed in $CATALINA_HOME/common/lib. Therefore classes111.zip or classes12.zip will need to be renamed with a .jar extension. Since jarfiles are zipfiles, there is no need to unzip and jar these files - a simple rename will suffice.

Some early versions of Tomcat 4.0 when used with JDK 1.4 will not load classes12.zip unless you unzip the file, remove the javax.sql.* class heirarchy and rejar.

For Oracle 9i onwards you should use oracle.jdbc.OracleDriver rather than oracle.jdbc.driver.OracleDriver as Oracle have stated that oracle.jdbc.driver.OracleDriver is deprecated and support for this driver class will be discontinued in the next major release.

server.xml 配置

In a similar manner to the mysql config above, you will need to define your Datasource in your server.xml file. Here we define a Datasource called myoracle using the thin driver to connect as user scott, password tiger to the sid called mysid. (Note: with the thin driver this sid is not the same as the tnsname). The schema used will be the default schema for the user scott.

使用OCI驱动只需要在URL字串里简单地把thin改变成oci 。

<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>

web.xml 配置

你应该确保在产生web.xml文件时，尊重DTD定义的元素排列顺序。

&lt;resource-ref&gt;
&lt;description&gt;Oracle Datasource example&lt;/description&gt;
&lt;res-ref-name&gt;jdbc/myoracle&lt;/res-ref-name&gt;
&lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
&lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;

代码示例

你可以使用与上面相同的程序例子(假设你产生了必需的数据库实例，表格等)来代替Datasource代码，它可能象这样：

Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
//etc.
PostgreSQL

简介

PostgreSQL is configured in a similar manner to Oracle.

1. Required files

Copy the Postgres JDBC jar to $CATALINA_HOME/common/lib. As with Oracle, the jars need to be in this directory in order for DBCP's Classloader to find them. This has to be done regardless of which configuration step you take next.

2. Resource configuration

You have two choices here: define a datasource that is shared across all Tomcat applications, or define a datasource specifically for one application.

2a. Shared resource configuration

Use this option if you wish to define a datasource that is shared across multiple Tomcat applications, or if you just prefer defining your datasource in this file.

This author has not had success here, although others have reported so. Clarification would be appreciated here.

<Resource name="jdbc/postgres" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://127.0.0.1:5432/mydb"
          username="myuser" password="mypasswd" maxActive="20" maxIdle="10" maxWait="-1"/>

2b. Application-specific resource configuration

Use this option if you wish to define a datasource specific to your application, not visible to other Tomcat applications. This method is less invasive to your Tomcat installation.

Create a resource definition file for your application defining the datasource. This file must have the same name as your application, so if your application deploys as someApp.war, this filename must be someApp.xml. This file should look something like the following.

<Context path="/someApp" docBase="someApp"
   crossContext="true" reloadable="true" debug="1">

<Resource name="jdbc/postgres" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://127.0.0.1:5432/mydb"
          username="myuser" password="mypasswd" maxActive="20" maxIdle="10"
maxWait="-1"/>
</Context>

web.xml 配置

&lt;resource-ref&gt;
&lt;description&gt;postgreSQL Datasource example&lt;/description&gt;
&lt;res-ref-name&gt;jdbc/postgres&lt;/res-ref-name&gt;
&lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
&lt;res-auth&gt;Container&lt;/res-auth&gt;
&lt;/resource-ref&gt;

4. Accessing the datasource

When accessing the datasource programmatically, remember to prepend java:/comp/env to your JNDI lookup, as in the following snippet of code. Note also that "jdbc/postgres" can be replaced with any value you prefer, provided you change it in the above resource definition file as well.

InitialContext cxt = new InitialContext();
if ( cxt == null ) {
   throw new Exception("Uh oh -- no context!");
}

DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );

if ( ds == null ) {
   throw new Exception("Data source not found!");
}
Non-DBCP Solutions

这些办法要么是利用单个数据库连接(建议仅作测试用，而不要作其它用处)，要么是其他pooling技术。

Oracle 8i with OCI client
Introduction

虽然没有严格强调使用OCI client来产生JNDI DataSource，这里的这些注解可以和上面所讲的Oracle and DBCP方法合在一起。

为了使用OCI驱动，你必须要安装一个Oracle client。你应该从cd安装Oracle8i(8.1.7) client ，然后再从otn.oracle.com下载相适宜的JDBC/OCI driver(Oracle8i 8.1.7.1 JDBC/OCI Driver)。

在把classes12.zip文件重新命名为classes12.jar以后，把它复制到Tomcat的$CATALINA_HOME/common/lib里面。根据你使用的Tomcat和JDK 版本，你还可能必须从这个文件删除javax.sql.* 类。

Putting it all together

确保在你的$PATH or LD_LIBRARY_PATH (possibly in $ORAHOME\bin ) 有ocijdbc8.dll or .so ，并且确定使用一个简单的测试程序System.loadLibrary("ocijdbc8")可以装载native library。

你下一步应该产生一个简单的测试servlet或jsp，要有下面这些关键行：

DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
conn =
DriverManager.getConnection("jdbc:oracle:oci8:@database","username","password");

这里数据库是host:port:SID的形式。现在如果你想试图访问你测试的servlet/jsp 的URL，你得到的是一个ServletException，造成它的根本原因在于java.lang.UnsatisfiedLinkError:get_env_handle 。

首先，这个UnsatisfiedLinkError表明你有下列问题：

  • JDBC类文件和Oracle client版本不相配。发给你的消息会说明是因为一个必须的library不能被找到。例如，你可能把Oracle Version 8.1.6里边的一个classes12.zip文件与与Version 8.1.5 Oracle client 一起使用。classeXXXs.zip文件与Oracle client软件的版本必须相配。
  • 一个$PATH , LD_LIBRARY_PATH 问题。
  • 据报道，忽略你从otn下载的驱动，使用$ORAHOME\jdbc\lib目录里的classes12.zip文件也行得通。

下一步，你可能会遇到错误ORA-06401 NETCMN: invalid driver designator

Oracle文件说明会说："Cause: The login (connect) string contains an invalid driver designator. Action: Correct the string and re-submit." 把数据库的连接字串( host:port:SID 的形式)改变成这个样：(description=(address=(host=myhost)(protocol=tcp)(port=1521))(connect_data=(sid=orcl)))

Ed. Hmm, I don't think this is really needed if you sort out your TNSNames - but I'm not an Oracle DBA :-)

Common Problems

这里是一些网络程序中使用数据库常常遇到的问题，以及怎样解决它们的提示。

Intermittent dB Connection Failures

Tomcat在一个JVM里运行。JVM定期地执行垃圾收集工作(GC)来删除不再被使用的对象。当JVM执行GC时，Tomcat暂停。如果配置的连接数据库的最长时间少于垃圾收集所花费的时间，你就可能得到一个数据库连接失败。

要收集关于垃圾收集所花费的时间，在启动Tomcat时，把-verbose:gc加入到你的CATALINA_OPTS环境变量中。当垃圾收集(gc)工作时，你的$CATALINA_BASE/logs/catalina.out日志文件会记录所有的关于垃圾收集的数据，包括垃圾收集需要多长时间。

当你的JVM调试正确率为99%时，垃圾收集工作花费的时间比一秒钟还少。收尾工作仅仅花几秒钟。垃圾收集很少用10秒钟以上的时间。

确保数据库连接时间设置为10-15秒。对于DBCP来说，用maxWait参数来设置。

Random Connection Closed Exceptions

当一个请求从连接池得到一个数据库连接，然后关闭它两次，就会产生这些异常。当使用一个连接池时，关闭连接仅仅是把它返回到池中再被另外的请求使用，而不时把这个连接断掉。Tomcat使用多线程来处理同时发生的请求。这里的例子是关于事件(events)顺序怎样在Tomcat里造成这类错误：

Request 1 running in Thread 1 gets a db connection.

Request 1 closes the db connection.

The JVM switches the running thread to Thread 2

Request 2 running in Thread 2 gets a db connection
(the same db connection just closed by Request 1).

The JVM switches the running thread back to Thread 1

Request 1 closes the db connection a second time in a finally block.

The JVM switches the running thread back to Thread 2

Request 2 Thread 2 tries to use the db connection but fails
because Request 1 closed it.
这里的例子是一个写得不错的关于使用从连接池获得的数据库连接的代码。
Connection conn = null;
Statement stmt = null; // Or PreparedStatement if needed
ResultSet rs = null;
try {
conn = ... get connection from connection pool ...
stmt = conn.createStatement("select ...");
rs = stmt.executeQuery();
... iterate through the result set ...
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
... deal with errors ...
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null) {
try { rs.close(); } catch (SQLException e) { ; }
rs = null;
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
}

Context versus GlobalNamingResources

请注意虽然在上面的说明中把JNDI声明放在一个Context元素里面，有可能，而且有时更需要把这些声明放在服务器配置文件的GlobalNamingResources区域。被放置在GlobalNamingResources区域的资源将会被服务器的Contexts共享。

JNDI Resource Naming and Realm Interaction

为了让Realms能运作，这个realm必须按照&lt;GlobalNamingResources&gt; 或 &lt;Context&gt; 章节定义的那样指向数据源，而不是指向用&lt;ResourceLink&gt;重新命名的数据源。


Apache Tomcat 5.5 Servlet/JSP 容器 - JNDI Resources HOW-TO

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

JNDI Resources HOW-TO
Introduction

Tomcat 5以一个可与Java2企业版(J2EE)应用服务器相容的方式，提供给每个在它里面运行的网络程序一个JNDI InitialContext执行实例。J2EE标准在/WEB-INF/web.xml文件里提供了一系列标准元素，可用来查询资源；被这些元素索引的资源还需要根据不同的应用服务器来配置。

对Tomcat 5来说，每个网络应用的InitialContext是在<Context>元素中被配置的，而<Context>元素最好在该网络应用的上下文XML文件(或META-INF/context.xml)中被指定，或者在$CATALINA_HOME/conf/server.xml文件中被指定。

Tomcat 5还为整个服务器所使用的全球性资源提供一个单独的命名空间(namespace)。这些资源配置在$CATALINA_HOME/conf/server.xml文件的 <GlobalNameingResources>元素中。你可以通过<ResourceLink>元素把这些资源提供给各个网络程序。

在这些元素内定义的资源可以被你的程序部署描述符( /WEB-INF/web.xml )里的下列这些元素引用：

  • <env-entry> - 环境变量输入，这个单个值参数(single-value parameter)可以用来配置网络程序如何运行。
  • <resource-ref> - 资源引用名，它通常指向该资源的对象(object)工厂，如JDBC 数据源, a JavaMail Session，或者作为自己编写(custom)的对象工厂配置在Tomcat 5里边。
  • <resource-env-ref> - 资源环境索引，这是Servlet 2.4版本里新加入的资源引用(resource-ref)变量，对那些不要求用户认证的资源来说，这个变量比较容易配置。

InitialContext是在网络程序最初被部署到服务器上时配置的，并且所有的网络程序可以使用它(仅供只读访问)。所有配置的条目和资源都被放置在JNDI的java:comp/env 命名空间中。以下是以JDBC DataSource(数据源)为例来说明如何访问一个资源——它看起来象这样：

// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");

// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

参看下面两个规范，了解更多关于编码JNDI APIs的信息，以及Java2 企业版(J2EE)服务器所支持的相关性能：

  • Java Naming and Directory Interface (包括在JDK 1.4版内, 在这之前的版本需要另外下载)
  • J2EE Platform Specification (参看第五章Naming )
Configuring JNDI Resources

Each available JNDI Resource is configured based on inclusion of the following elements in the <Context> element:

  • <Environment> - 配置环境变量的名字和值,网络程序可通过JNDI InitialContext 来查询(相当于在网络程序部署描述符中包括一个<env-entry>元素)。
  • <Resource> - 配置程序可以使用的资源名字和数据类型(相当于 在网络程序部署描述符中包括一个<resource-ref>元素)。
  • <ResourceLink> - 为定义在全球性JNDI context内的资源加上一个链连。让网络程序可以使用这个链连访问定义在<GlobalNamingResources>里的资源，这个<GlobalNamingResources>是<Server>的子元素。
  • <Transaction> - Add a resource factory for instantiating the UserTransaction object instance that is available at java:comp/UserTransaction.

任何数目的上述元素都可以套嵌在<Context>元素里（这些元素必须是和某个特定的网络应用程序相关的）。

另外，包含在程序部署描述符(/WEB-INF/web.xml)里的所有<env-entry>元素的 名字和值也都会加入到initial context中，只有<Environment>元素 允许(通过把override属性设置为"true")的情况下，<env-entry>元素中 的值才会覆盖conf/server.xml 中相应的值。

全球性资源可以定义在全服务器的JNDI context，把上面描述的资源元素加到<Server>的子元素<GlobalNamingResources>中，并且用<ResourceLink>把它包括在每个网络程序的(per-web-application)上下文中。

Tomcat Standard Resource Factories

Tomcat 5包含了一系列标准资源工厂来为你的网络程序服务，但又给你配置适度的弹性(在 $CATALINA_HOME/conf/server.xml 里)而不需要修改网络程序或部署描述符。下列章节详细描述了如何配置和使用这些标准资源工厂。

关于怎样产生，安装，配置和使用你自己编写的资源工厂类，参看Adding Custom Resource Factories。

注意——在标准资源工厂当中，只有"JDBC Data Source" 和 "User Transaction" 是必须让所有执行Java2企业版(J2EE)规范的平台使用。其他的标准资源工厂，以及你自己写的资源工厂只对Tomcat有效，而不能假设可让其他容器使用。

Generic JavaBean Resources

简介

这个资源工厂可以用来产生任何遵守标准JavaBeans命名习惯的Java类的对象(例如，它具有一个没有变量的构造式，具有遵守setFoo()命名模式的属性设置方法)。每次lookup()输入，这个资源工厂就会产生一个新的相称的bean class实例。

使用这一设施的必需步骤如下：

产生你的JavaBean类

产生JavaBean类，让它每一次要查找资源工厂时就被实例化(instantiated)。在这个例子中，假设你产生一个叫做com.mycompany.MyBean的类，它看起来象这样：

package com.mycompany;

public class MyBean {

private String foo = "Default Foo";

public String getFoo() {
return (this.foo);
}

public void setFoo(String foo) {
this.foo = foo;
}

private int bar = 0;

public int getBar() {
return (this.bar);
}

public void setBar(int bar) {
this.bar = bar;
}

}

声明你的资源要求

下一步，修改你的网络程序部署描述符( /WEB-INF/web.xml ) 来声明JNDI名字，你将要求产生这个bean的新的实例在其名下。最简单的方法是象这样来使用<resource-env-ref>元素：

&lt;resource-env-ref&gt;
&lt;description&gt;
Object factory for MyBean instances.
&lt;/description&gt;
&lt;resource-env-ref-name&gt;
bean/MyBeanFactory
&lt;/resource-env-ref-name&gt;
&lt;resource-env-ref-type&gt;
com.mycompany.MyBean
&lt;/resource-env-ref-type&gt;
&lt;/resource-env-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

典型的使用这个资源环境索引的编码看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
bean.getBar());

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到$CATALINA_HOME/conf/server.xml文件中，并把它套嵌在这个网络应用程序的Context元素里。

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="org.apache.naming.factory.BeanFactory"
            bar="23"/>
  ...
</Context>

注意资源名称(这里是bean/MyBeanFactory)必须与网络程序部署描述符里指定的值相对映。我们也还要初始化bar property的值，这会在返回新的bean之前引起调用setBar(23)。因为我们没有初始化foo property(尽管我们也可以这样做)，bean会包含它的构造器设置的任何默认值。

JavaMail Sessions

简介

在许多网络应用中，发送电子邮件是系统功能必须的一部分。Java Mail API 使得这一处理过程相对直截了当，但是客户的应用程序必须要了解许多配置的详细情况(包括用来发送消息的SMTP主机名字)。

Tomcat 5包括一个产生javax.mail.Session实例的标准资源工厂，它已经与被server.xml配置过的SMTP服务器连接好了。通过这种办法，程序完全和电子邮件服务器配置环境中的变化分隔开了——在任何需要的时候，只要请求和接受一个预先配置过的session就行了。

这个过程必需的步骤概括如下：

声明你的资源要求

你要做的第一件事就是修改网络程序部署描述符(/WEB-INF/web.xml)来声明JNDI名称，你可在其名下查看预先配置过的sessions。根据习惯性，所有这样的名称都必须围绕着邮件的subcontext而派生(与标准的java:comp/env naming context 相关，这个naming context是所有的资源工厂的根)。 一个典型的web.xml看起来象这样：

&lt;resource-ref&gt;
&lt;description&gt;
Resource reference to a factory for javax.mail.Session
instances that may be used for sending electronic mail
messages, preconfigured to connect to the appropriate
SMTP server.
&lt;/description&gt;
&lt;res-ref-name&gt;
mail/Session
&lt;/res-ref-name&gt;
&lt;res-type&gt;
javax.mail.Session
&lt;/res-type&gt;
&lt;res-auth&gt;
Container
&lt;/res-auth&gt;
&lt;/resource-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

一个典型的使用这个资源索引的例子看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from"));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);

注意，这个程序使用的是与网络程序部署描述符里声明的资源索引相同的名字。这是与在$CATALINA_HOME/conf/server.xml 里配置的资源工厂相映射的，描述如下：

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到$CATALINA_HOME/conf/server.xml文件中，并把它套嵌在这个网络应用程序的Context元素里。

<Context ...>
  ...
  <Resource name="mail/Session" auth="Container"
            type="javax.mail.Session"
            mail.smtp.host="localhost"/>
  ...
</Context>

注意，资源的名字(这里是mail/Session)必须与网络程序部署描述符里指定的值相映射。客户化(自己指定)mail.smtp.host参数值，让它指向为你的网络(network)提供SMTP服务的服务器那里。

安装JavaMail libraries

Download the JavaMail API. The JavaMail API requires the Java Activation Framework (JAF) API as well. The Java Activation Framework can be downloaded from Sun's site.

This download includes 2 vital libraries for the configuration; activation.jar and mail.jar. Unpackage both distributions and place them into $CATALINA_HOME/common/lib so that they are available to Tomcat during the initialization of the mail Session Resource. Note: placing these jars in both common/lib and a web application's lib folder will cause an error, so ensure you have them in the $CATALINA_HOME/common/lib location only.

应用程序示例(Example Application)

这个Tomcat包含的/examples 程序里有一个利用这一资源工厂的例子。你可通过"JSP Examples"链连来访问。实际上发送邮件的这个servlet的源代码是在/WEB-INF/classes/SendMailServlet.java里面。

警告——默认的配置假设在局部主机的端口25(port 25)有一个SMTP服务器的列单。如果不是这样，去编辑一下$CATALINA_HOME/conf/server.xml文件，把mail.smtp.host的参数值修改成你的网络SMTP服务器的主机名字。

JDBC Data Sources

简介

许多网络程序需要通过JDBC驱动来访问数据库，从而来支持这个程序必需的功能。J2EE Platform Specification 要求J2EE应用服务器让数据源实施(DataSource implementation) 成为可能(那就是，让数据源实施作为JDBC连接的连接池)。Tomcat 5提供完全一样的支持，这样你在Tomcat上开发的基于数据库的(database-based)程序，要使用这个服务，可以在任何J2EE服务器上运行而不需任何更改。

关于JDBC的信息，你应该去参考下列链连：

  • http://java.sun.com/products/jdbc/ - 关于Java数据库连接信息的主 页。
  • http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html - The JDBC 2.1应用编程界面规范。
  • http://java.sun.com/products/jdbc/jdbc20.stdext.pdf - JDBC 2.0 标准扩展应用编程界面 (包括 javax.sql.DataSource API). 这个软件包就是现在的"JDBC Optional Package"。
  • http://java.sun.com/j2ee/download.html - J2EE 操作平台规范(涵盖所有J2EE操作平台必须提供给应用程序的JDBC设施).

注意——Tomcat里支持的默认数据源是基于Jakarta Commons分项目的DBCP连接池的。然而，也有可能通过使用其他实施javax.sql.DataSource的连接池来编写你自己的资源工厂，描述如下：

安装你的JDBC驱动

要使用JDBC Data Sources JNDI 资源工厂，你必须让适当的JDBC驱动既能被Tomcat内部的类使用，又能被你的网络程序使用。最容易的办法是在$CATALINA_HOME/common/lib目录里边安装驱动的JAR文件，这样就让这个驱动既能被资源工厂使用，又能被你的程序使用。

声明你的资源要求

下一步，修改网络程序部署描述符(/WEB-INF/web.xml)来声明JNDI名称。根据习惯性，所有这样的名称都必须围绕着jdbc subcontext 而派生(与标准的java:comp/env naming context 相关，这个naming context是所有的资源工厂的根)。 一个典型的web.xml看起来象这样：

&lt;resource-ref&gt;
&lt;description&gt;
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the server.xml file.
&lt;/description&gt;
&lt;res-ref-name&gt;
jdbc/EmployeeDB
&lt;/res-ref-name&gt;
&lt;res-type&gt;
javax.sql.DataSource
&lt;/res-type&gt;
&lt;res-auth&gt;
Container
&lt;/res-auth&gt;
&lt;/resource-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

一个典型的使用这个资源索引的例子看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

注意，这个程序使用的是与网络程序部署描述符里声明的资源索引相同的名字。这是与在$CATALINA_HOME/conf/server.xml 里配置的资源工厂相映射的，描述如下：

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到网络应用程序的/META-INF/context.xml 文件中。

<Context ...>
  ...
  <Resource name="jdbc/EmployeeDB" auth="Container"
            type="javax.sql.DataSource" username="dbusername" password="dbpassword"
            driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database"
            maxActive="8" maxIdle="4"/>
  ...
</Context>

注意，这个资源的名字(这里是jdbc/EmployeeDB )必须与网络程序部署描述符里指定的值相映射。

这个例子假设你使用HypersonicSQL数据库JDBC驱动。客户化(自己指定)driverClassName 和 driverName这两个参数，让它们与你实际使用的JDBC驱动和连接URL相映射。

Tomcat标准数据资源工厂(org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory)的配置属性如下：

  • driverClassName - 被使用的JDBC驱动的完全合格的Java类名。
  • maxActive - 可以同时从这个pool被分配的最大active实例数目。
  • maxIdle - 可以同时在这个pool闲滞的最大连接数目。
  • maxWait - 这个pool在抛出异常之前可以等待连接返回的最长milliseconds 。
  • password - 将要传递给JDBC驱动的数据库密码。
  • url - 将要传递给JDBC驱动的连接URL(因为向后兼容性，属性的driverName也被认可)。
  • user - 将要传递给JDBC驱动的数据库用户名。
  • validationQuery - 在连接被返回到程序之前，可以被这个pool用来验证连接用的SQL query 。 如被指定，这个query必须是一个SQL SELECT 指令，它至少有一行的返回说明。

更多详细信息，请参看commons-dbcp文档资料。

Adding Custom Resource Factories

如果任何标准资源工厂都不能满足你的要求，你可以编写你自己的资源工厂，并把它整合到Tomcat 5里面，再在conf/server.xml configuration文件里配置怎样使用它。在下面的例子里，你将要产生一个资源工厂，这个工厂仅仅知道怎样产生上面所描述的Generic JavaBean Resources例子里的com.mycompany.MyBean beans 。

编写一个资源工厂类

你必须编写一个实施JNDI服务供给者 javax.naming.spi.ObjectFactory 界面的类。每次你的程序在这个工厂绑定的context entry上调用lookup() ，这个getObjectInstance()方法就会被叫到，有以下这些参数：

  • Object obj - 包含地址或索引信息的对象(很可能是空值)，它可用于制造一个对象(object)。对Tomcat来说，这总是一个javax.naming.Reference类型的对象，它包括这个工厂类的类名，以及用来产生返回对象的配置属性(来自conf/server.xml)。
  • Name name - 这个工厂绑定的与nameCtx有关联的名字,如果没有名字被指定,它就是空值。
  • Context nameCtx - 名称参数相对于这个context被指定，如果名称是相对于默认的初始context，它就是空值。
  • Hashtable environment - 用来产生这个对象的环境(很可能是空值)。这通常在Tomcat对象工厂被忽略。

要制造一个知道怎样产生MyBean实例的资源工厂，你可能会产生一个象这样的类：

package com.mycompany;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {

  public Object getObjectInstance(Object obj,
      Name name, Context nameCtx, Hashtable environment)
      throws NamingException {

      // Acquire an instance of our specified bean class
      MyBean bean = new MyBean();

      // Customize the bean properties from our attributes
      Reference ref = (Reference) obj;
      Enumeration addrs = ref.getAll();
      while (addrs.hasMoreElements()) {
          RefAddr addr = (RefAddr) addrs.nextElement();
          String name = addr.getType();
          String value = (String) addr.getContent();
          if (name.equals("foo")) {
              bean.setFoo(value);
          } else if (name.equals("bar")) {
              try {
                  bean.setBar(Integer.parseInt(value));
              } catch (NumberFormatException e) {
                  throw new NamingException("Invalid 'bar' value " + value);
              }
          }
      }

      // Return the customized instance
      return (bean);

  }

}

在这个例子里，我们无条件地产生一个新的com.mycompany.MyBean类的实例，并且在&lt;ResourceParams&gt;元素所包含的参数基础上populating它的属性，而这个&lt;ResourceParams&gt;元素是配置这个工厂用的(参见下面)。你应该注意，必须跳过所有名字叫工厂的参数——这个参数是用来指定工厂类自身的名字(在这里的情况下是com.mycompany.MyBeanFactory)，而不是用来指定要被配置的bean的属性。

关于ObjectFactory的更多信息，请参看JNDI 1.2 Service Provider Interface (SPI) Specification 。

你需要对照一个包括所有$CATALINA_HOME/common/lib 和$CATALINA_HOME/server/lib目录里的JAR文件的class path来编译这个类。当你完成以后，把这个工厂类(以及相关的bean类)以未包装形式放在$CATALINA_HOME/common/classes下面，或者放在$CATALINA_HOME/common/lib里的一个JAR文件里。通过这种方式，所需要的类文件既可以被Catalina内部资源又可以被你的网络程序使用。

声明你的资源要求

下一步，修改你的网络程序部署描述符( /WEB-INF/web.xml ) 来声明JNDI名字，你将要求产生这个bean的新的实例在其名下。最简单的方法是象这样来使用<resource-env-ref>元素：

&lt;resource-env-ref&gt;
&lt;description&gt;
Object factory for MyBean instances.
&lt;/description&gt;
&lt;resource-env-ref-name&gt;
bean/MyBeanFactory
&lt;/resource-env-ref-name&gt;
&lt;resource-env-ref-type&gt;
com.mycompany.MyBean
&lt;/resource-env-ref-type&gt;
&lt;/resource-env-ref&gt;

警告——一定要尊重元素的排列顺序，这是网络程序部署描述符DTD所要求的。详细信息请参看Servlet 规范 。

编写使用这个资源的程序

典型的使用这个资源环境索引的编码看起来象这样：

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
bean.getBar());

配置Tomcat的资源工厂

要配置Tomcat的资源工厂，把象下面这样的一个元素添加到$CATALINA_HOME/conf/server.xml文件中，并把它套嵌在这个网络应用程序的Context元素里。

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="com.mycompany.MyBeanFactory"
            bar="23"/>
  ...
</Context>

注意资源名称(这里是bean/MyBeanFactory)必须与网络程序部署描述符里指定的值相对映。我们也还要初始化bar property的值，这会在返回新的bean之前引起调用setBar(23)。因为我们没有初始化foo property(尽管我们也可以这样做)，bean会包含它的构造器设置的任何默认值。

你会注意到，从程序开发员的角度来看，对资源环境索引的声明，和用于请求新实例的编程，与Generic JavaBean Resources例子里使用的方法完全一样。这里举例说明了使用JNDI资源来封装功能(functionality)的一个优点——那就是，只要你保持相兼容的APIs，你可以改变下面的实施(underlying implementation)而不需要使用资源来修改程序。


Apache Tomcat 5.5 Servlet/JSP 容器 - Logging in Tomcat

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Logging in Tomcat
Introduction

Tomcat 5.5 uses Commons Logging throughout its internal code allowing the developer to choose a logging configuration that suits their needs, e.g java.util.logging or Log4J. Commons Logging provides Tomcat the ability to log hierarchially across various log levels without needing to rely on a particular logging implementation.

An important consequence for Tomcat 5.5 is that the <Logger> element found in previous versions to create a localhost_log is no longer a valid nested element of <Context>. Instead, the default Tomcat configuration will use java.util.logging. If the developer wishes to collect detailed internal Tomcat logging (i.e what is happening within the Tomcat engine), then they should configure a logging system such as java.util.logging or log4j as detailed next.

log4j

Tomcat 5.5 has done away with localhost_log which you may be familiar with as the runtime exception/stack trace log. These types of error are usually thrown by uncaught exceptions, but are still valuable to the developer. They can now be found in the stdout log.

If you need to setup cross-context detailed logging from within Tomcat's code, then you can use a simple log4j configuration. Note that this logging van be very verbose depending on the log level you chose to use. Note also that a log4j logging configuration is not going to produce stack trace type logging: those stack traces are output to stdout as discussed above.

Follow the following steps to setup a file named tomcat.log that has internal Tomcat logging output to it:

  1. Create a file called log4j.properties with the following content and save it into common/classes.
                log4j.rootLogger=debug, R
            log4j.appender.R=org.apache.log4j.RollingFileAppender
            log4j.appender.R.File=${catalina.home}/logs/tomcat.log
            log4j.appender.R.MaxFileSize=10MB
            log4j.appender.R.MaxBackupIndex=10
            log4j.appender.R.layout=org.apache.log4j.PatternLayout
            log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
            log4j.logger.org.apache.catalina=DEBUG, R
  2. Download Log4J (v1.2 or later) and place the log4j jar in $CATALINA_HOME/common/lib.
  3. Download Commons Logging and place the commons-logging.jar (not commons-logging-api.jar) in $CATALINA_HOME/common/lib with the log4j jar.
  4. Start Tomcat

This log4j configuration sets up a file called tomcat.log in your Tomcat logs folder with a maximum file size of 10MB and up to 10 backups. DEBUG level is specified which will result in the most verbose output from Tomcat.

You can (and should) be more picky about which packages to include in the logging. Tomcat 5.5 uses defines loggers by Engine and Host names. For example, for a default Catalina localhost log, add this to the end of the log4j.properties above. Note that there are known issues with using this naming convention (with square brackets) in log4j XML based configuration files, so we recommend you use a properties file as described until a future version of log4j allows this convention.

  • log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=DEBUG, R
  • log4j.logger.org.apache.catalina.core=DEBUG, R
  • log4j.logger.org.apache.catalina.session=DEBUG, R
Be warned a level of DEBUG will produce megabytes of logging and slow startup of Tomcat. This level should be used sparingly when debugging of internal Tomcat operations is required.

Your web applications should certainly use their own log4j configuration. This is valid with the above configuration. You would place a similar log4j.properties file in your web application's WEB-INF/classes folder, and log4j1.2.8.jar into WEB-INF/lib. Then specify your package level logging. This is a basic setup of log4j which does *not* require Commons-Logging, and you should consult the log4j documentation for more options. This page is intended only as a bootstrapping guide.

java.util.logging

In order to configure JDK logging you should have JDK 1.4+. Tomcat 5.5 is intended for JDK 5.0 or later, but can be run on JDK 1.4 using a compatibility package.

The default implemenatation of java.util.logging provided in the JDK is too limited to be useful. A limitation of JDK Logging appears to be the inability to have per-web application logging, as the configuration is per-VM. As a result, Tomcat will, in the default configuration, replace the default LogManager implementation with a container friendly implementation called JULI, which addresses these shortcomings. It supports the same configuration mechanisms as the standard JDK java.util.logging, using either a programmatic approach, or properties files. The main difference is that per-classloader properties files can be set (which enables easy redeployment friendly webapp configuration), and the properties files support slightly extended constructs which allows more freedom for defining handlers and assigning them to loggers.

JULI is enabled by default in Tomcat 5.5, and supports per classloader configuration, in addition to the regular global java.util.logging configuration. This means that logging can be configured at the following layers:

  • In the JDK's logging.properties file. Check your JAVA_HOME environment setting to see which JDK Tomcat is using (or maybe JRE 5.0 as Tomcat can now run on a JRE from version 5.5). The file will be in $JAVA_HOME/jre/lib. Alternately, it can also use a global configuration file located elsewhere by using the system property java.util.logging.config.file, or programmatic configuration using java.util.logging.config.class.
  • In each classloader using a logging.properties file. This means that it is possible to have a configuration for the Tomcat core, as well as separate configurations for each webapps which will have the same lifecycle as the webapps.

The default logging.properties specifies a ConsoleHandler for routing logging to stdout and also a FileHandler. A handler's log level threshold can be set using SEVERE, CONFIG, INFO, WARN, FINE, FINEST or ALL. The logging.properties shipped with JDK is set to INFO. You can also target specific packages to collect logging from and specify a level. Here is how you would set debugging from Tomcat. You would need to ensure the ConsoleHandler's level is also set to collect this threshold, so FINEST or ALL should be set. Please refer to Sun's java.util.logging documentation for the complete details.

org.apache.catalina.level=FINEST

The configuration used by JULI is extremely similar, but uses a few extensions to allow better flexibility in assigning loggers. The main differences are:

  • A prefix may be added to handler names, so that multiple handlers of a single class may be instantiated. A prefix is a String which starts with a digit, and ends with '.'. For example, 22foobar. is a valid prefix.
  • As in Java 5.0, loggers can define a list of handlers using the loggerName.handlers property.
  • By default, loggers will not delegate to their parent if they have associated handlers. This may be changed per logger using the loggerName.useParentHandlers property, which accepts a boolean value.
  • The root logger can define its set of handlers using a .handlers property.
  • System property replacement for property values which start with ${sytstemPropertyName}.

Example logging.properties file to be placed in common/classes:

handlers = 1catalina.org.apache.juli.FileHandler, 2localhost.org.apache.juli.FileHandler, \
           3manager.org.apache.juli.FileHandler, 4admin.org.apache.juli.FileHandler, \
           java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.FileHandler.level = FINE
1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.FileHandler.prefix = catalina.

2localhost.org.apache.juli.FileHandler.level = FINE
2localhost.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.FileHandler.prefix = localhost.

3manager.org.apache.juli.FileHandler.level = FINE
3manager.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.FileHandler.prefix = manager.

4admin.org.apache.juli.FileHandler.level = FINE
4admin.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
4admin.org.apache.juli.FileHandler.prefix = admin.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
   2localhost.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = \
   3manager.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].handlers = \
   4admin.org.apache.juli.FileHandler

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Example logging.properties for the servlet-examples web application to be placed in WEB-INF/classes inside the web application:

handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = servlet-examples.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

Handler Properties

Tomcat's JULI implementation is not intended to be a fully-featured logging libary, only a simple bridge to those libraries. However, JULI does provide several properties for configuring the its handlers. These are listed below.

FileHandler
Attribute Description
directory

The directory where the log file will be written. The Tomcat server account should have write permissions to this directory. The default value of this property is logs.

prefix

The log file name prefix. This is the portion of the log file name before the date. The default value of this property is juli..

suffix

The log file name suffix. This is the portion of the log file name after the date. The default value of this property is .log.

level

The threshold level for this handler. It must be one of the levels in the java.util.logging.Level class. The default value of this property is ALL. Messages whose level is below the specified level will not be written to the file.

filter

The fully-qualified class name of a class that implements the java.util.logging.Filter interface. JULI will load this class and associate it with this handler to filter its messages. By default, there is no Filter associated with the handler.

formatter

The fully-qualified class name of a class that implements the java.util.logging.Formatter interface. JULI will load this class and associate it with this handler to format its messages. By default, there is no Formatter associated with the handler.


Apache Tomcat 5.5 Servlet/JSP 容器 - Manager App HOW-TO

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Manager App HOW-TO
Table of Contents

简介
配置管理员程序存取( Configuring Manager Application Access)
被支持的管理员命令(Supported Manager Commands)

远程部署新的应用程序(Deploy A New Application Remotely)
从局部路径部署新的应用程序(Deploy A New Application from a Local Path)
列出当前被部署的应用程序（ List Currently Deployed Applications）
重新装载现有的应用程序(Reload An Existing Application)
列出OS和Java虚拟器(JVM)的属性(List OS and JVM Properties)
列出可用的全球性JNDI资源( List Available Global JNDI Resources)
列出可用的安全性功能(List Available Security Roles)
Session统计(Session Statistics)
启动一个现有的应用程序(Start an Existing Application)
停止运行一个现有的应用程序(Stop an Existing Application)
反部署一个现有的应用程序( Undeploy an Existing Application)
使用Ant执行管理员命令( Executing Manager Commands With Ant)
使用JMX代理Servlet( Using the JMX Proxy Servlet)
什么是JMX代理Servlet?(What is JMX Proxy Servlet?)
查询命令(Query command)
设置命令(Set command)

Introduction

在许多生产环境(production environments)里，这种能力很重要，那就是在不需要关闭和重新启动整个容器的情况下能够部署一个新的web程序，或者反部署一个现有的程序。另外, 你能要求一个现有应用程序再装载它自己，既使你还没有在Tomcat 5服务器配置文件里声明它是可以被重新装载的(reloadable)。

为了支持这种能力，Tomcat 5包含了一个web程序(默认安装在context path /manager上),它支持以下这些功能:

  • 从上载的(uploaded)WAR文件内，把新的web程序部署到指定的context path上去。
  • Deploy a new web application, on a specified context path, from the server file system.
  • 列出当前部署的web程序，以及这些web程序的活跃着的sessions。
  • 重新装载现有的web程序，以反映出/WEB-INF/classes 或 /WEB-INF/lib 里内容的更改。
  • 列出OS和Java虚拟器(JVM)属性值(property values)。
  • 列出可使用的全球性JNDI资源, 供给正在准备&lt;ResourceLink&gt；套嵌在&lt;Context&gt 的元素；部署描述的开发工具使用。
  • 列出用户数据库里定义的可用安全性功能。
  • 启动运行一个被停止了的程序(让它可再被使用)。
  • 停止一个现有的程序(这样它就变成不可被使用)，但是不undeploy它。
  • Undeploy a deployed web application and delete its document base directory (unless it was deployed from file system).

有两种方式来配置Manager网络应用程序Context：

  • 把manager.xml context配置文件安装在$CATALINA_HOME/conf/[enginename]/[hostname]文件夹里。
  • 在Tomcat server.xml 配置文件的主机配置(Host configuration)中来配置the Manager Context。下面是一个例子：
    &lt;Context path="/manager" debug="0" privileged="true"
docBase="/usr/local/kinetic/tomcat5/server/webapps/manager"&gt;
&lt;/Context&gt;

如果你把Tomcat配置成可支持多个网站，你就需要为每一个网站单独配置一个管理员(Manager)。

有三种方法来使用管理员(manager)网络应用程序：

  • 作为使用在浏览器上用户接口(user interface)的程序。下面是一个关于URL的例子，这里你可以用你的网站的名字来取代局部主机(localhost): http://localhost/manager/html/。
  • 作为一个使用HTTP(超文本传输协议)请求的小版本程序，它只适合系统管理员用于scripts设置。命令作为这个request URI的一部分给出，并且反应(responses)是那种容易被解析(parsed)和处理的简单文本的形式。更多信息参看被支持的管理员命令( Supported Manager Commands)。
  • 作为Ant(1.4以及其后版本)建造工具的一套简易的task定义。更多信息请参看Executing Manager Commands With ant 。

Tomcat 5的未来版本将包括下面这些形式的管理功能:

  • 作为网络服务，这样Tomcat管理就很容易地整合到远程/或者非Java的管理环境中去。
  • 作为一种具有较好user interface的网络程序(建立在网络服务过程的顶层)，可方便Tomcat通过web浏览器进行管理。

Configuring Manager Application Access

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

如果Tomcat里的默认设置允许互联网上的任何人在你的服务器上执行管理员程序(the Manager application)，那就相当不安全了。因此，管理员程序要求每一个使用它的人通过使用带有管理员(manager)角色的用户名称和密码证实它们自己的身份。更进一步，在默认的用户文件中($CATALINA_HOME/conf/tomcat-users.xml)没有用户名称被指派这个角色。因此，以默认的形式是完全不可能访问管理员程序的。

为了能进入管理员程序进行存取，你必须产生一个新的用户名称/密码组合，并把它们与管理员(manager)角色联系在一起，或者把管理员(manager)角色添加给现有的用户名称/密码组合。在什么确切的地方做上面这些工作依赖于你使用了哪个Realm implementation ：

  • MemoryRealm ——别如果你还没有客户化$CATALINA_HOME/conf/server.xml，就选择另外一个文件，Tomcat 5默认选用存放在$CATALINA_HOME/conf/tomcat-users.xml里的一个XML-格式的文件，它可以由任何文字编辑器(text editor)来编辑。这个文件为每一个用户包括了一个XML &lt;user&gt;，它看上去可能象这样：
    &lt;user name="craigmcc" password="secret" roles="standard,manager" /&gt;
    它定义了用于个人登录使用的用户名称和密码，以及他(她)们相关联的角色名称。你可以给现有的一个或多个用户添加“管理员(manager)”角色，或者产生具有管理员角色的新用户。
  • JDBCRealm —— 关于用户以及其角色的信息被存放在数据库里，通过JDBC(Java数据库连接)进行存取。按照你使用的工作环境里的标准手续来给一个或多个现有用户添加“管理员(manager)"职责，或者产生一个或多个具有管理员角色的新用户。
  • JNDIRealm —— 关于用户以及其角色的信息被存放在目录服务器上，通过LDAP进行存取。按照你使用的工作环境里的标准手续来给一个或多个现有用户添加“管理员(manager)”职责，或者产生一个或多个具有管理员角色的新用户。

当你第一次试图发布一个下个章节将要描述的Manager命令时，你会被要求用BASIC认证来登入。不管你输入什么用户名称和密码，只要它们是能被用户数据库识别的具有管理员(manager)角色的用户就行。

除了密码制约之外，在远程IP地址或主机上增加RemoteAddrValve或者RemoteHostValve也可以对管理员网络程序进行限制。下面的例子是通过IP地址对进出局部主机(localhost)进行限制:

&lt;Context path="/manager" debug="0" privileged="true"
docBase="/usr/local/kinetic/tomcat5/server/webapps/manager"&gt;
&lt;Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127.0.0.1"/&gt;
&lt;/Context&gt;

Supported Manager Commands

管理员程序的所有命令都是由象这样的单个request URI指定(它的格式如下):

http://{host}:{port}/manager/{command}?{parameters}

这里{host}和{port}代表主机名称和Tomcat运行的端口(port)数目，{command}代表你想要执行的管理员命令，{parameters}代表那个命令特有的查询参数。在下面的说明里，把主机和端口适当地客户化以便进行安装。

多数命令接受以下一个或多个查询参量:

  • 路径(path)——你将要处理的网络应用程序的上下文路径(包括前面的“/”)。要选择the ROOT网络应用程序，指定"/"。注意——不可能仅仅在管理员程序自身就能执行管理命令。
  • 网络应用程序档案(war)—— 网络应用程序档案文件的统一资源定位器(URL)，包含网络程序的目录的路径名称，或者是一个Context configuration ".xml" 文件。你可以以下面任何格式使用URLs:
    • file:/absolute/path/to/a/directory ——这是通向包含未包装版的网络程序目录的绝对路径。这个目录可以附加在你指定的context path上，而不需要任何改变。
    • file:/absolute/path/to/a/webapp.war —— 这是通向网络应用档案(WAR)文件的绝对路径。这仅仅对/deploy 命令有效，也是这个命令唯一被接受的格式。
    • jar:file:/absolute/path/to/a/warfile.war!/ —— 这是通向局部网络应用档案(WAR)文件的URL。你可以使用任何对JarURLConnection class有效的语法来代指一整个JAR文件。
    • file:/absolute/path/to/a/context.xml —— 这是通向网络应用上下文配置 ".xml"文件的绝对路径，这个".xml"文件包含有上下文配置元素。
    • directory (目录)—— 主机的应用基础目录中各种web程序内容的子目录名称。
    • webapp.war —— 这是网络程序war文件的名称，它被放置在主机的应用基础目录上。

每个命令都会产生一个text/plain 形式的反应(response)(例如，简单的ASCII而没有HTML修饰)，使它能容易地被人或机器阅读。反应(response)的第一行通常以OK(可以)或者FAIL(失败)开始，表明了这个请求命令被成功执行与否。如果出现失败，第一行的剩余部分会描述你所遇到的问题。下面将描述一些命令及其额外的信息。

Internationalization Note(国际化注意事项):管理员程序从资源束(resource bundles)里查看消息字串(message strings)，所以有可能这些字串已被翻译过以适用于你的工作平台。下面的例子显示的是英文版的消息(messages)。

警告：以前使用的命令 /install 和 /remove 不再被使用了。它们现在等同于/deploy 和 /undeploy命令，在以后的发行版中可能会被删除掉。

Deploy A New Application Remotely
http://localhost:8080/manager/deploy?path=/foo

上装(Upload)在HTTP PUT request里特指的WAR文件，然后把它安装在相应的虚拟主机(virtual host)的appBase目录上，在路径请求参数特指的context path 上启动运行。如果没有指定路径，那么目录名称或者不带有.war 扩展名的WAR文件名称就被当作路径。这个应用程序在以后可以通过使用/undeploy 被取消部署(相关的程序目录也会被删除)。

这个.WAR 文件可以通过在/META-INF/context.xml里包含一个上下文配置XML 文件来包括 Tomcat特指的部署配置。

URL参数包括：

  • 更新(update)：当被设置为正确(true)时，已有的更新参数会被首先取消部署。默认值是被设为错误(false)。
  • 标志(tag)：指定一个标志名称，这样允许把版本数目与被部署的网络程序相关联。以后可以只用标志(tag)就可以重新部署这个版本的程序。

注意 —— 这个命令在逻辑上和/undeploy命令相反。

如果安装和启动成功，你会收到象下面这种回应：

OK - Deployed application at context path /foo

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 应用程序已经存在于path /foo

    所有当前运行的网络程序的context paths 必须是独特（彼此不同）的。因此，你必须取消部署现有的使用这个context path的网络程序，或者为新程序选择一个不同的context path 。update参数必须指定为URL上的一个参数，为避免错误，把参数值设为true 。这样，在部署新程序前会对现有程序执行取消部署。

  • 遇到异常

    当试图启动新程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)，不过通常的解释多为在语法分析(parsing)/WEB-INF/web.xml 文件时遇到问题，或者是在初始化程序事件(event)监听器(listeners)或过滤器(filters)遇到了缺失的类(missing classes)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • 没有指定上下文路径
    路径参数是必需的。
Deploy A New Application from a Local Path

安装和启动一个新的网络程序，把它和特定的上下文路径相连(这个上下文路径不能被其他网络程序使用)。这个命令(指deploy)与/undeploy 命令在逻辑意义上相反。

有许多种不同的办法来使用deploy命令:

部署一个以前被部署过的网络程序版本

这可以用来部署一个以前版本的网络程序，这个程序曾被使用标志(tag)属性部署过。注意，管理员程序的工作目录必须包含以前部署过的WARs；删除它会使得这里的部署失败。

http://localhost:8080/manager/deploy?path=/footoo&amp;tag=footag

通过URL部署一个目录或者WAR

部署Tomcat服务器上的网络程序目录或者".war"文件。如果没有指定路径(path)，那么目录名称或者不带有".war"扩展名的WAR文件名称就被当作路径。网络应用程序档案(war)参数为每个目录或WAR文件指定了URL(包括文件: scheme)。关于URL指向WAR文件的语法在Javadocs页面java.net.JarURLConnection class里有描述。只能使用那些指向全部(entire)WAR文件的URL。

在下面的这个例子里，位于Tomcat服务器/path/to/foo目录里的网络程序被部署为一个名叫/footoo 的网络程序context。

http://localhost:8080/manager/deploy?path=/footoo&amp;war=file:/path/to/foo

在下面的这个例子里，位于Tomcat服务器上的".war"文件/path/to/bar.war被部署为一个名叫/bar 的网络程序context。注意，这里没有path参数，所以在默认的情况下，context path指向不带有".war"扩展名的网络应用程序档案文件。

http://localhost:8080/manager/deploy?war=jar:file:/path/to/bar.war!/

在主机的appBase部署一个目录或War文件

在主机的appBase目录里部署一个网络程序目录或".war"文件。如果没有指定路径(path)，那么目录名或者不带有".war"扩展符的WAR文件名称就被当作路径。

在下面的这个例子里，位于Tomcat服务器主机appBase目录下的子目录foo里面的网络程序被部署为叫作/foo 的网络程序context。注意，这里没有path参数，所以在默认的情况下，context path指向网络程序目录名。

http://localhost:8080/manager/deploy?war=foo

在下面的这个例子里，位于Tomcat服务器主机appBase目录里的".war"文件bar.war被部署为名叫/bartoo 的网络程序context。

http://localhost:8080/manager/deploy?path=/bartoo&amp;war=bar.war

使用上下文语境配置".xml"文件进行部署

如果主机(Host) deployXML旗标被设置为正确(true)，你可以用上下文语境配置".xml"文件，或者".war"文件，或者程序目录来部署你的网络程序。当使用上下文语境配置".xml"文件来部署网络程序时，不需要使用context path。

一个上下文语境配置".xml"文件可包括有效的网络程序上下文XML文件，就象在Tomcat server.xml 配置文件里被配置过一样。下面是个示例：

&lt;Context path="/foobar" docBase="/path/to/application/foobar"
debug="0"&gt;

&lt;!-- Link to the user database we will get roles from --&gt;
&lt;ResourceLink name="users" global="UserDatabase"
type="org.apache.catalina.UserDatabase"/&gt;

&lt;/Context&gt;

当可任选的网络应用程序档案(war)参数被设置指向一个web程序的".war"文件或目录的URL时,它会取代任何在上下文配置".xml"文件里配置的docBase 。

这里是使用上下文语境配置".xml"文件部署一个应用程序的例子。

http://localhost:8080/manager/deploy?config=file:/path/context.xml

这个例子是使用上下文语境配置".xml"文件和一个位于服务器上的".war"文件来部署一个应用程序。

http://localhost:8080/manager/deploy?config=file:/path/context.xml&amp;war=jar:file:/path/bar.war!/

部署注意事项

如果主机(Host)配置为unpackWARs=true ，并且你部署了一个war文件，那么，这个war文件就会被unpacked到主机的appBase目录上。

如果war文件或者目录被安装到主机的appBase目录上，并且主机被配置为autoDeploy=true 或者liveDeploy=true ，那么Context path 必须与目录名或不带有".war"扩展符的war文件名相配。

因为安全原因，当不可靠用户来管理网络程序时，主机的deployXML旗标可以设置为false 。这就使不可靠用户不能够使用配置XML文件来部署web程序，也不能部署位于主机appBase之外的目录或".war"文件。

部署回应

如果安装和启动成功，你会收到象下面这种回应：

OK - Deployed application at context path /foo

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 应用程序已经存在于path /foo

    所有当前运行的网络程序的context paths 必须是独特（彼此不同）的。因此，你必须取消部署现有的使用这个context path的网络程序，或者为新程序选择一个不同的context path 。update参数必须指定为URL上的一个参数，为避免错误，把参数值设为true 。这样，在部署新程序前会对现有程序执行取消部署。

  • 文档base不存在或者是一个不可读取的目录

    由网络应用程序档案(war)参数指定的URL必须识别这个服务器上包含"unpacked"版本的网络程序目录，或者包含这个程序的网络应用程序档案(WAR)的绝对URL。修正这个网络应用程序档案(war)参数指定值。

  • 遇到异常

    当试图启动新程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)，不过通常的解释多为在语法分析(parsing)/WEB-INF/web.xml 文件时遇到问题，或者是在初始化程序事件(event)监听器(listeners)或过滤器(filters)遇到了缺失的类(missing classes)。

  • 指定的程序URL无效

    你为目录或网络程序指定的URL是无效的。这样的URL必须以“file:”开始，为WAR文件提供的URL必须以".war"结束。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • 上下文路径必须与目录名或WAR文件名相配
    如果war文件或者目录被安装到主机的appBase目录上，并且主机被配置为autoDeploy=true 或者liveDeploy=true ，那么Context path 必须与目录名或不带有".war"扩展符的war文件名相配。
  • 只有在主机网络程序目录里的web程序才能被安装
    如果主机的deployXML旗标被设为false，要是试图部署位于主机appBase目录之外的网络程序目录或".war"文件，就会出现错误。
List Currently Deployed Applications
http://localhost:8080/manager/list

列出所有当前被部署过的程序的context paths，当前状态(运行中的或停止的)，以及活动会话(active sessions)数目。在启动Tomcat后马上出现的典型回应可能象这样：

OK - Listed applications for virtual host localhost
/webdav:running:0
/examples:running:0
/manager:running:0
/:running:0
Reload An Existing Application
http://localhost:8080/manager/reload?path=/examples

向一个现有的程序发出信号去把它自己关闭然后再重新装载。当程序的context不能够被重新装载，但你/WEB-INF/classes目录中有更新过的类或属性文件，或者在/WEB-INF/lib目录中添加或更新过jar文件，上面这个办法就很有用。

注意 —— /WEB-INF/web.xml 网络程序配置文件不能在被重新装载时被再次读取。如果你更改了web.xml文件，你必须停止运行，然后再启动网络程序。

如果这个命令成功，你会看到象下面这样的回应：

OK - Reloaded application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图重新启动网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
  • 在path /foo上部署的WAR文件不支持重新装载
    目前，当网络程序从一个WAR文件直接被部署时，程序的重新装载(拾起classes 或 web.xml文件里的更改)就不被支持。重新装载仅仅适用于那些从未包装目录那里部署的程序。如果你在使用WAR文件，要拾起(pick up)那些更改，你应该先undeploy(旧的文件)，然后再deploy这个程序，或者以update的参数来部署这个程序。
List OS and JVM Properties
http://localhost:8080/manager/serverinfo

列出关于Tomcat版本，OS, 和 JVM属性的信息。

如果出现错误，回应(response)将是以FAIL开头的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    在枚举系统属性时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

List Available Global JNDI Resources
http://localhost:8080/manager/resources[?type=xxxxx]

列出可用于上下文配置文件资源链接(resource links)的全球性JNDI资源。如果你指定类型请求参数(type request parameter)，参数值必须是你所感兴趣的资源类型中完全合格的Java class name(例如，你得要指定javax.sql.DataSource 来取得所有可用的JDBC数据源的名称)。如果你没有指定类型请求参数，所有类型的资源将被返回。

依赖于类型请求参数(type request parameter)被指定与否，通常回应的第一行会是这样：

OK - Listed global resources of all types

or

OK - Listed global resources of type xxxxx

然后是每一行对应一个资源。每一行由以冒号(":")为界限的如下区域组成：

  • 全球性资源名称(Global Resource Name) —— 全球性JNDI资源的名称，它将被用在&lt;ResourceLink&gt;元素的全球性属性中。
  • 全球性资源类型(Global Resource Type)—— 全球性JNDI资源的完全合格的Java class 名称。

如果出现错误，回应(response)将是以FAIL开头的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    在枚举全球性JNDI资源时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 全球性JNDI资源不存在

    你在运行的Tomcat服务器没有被配置全球性JNDI资源。

List Available Security Roles
http://localhost:8080/manager/roles

列出在org.apache.catalina.UserDatabase资源里的安全性能名称(以及相应的描述)，这个资源与Manager网络程序里web.xml文件中的用户资源索引相链连。例如，这通常会被那些想要产生 &lt;security-role-ref&gt;元素的部署工具使用，而&lt;security-role-ref&gt;元素是用来映射网络程序里的安全性能名称和容器里实际上被定义的角色名称的。

在默认的情况下，用户资源索引指向全球性UserDatabase资源。如果你选择让每个虚拟器使用不同的用户数据库，你应该修改默认的manager.xml 配置文件里的&lt;ResourceLink&gt; 元素，让它指向这个虚拟器的全球性用户数据库资源。

当这个命令被执行后，回应的第一行是这样的：

OK - Listed security roles

然后是每一行对应一个安全性能。每一行由以冒号(":")为界限的如下区域组成：

  • 安全性能名称(Security Role Name)——用户数据库里Tomcat所知道的安全性能名称。
  • 描述(Description)——关于这个安全性能的描述(对于产生选定功能的用户界面有用)

如果出现错误，回应(response)将是以FAIL开头的一段错误消息。产生错误的可能原因包括：

  • Cannot resolve user database reference —— 一个JNDI错误，阻止了成功查询org.apache.catalina.UserDatabase 资源。关于这类错误，请查看Tomcat log 文件的stack trace 。
  • No user database is available —— 你还没有为用户资源配置一个可以指向适当的用户数据库实例(instance)的资源索引。检查一下你的manager.xml文件，确保你为这个资源产生了一个适合的&lt;ResourceLink&gt;或&lt;ResourceParams&gt;元素。
Session Statistics
http://localhost:8080/manager/sessions?path=/examples

显示一个网络程序的默认session timeout，以及在实际timeout时间十分钟左右范围里的活动sessions数目。例如，在重新启动Tomcat和执行/examples程序里的一个JSP样本以后，你可能会得到象下面这样的东西：

OK - Session information for application at context path /examples
Default maximum session inactive interval 30 minutes
30 - &lt;40 minutes:1 sessions
Start an Existing Application
http://localhost:8080/manager/start?path=/examples

向一个被停止运行的程序发出重新启动的信号，使它可以再被使用。停止和启动(这两个命令)是有用处的，例如，在你的程序所必需的数据库临时unavailable时。通常停止运行依赖于这个数据库的程序，比起让用户不断地遇到数据库异常要好一些。

如果这个命令成功，你会看到象下面这样的回应：

OK - Started application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图启动网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
Stop an Existing Application
http://localhost:8080/manager/stop?path=/examples

向一个现有的程序发出信号，使它自己变成不能被使用，但让它还是被部署着。当一个程序被停止运行，任何一个进来的请求都会看到一个HTTP错误404，而且在执行list applications命令时，这个程序会显示为"stopped"。

如果这个命令成功，你会看到象下面这样的回应：

OK - Stopped application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图停止运行网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
Undeploy an Existing Application
http://localhost:8080/manager/undeploy?path=/examples

警告：这个命令将会删除存在于虚拟主机appBase 目录下的(典型名称叫做"webapps")任何web程序内容。也会删除源代码.WAR文件， 如果存在的话。这个appBase目录的内容或者是从未包装的程序部署过来的， 或者是.WAR 扩展而来的，它还包括$CATALINA_HOME/conf/[enginename]/[hostname]/ 目录里的XML Context定义。 如果你仅仅只想让程序停止工作，你就使用/stop命令。

向一个现有的程序发出关闭信息，把它自己从Tomcat里删除(这就使得这个context path以后可以被再使用)。另外，存在于虚拟主机appBase目录(典型名称 "webapps")上的文件根目录(document root directory)也被删除掉了。这个命令在逻辑上和/deploy 命令相反。

如果这个命令成功，你会看到象下面这样的回应：

OK - Undeployed application at context path /examples

否则,回应(response)将是以FAIL为首的一段错误消息。产生错误的可能原因包括：

  • 遇到异常

    当试图取消部署网络程序时，遇到了异常。详细问题去查看Tomcat 5日志(logs)。

  • 指定的上下文路径是无效的

    Context path必须以一个slash符号开始。使用"/"代指ROOT网络应用程序。

  • path /foo 上没有存在context

    在你指定的context path上没有被部署过的程序。

  • 没有指定上下文路径
    路径参数是必需的。
Executing Manager Commands With Ant

除了象上面所讲的可以通过HTTP请求来执行Manager命令，Tomcat 5还包括了一套使用方便的Ant(1.4及其后版本)构造工具的任务定义。为了能够使用这些命令，你必须进行下面的操作设置：

  • 从http://ant.apache.org下载Ant的binary distribution 。你必须使用1.4或其后版本。
  • 把Ant distribution 安装在一个方便的目录(在这个说明的其余部分被称作ANT_HOME)。
  • 把文件server/lib/catalina-ant.jar从Tomcat 5安装复制到Ant的library目录($ANT_HOME/lib)。
  • 把$ANT_HOME/bin目录添加到PATH环境变量中。
  • 在Tomcat具有管理员(manager)角色的用户数据库里至少配置一个用户名/密码组合。

要在Ant里使用客户化的任务，你必须事先用&lt;taskdef&gt;元素对它们进行声明。因此，你的build.xml文件看起来会象这样：

&lt;project name="My Application" default="compile" basedir="."&gt;

&lt;!-- Configure the directory into which the web application is built --&gt;
&lt;property name="build" value="${basedir}/build"/&gt;

&lt;!-- Configure the context path for this application --&gt;
&lt;property name="path" value="/myapp"/&gt;

&lt;!-- Configure properties to access the Manager application --&gt;
&lt;property name="url" value="http://localhost:8080/manager"/&gt;
&lt;property name="username" value="myusername"/&gt;
&lt;property name="password" value="mypassword"/&gt;

&lt;!-- Configure the custom Ant tasks for the Manager application --&gt;
&lt;taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"/&gt;
&lt;taskdef name="list" classname="org.apache.catalina.ant.ListTask"/&gt;
&lt;taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"/&gt;
&lt;taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask"/&gt;
&lt;taskdef name="roles" classname="org.apache.catalina.ant.RolesTask"/&gt;
&lt;taskdef name="start" classname="org.apache.catalina.ant.StartTask"/&gt;
&lt;taskdef name="stop" classname="org.apache.catalina.ant.StopTask"/&gt;
&lt;taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/&gt;

&lt;!-- Executable Targets --&gt;
&lt;target name="compile" description="Compile web application"&gt;
&lt;!-- ... construct web application in ${build} subdirectory, and
generated a ${path}.war ... --&gt;
&lt;/target&gt;

&lt;target name="deploy" description="Install web application"
depends="compile"&gt;
&lt;deploy url="${url}" username="${username}" password="${password}"
path="${path}" war="${build}${path}.war"/&gt;
&lt;/target&gt;

&lt;target name="reload" description="Reload web application"
depends="compile"&gt;
&lt;reload url="${url}" username="${username}" password="${password}"
path="${path}"/&gt;
&lt;/target&gt;

&lt;target name="undeploy" description="Remove web application"&gt;
&lt;undeploy url="${url}" username="${username}" password="${password}"
path="${path}"/&gt;
&lt;/target&gt;

&lt;/project&gt;

现在，你可以执行象ant deploy这样的命令向运行的Tomcat实例部署应用程序，或者用ant reload来告诉Tomcat对程序进行重新装载。请注意，在build.xml文件中大多数有趣的参数值都被定义为可被替换的属性，这样一来你可以从命令行来替代(override)它们的参数值。例如，你可能认为把真实管理员密码写在build.xml的源代码里会对安全性能造成危险。为避免这样，你可以忽略密码这个属性，然后从命令行来指定它：

ant -Dpassword=secret deploy
Tasks output capture

使用Ant 1.6.2或其后版本，Catalina tasks在属性文件或外部文件里提供捕捉它们的输出信息的选项。 它们直接支持下列<redirector>类型attributes的下属属性：

属性 | 描述 | 是否必要
output | 向其进行输出的文件名。如果error stream没有被重新指向一个文件或属性，那么它就出现在这里。 | No
error | 标准的错误信息输出命令应该指向这个文件。 | No
logError | This attribute is used when you wish to see error output in Ant's log and you are redirecting output to a file/property. The error output will not be included in the output file/property. If you redirect error with the error or errorProperty attributes, this will have no effect. | No
append | 输出和错误文件是否应该被附加上或被overwritten。默认设置是false。 | No
createemptyfiles | 即使在输出和错误文件是empty时，它是否应该被产生。默认设置是true。 | No
outputproperty | The name of a property in which the output of the command should be stored. Unless the error stream is redirected to a separate file or stream, this property will include the error output. | No
errorproperty | The name of a property in which the standard error of the command should be stored. | No

A couple of additional attributes can also be specified:

属性 | 描述 | 是否必要
alwaysLog | This attribute is used when you wish to see the output you are capturing, appearing also in the Ant's log. It must not be used unless you are capturing task output. Defaults to false. This attribute will be supported directly by <redirector> in Ant 1.6.3 | No
failonerror This attribute is used when you wish to avoid that any manager command processing error terminates the ant execution. Defaults to true. It must be set to false, if you want to capture error output, otherwise execution will terminate before anything can be captured.
This attribute acts only on manager command execution, any wrong or missing command attribute will still cause Ant execution termination. 		No

They also support the embedded <redirector> element in which you can specify its full set of attributes, but input, inputstring and inputencoding that, even if accepted, are not used because they have no meaning in this context. Refer to ant manual for details on <redirector> element attributes.

Here is a sample build file extract that shows how this output redirection support can be used:

    <target name="manager.deploy"
        depends="context.status"
        if="context.notInstalled">
        <deploy url="${mgr.url}"
            username="${mgr.username}"
            password="${mgr.password}"
            path="${mgr.context.path}"
            config="${mgr.context.descriptor}"/>
    </target>

    <target name="manager.deploy.war"
        depends="context.status"
        if="context.deployable">
        <deploy url="${mgr.url}"
            username="${mgr.username}"
            password="${mgr.password}"
            update="${mgr.update}"
            path="${mgr.context.path}"
            war="${mgr.war.file}"/>
    </target>

    <target name="context.status">
        <property name="running" value="${mgr.context.path}:running"/>
        <property name="stopped" value="${mgr.context.path}:stopped"/>

        <list url="${mgr.url}"
            outputproperty="ctx.status"
            username="${mgr.username}"
            password="${mgr.password}">
        </list>

        <condition property="context.running">
            <contains string="${ctx.status}" substring="${running}"/>
        </condition>
        <condition property="context.stopped">
            <contains string="${ctx.status}" substring="${stopped}"/>
        </condition>
        <condition property="context.notInstalled">
            <and>
                <isfalse value="${context.running}"/>
                <isfalse value="${context.stopped}"/>
            </and>
        </condition>
        <condition property="context.deployable">
            <or>
                <istrue value="${context.notInstalled}"/>
                <and>
                    <istrue value="${context.running}"/>
                    <istrue value="${mgr.update}"/>
                </and>
                <and>
                    <istrue value="${context.stopped}"/>
                    <istrue value="${mgr.update}"/>
                </and>
            </or>
        </condition>
        <condition property="context.undeployable">
            <or>
                <istrue value="${context.running}"/>
                <istrue value="${context.stopped}"/>
            </or>
        </condition>
    </target>

WARNING: even if it doesn't make many sense, and is always a bad idea, calling a Catalina task more than once, badly set Ant tasks depends chains may cause that a task be called more than once in the same Ant run, even if not intended to. A bit of caution should be exercised when you are capturing output from that task, because this could lead to something unexpected:

  • when capturing in a property you will find in it only the output from the first call, because Ant properties are immutable and once set they cannot be changed,
  • when capturing in a file, each run will overwrite it and you will find in it only the last call output, unless you are using the append="true" attribute, in which case you will see the output of each task call appended to the file.

Using the JMX Proxy Servlet
What is JMX Proxy Servlet
JMX Proxy Servlet是用来获取和设置Tomcat内部组织的轻型代理。(或者任何通过MBean被exposed过的类)。 它的用法对客户来说不方便，但是它的UI对于整合命令行scripts来监督和改变Tomcat内部组织很有帮助。你可以用代理来做两件事：获取信息和设置信息。你必须对JMX有个基本了解才能真正理解JMX Proxy Servlet。如果你不知道JMX是什么，那你就会感到迷惑。
JMX Query command
以这种形式：
http://webserver/manager/jmxproxy/?qry=STUFF
这里STUFF是你想要执行的查询(query)。例如，这里是一些你想要运行的查询(queries)：
  • qry=*%3Atype%3DRequestProcessor%2C* --> type=RequestProcessor 找出所有的可以处理请求以及汇报它们的状态的 workers 。
  • qry=*%3Aj2eeType=Servlet%2c* --&gt; j2eeType=Servlet 会返回所有装载的servlets。
  • qry=Catalina%3Atype%3DEnvironment%2Cresourcetype%3DGlobal%2Cname%3DsimpleValue --&gt; Catalina:type=Environment,resourcetype=Global,name=simpleValue 由所给出的名字查看一个特定的MBean。
你得要真正试一试这些查询(queries)才能真正知道它的能力。如果你没有提供qry参数，那么所有的MBeans就会被显示出来。我们极力建议你先去读一读tomcat源代码并弄懂JMX规范，这样你就会更好地理解你运行的那些queries了。
JMX Set command
你可以查询一个MBean,现在是"搅乱"Tomcat内部组织的时候了! 这个set命令的一般形式是:
http://webserver/manager/jmxproxy/?set=BEANNAME&amp;att=MYATTRIBUTE&amp;val=NEWVALUE
这样,你必须提供三个请求参数:
  1. set: 完整的bean名字
  2. att: 你想要改变的特性(attribute)
  3. val: 新的值
如果所有都顺利，机器就会说OK，不然就会出现一段错误消息。例如，我们想要打开ErrorReportValve的排错(debugging)功能，下面将把debugging值设为10:
http://localhost:8080/manager/jmxproxy/
?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost&amp;att=debug&amp;val=10
所得结果是(YMMV):
Result: ok
如果我传送一个坏的值，就会看到下面这种情况。这里我是使用的URL，我把debugging值设为'cowbell':
http://localhost:8080/manager/jmxproxy/
?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost&amp;att=debug&amp;val=cowbell
当试着执行它时，结果是：
Error: java.lang.NumberFormatException: For input string: "cowbell"


Apache Tomcat 5.5 Servlet/JSP 容器 - MBean 描述说明

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

MBean 描述说明
简介

Tomcat 可以使用 JMX 的 MBeans 来实现Tomcat性能管理。

Java包里的 mbeans-descriptor.xml 是 Catalina 的 MBeans 描述。

为了避免"ManagedBean is not found"异常，你需要为你自己的组件添加MBean描述。

增加 MBean 描述

你可以在 mbeans-descriptor.xml 为你自己写的组件添加 MBean 描述，mbeans-descriptor.xml 应该在要描述的Java类同一个目录里，与所在的包一致。请看下面例子：

&lt;mbean name="LDAPRealm"
className="org.apache.catalina.mbeans.ClassNameMBean"
description="Custom LDAPRealm"
domain="Catalina"
group="Realm"
type="com.myfirm.mypackage.LDAPRealm"&gt;

&lt;attribute name="className"
description="Fully qualified class name of the managed object"
type="java.lang.String"
writeable="false"/&gt;

&lt;attribute name="debug"
description="The debugging detail level for this component"
type="int"/&gt;
.
.
.

&lt;/mbean&gt;


Apache Tomcat 5.5 Servlet/JSP 容器 - Monitoring and Managing Tomcat

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Monitoring and Managing Tomcat
前言

监视服务器运行状况对于今天的网路来说已经变得越来越重要。监视服务器的运行，获取统计资料， 修改服务器设置是系统管理员的日常工作。

激活 JMX 遥控器

下列Sun的网站包括了一个 Java 5 版本里 设置 JMX 遥控器的选项： http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html.

这里给你的是一个快速简单的安装步骤：

在你的 Tomcat 的启动程序里加入以下几行：

    set CATALINA_OPTS="-Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=%my.jmx.port% \
    -Dcom.sun.management.jmxremote.ssl=false \
    -Dcom.sun.management.jmxremote.authenticate=false"

  1. 如果你觉得有必要验证使用者的用户名和密码，加入以下几行：
        -Dcom.sun.management.jmxremote.authenticate=true \
    -Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password \
    -Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access \
  2. 修改文件 $CATALINA_BASE/conf/jmxremote.access :
    monitorRole readonly
controlRole readwrite
  3. 修改密码文件 $CATALINA_BASE/conf/jmxremote.password :
    monitorRole tomcat
controlRole tomcat
    注意： 密码文件一定要只允许读取，防止以外修改，还要删除其他用户对这个文件操作的许可。
注意： JSR 160 JMX-Adaptor 会打开另一个数据协议的端口， 如果你安装本地防火墙的话， 这会产生问题。

用 Java 1.4 激活 JMX MX4J Http Adaptor：

  1. 安装 Tomcat 的 compat 版
  2. 把 mx4j-tools.jar 放入 common/lib。 请使用与你安装的 Tomcat一样版本的 MX4j
  3. 在 AJP 连接器中加入 MX4J JMX HTTP Adaptor 设置

          <Connector port="${AJP.PORT}"
            handler.list="mx"
            mx.enabled="true"
            mx.httpHost="${JMX.HOST}"
            mx.httpPort="${JMX.PORT}"
            protocol="AJP/1.3" />

    提示： 如果选择 ${AJP.PORT}=0， ajp 连接器不会在那里启动。

    注意： MX4J JSR 160 RMI Adaptor to support JDK 1.4 currently not integrated.

  4. 启动 Tomcat 然后用浏览器查看： http://${JMX.HOST}:${JMX.PORT}
  5. 如果使用 mx connector 属性 mx.authMode="basic" mx.authUser="tomcat" mx.authPassword="strange" 你可以控制用户登陆。
  6. 你可以在下面网站找到完整的 Tomcat 核心 MBean 的列表： http://tomcat.apache.org/tomcat-5.5-doc/catalina/funcspecs/mbean-names.html

使用 JMX 遥控器的 Ant 指令来管理 Tomcat

Tomcat 提供了使用 Ant 1.6 来管理 Tomcat 的 antlib。

antlib 把 $CATALINA_HOME/server/lib 里的 catalina-ant.jar from 复制到 $ANT_HOME/lib 里。

下面的例子显示 JMX Accessor 的使用方法：

<project name="Catalina Ant JMX"
        xmlns:jmx="antlib:org.apache.catalina.ant.jmx"
        default="state"
        basedir=".">
    <property name="jmx.server.name" value="localhost" />
    <property name="jmx.server.port" value="9012" />
    <property name="cluster.server.address" value="192.168.1.75" />
    <property name="cluster.server.port" value="9025" />

    <target name="state" description="Show JMX Cluster state">
        <jmx:open
            host="${jmx.server.name}"
            port="${jmx.server.port}"
            username="controlRole"
            password="tomcat"/>
        <jmx:get
            name="Catalina:type=IDataSender,host=localhost,senderAddress=${cluster.server.address},senderPort=${cluster.server.port}"
            attribute="connected"
            resultproperty="IDataSender.backup.connected"
            echo="false"
        />
       <jmx:get
            name="Catalina:type=ClusterSender,host=localhost"
            attribute="senderObjectNames"
            resultproperty="senderObjectNames"
            echo="false"
        />
        <!-- get current maxActiveSession from ClusterTest application
             echo it to ant output and store at
             property <em>clustertest.maxActiveSessions.orginal</em>
        -->
       <jmx:get
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            attribute="maxActiveSessions"
            resultproperty="clustertest.maxActiveSessions.orginal"
            echo="true"
        />
        <!-- set maxActiveSession to 100
        -->
        <jmx:set
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            attribute="maxActiveSessions"
            value="100"
            type="int"
        />
        <!-- get all sessions and split result as delimiter <em>SPACE</em> for easy
             access all session ids directly with ant property sessions.[0..n].
        -->
        <jmx:invoke
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            operation="listSessionIds"
            resultproperty="sessions"
            echo="false"
            delimiter=" "
        />
        <!-- Access session attribute <em>Hello</em> from first session.
        -->
        <jmx:invoke
            name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
            operation="getSessionAttribute"
            resultproperty="Hello"
            echo="false"
        >
          <arg value="${sessions.0}"/>
          <arg value="Hello"/>
        </jmx:invoke>
        <!-- Query for all application manager.of the server from all hosts
             and bind all attributes from all found manager mbeans.
        -->
        <jmx:query
            name="Catalina:type=Manager,*"
            resultproperty="manager"
            echo="true"
            attributebinding="true"
        />
        <!-- echo the create properties -->
        <echo>
           senderObjectNames: ${senderObjectNames.0}
           IDataSender.backup.connected: ${IDataSender.backup.connected}
           session: ${sessions.0}
           manager.length: ${manager.length}
           manager.0.name: ${manager.0.name}
           manager.1.name: ${manager.1.name}
           hello: ${Hello}
           manager.ClusterTest.0.name: ${manager.ClusterTest.0.name}
           manager.ClusterTest.0.activeSessions: ${manager.ClusterTest.0.activeSessions}
           manager.ClusterTest.0.counterSend_EVT_SESSION_EXPIRED: ${manager.ClusterTest.0.counterSend_EVT_SESSION_EXPIRED}
           manager.ClusterTest.0.counterSend_EVT_GET_ALL_SESSIONS: ${manager.ClusterTest.0.counterSend_EVT_GET_ALL_SESSIONS}
        </echo>

    </target>

</project>

导入： 用下面的指令导入 JMX Accessor 项目 <import file="${CATALINA.HOME}/bin/jmxaccessor-tasks.xml" /> ， 参考下面的 Ant 指令： jmxOpen, jmxSet, jmxGet, jmxQuery, jmxInvoke,jmxEquals and jmxCondition.

JMXAccessorOpenTask - jmx 打开连接指令

属性
属性 | 描述 | 缺省值
url | 设置 jmx 连接 url - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi
<Host> | 设置主机名，简化冗长的 url 格式 | localhost
port | 设置遥控连接的端口 | 8050
username | 遥控器用户名
password | jmx 遥控器用户连接密码
ref | Name of the internal connection referenz. With this attribute you can configure more the one connection inside the same ant projekt. | jmx.server
echo | Echo the command usage (for analyse access or debugging) | false
if | Only execute if a property of the given name exists in the current project.
unless | Only execute if a property of the given name not exists in the current project.

实例：jmx 连接

    <jmx:open
            host="${jmx.server.name}"
            port="${jmx.server.port}"
    />

实例：用URL、用户名和密码打开 jmx 连接

    <jmx:open
            url="service:jmx:rmi:///jndi/rmi://localhost:9024/jmxrmi"
            ref="jmx.server.9024"
            username="controlRole"
            password="tomcat"
    />

实例：当jmx.if 存在而且jmx.unless不存在，用URL、用户名和密码打开 jmx 连接

    <jmx:open
            url="service:jmx:rmi:///jndi/rmi://localhost:9024/jmxrmi"
            ref="jmx.server.9024"
            username="controlRole"
            password="tomcat"
            if="jmx.if"
            unless="jmx.unless"
    />

注意：jmxOpen任务的属性同样适用于其他任务或条件。

JMXAccessorGetTask: get attribute value ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=Server
attribute | Existing Mbean attribute (see Tomcat mbean description above)
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false
resultproperty | Save result at this project property
delimiter | Split result with delimiter (java.util.StringTokenizier) and use resultproperty as prefix to store tokens.
separatearrayresults | When return value is an array, save result as property list ($resultproperty.[0..N] and $resultproperty.lenght) | true

Example to get remote mbean attribute from default jmx connection

    <jmx:get
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        attribute="maxActiveSessions"
        resultproperty="servlets-examples.maxActiveSessions"
    />

Example to get and result array and split it at separate properties

    <jmx:get
        name="Catalina:type=ClusterSender,host=localhost"
        attribute="senderObjectNames"
        resultproperty="senderObjectNames"
    />
Access the senderObjectNames properties with:
    ${senderObjectNames.lenght} give the number of returned sender list.
    ${senderObjectNames.[0..N]} found all sender object names

Example to get IDataSender attribute connected only when cluster is configured.

<jmx:query
    failonerror="false"
    name="Catalina:type=Cluster,host=${tomcat.application.host}"
    resultproperty="cluster"
/>
<jmx:get
    name="Catalina:type=IDataSender,host=${tomcat.application.host},senderAddress=${cluster.backup.address},senderPort=${cluster.backup.port}"
    attribute="connected"
    resultproperty="datasender.connected"
    if="cluster.0.name" />

JMXAccessorSetTask: set attribute value ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=Server
attribute | Existing Mbean attribute (see Tomcat mbean description above)
value | value that set to attribute
type | type of the attribute. | java.lang.String
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false

Example to set remote mbean attribute value

    <jmx:set
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        attribute="maxActiveSessions"
        value="500"
        type="int"
    />

Examples to set multiple remote mbean attributes

    <jmx:set
        name="java.lang:type=Threading">
             <arg name="ThreadContentionMonitoringEnabled" value="true" type="boolean"/>
             <arg name="ThreadCpuTimeEnabled" value="false" type="boolean"/>
    </jmx:set>

JMXAccessorInvokeTask: invoke Mbean operation ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=Server
operation | Existing Mbean operation (see Tomcat http://tomcat.apache.org/tomcat-5.5-doc/catalina/funcspecs/fs-admin-opers.html.
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false
resultproperty | Save result at this project property
delimiter | Split result with delimiter (java.util.StringTokenizier) and use resultproperty as prefix to store tokens.
separatearrayresults | When return value is an array, save result as property list ($resultproperty.[0..N] and $resultproperty.lenght) | true

stop an application

    <jmx:invoke
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        operation="stop"/>
Now you can find the sessionid at ${sessions.[0..N} properties and access the count with ${sessions.lenght} property.

Example to get all sessionids

    <jmx:invoke
        name="Catalina:type=Manager,path=/servlets-examples,host=localhost"
        operation="listSessionIds"
        resultproperty="sessions"
        delimiter=" "
    />
Now you can find the sessionid at ${sessions.[0..N} properties and access the count with ${sessions.lenght} property.

Example to get remote mbean session attribute from session ${sessionid.0}

    <jmx:invoke
        name="Catalina:type=Manager,path=/ClusterTest,host=localhost"
        operation="getSessionAttribute"
        resultproperty="hello">
         <arg value="${sessionid.0}"/>
         <arg value="Hello" />
 </jmx:invoke>

Example to create a new access logger valve at vhost localhost

 <jmx:invoke
         name="Catalina:type=MBeanFactory"
         operation="createAcccesLoggerValve"
         resultproperty="acccesLoggerObjectName"
 >
     <arg value="Catalina:type=Host,host=localhost"/>
 </jmx:invoke>
Now you can find new Mbean with name stored at ${acccesLoggerObjectName} proeprty.

JMXAccessorQueryTask: query Mbean ant task

List of Attributes
属性 | 描述 | Default value
name | JMX ObjectName query string -- Catalina:type=Manager,*
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false
resultproperty | Prefix project property name to all founded Mbeans (mbeans.[0..N].objectname)
attributebinduing | bind ALL MBean attributes in addition to name | false
delimiter | Split result with delimiter (java.util.StringTokenizier) and use resultproperty as prefix to store tokens.
separatearrayresults | When return value is an array, save result as property list ($resultproperty.[0..N] and $resultproperty.lenght) | true

Get all Manager ObjectNames from all services and Hosts

  <jmx:query
           name="Catalina:type=Manager,*
           resultproperty="manager" />
Now you can find the Session Manager at ${manager.[0..N].name} properties and access the result object counter with ${manager.length} property.

Example to get the Manager from servlet-examples application an bind all mbean properties

  <jmx:query
           name="Catalina:type=Manager,path=/servlet-examples,host=localhost*"
           attributebinding="true"
           resultproperty="manager.servletExamples" />
Now you can find the manager at ${manager.servletExamples.0.name} property and can access all properties from this manager with ${manager.servletExamples.0.[manager attribute names]}. The result object counter from MBeans is stored ad ${manager.length} property.

Example to get all MBeans from a server and store inside an external xml property file

<project name="jmx.query"
            xmlns:jmx="antlib:org.apache.catalina.ant.jmx"
            default="query-all" basedir=".">
<property name="jmx.host" value="localhost"/>
<property name="jmx.port" value="8050"/>
<property name="jmx.username" value="controlRole"/>
<property name="jmx.password" value="tomcat"/>

<target name="query-all" description="Query all MBeans of a server">
<!-- Configure connection -->
<jmx:open
    host="${jmx.host}"
    port="${jmx.port}"
    ref="jmx.server"
    username="${jmx.username}"
    password="${jmx.password}"/>
<!-- Query MBean list -->
<jmx:query
    name="*:*"
    resultproperty="mbeans"
    attributebinding="false"/>

<echoproperties
    destfile="mbeans.properties"
    prefix="mbeans."
    format="xml"/>

<!-- Print results -->
<echo
    message="Number of MBeans in server ${jmx.host}:${jmx.port} is ${mbeans.length}"/>
</target>
</project>
Now you can find all MBeans inside the file mbeans.properties.

JMXAccessorCreateTask: remote create mbean ant task

List of Attributes
属性 | 描述 | Default value
name(名称) | Full qualified JMX ObjectName -- Catalina:type=MBeanFactory
className | Existing MBean full qualified classname (see Tomcat mbean description above)
classLoader ObjectName of server or web application classloader
( Catalina:type=ServerClassLoader,name=[server,common,shared] or
Catalina:type=WebappClassLoader,path=/myapps,host=localhost)
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false

Example to create remote mbean

    <jmx:create
             ref="${jmx.reference}"
             name="Catalina:type=MBeanFactory"
             className="org.apache.commons.modeler.BaseModelMBean"
             classLoader="Catalina:type=ServerClassLoader,name=server">
             <Arg value="org.apache.catalina.mbeans.MBeanFactory" />
    </jmx:create>

Warning: A lot of tomcat mbeans can't be really create and connect with
the parent. The valve, cluster or realm Mbeans are not autconnect with there parent.
Use MBeanFacrory create operation instead.

JMXAccessorUnregisterTask: remote unregister mbean ant task

List of Attributes
属性 | 描述 | Default value
name | Full qualified JMX ObjectName -- Catalina:type=MBeanFactory
ref | JMX Connection reference | jmx.server
echo | Echo command usage (access and result) | false

Example to unregister remote mbean

    <jmx:unregister
        name="Catalina:type=MBeanFactory"
    />

Warning: A lot of tomcat mbeans can't be really unregister.
The Mbeans are not deregister from parent. Use MBeanFacrory
remove operation instead.

JMXAccessorCondition: express condition

List of Attributes
属性 | 描述 | Default value
url | Set jmx connection url - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi
host | Set the host, shortcut the very long url syntax. | localhost
port | Set the remote connection port | 8050
username | remote jmx connection user name.
password | remote jmx connection password.
ref | Name of the internal connection reference. With this attribute you can configure more the one connection inside the same ant projekt. | jmx.server
name | Full qualified JMX ObjectName -- Catalina:type=Server
echo | Echo condition usage (access and result) | false
if | Only execute if a property of the given name exists in the current project.
unless | Only execute if a property of the given name not exists in the current project.
value (requiered) | Second arg for operation
type | Value type to express operation (support long and double) | long
operation express one
  • == equals
  • != not equals
  • > greater than (&gt;)
  • >= greater than or equals (&gt;=)
  • < lesser than (&lt;)
  • <= lesser than or equals (&lt;=)
 ==

Wait for server connection and that cluster backup node is accessable

      <target name="wait">
         <waitfor maxwait="${maxwait}" maxwaitunit="second" timeoutproperty="server.timeout" >
            <and>
                <socket server="${server.name}" port="${server.port}"/>
                <http url="${url}"/>
                <jmx:condition
                    operation="=="
                    host="localhost"
                    port="9014"
                    username="controlRole"
                    password="tomcat"
                    name="Catalina:type=IDataSender,host=localhost,senderAddress=192.168.111.1,senderPort=9025"
                    attribute="connected"
                    value="true"
                />
            </and>
        </waitfor>
        <fail if="server.timeout" message="Server ${url} don't answer inside ${maxwait} sec" />
        <echo message="Server ${url} alive" />
    </target>

JMXAccessorEqualsCondition: equals Mbean ant condition

List of Attributes
属性 | 描述 | Default value
url | Set jmx connection url - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi
host | Set the host, shortcut the very long url syntax. | localhost
port | Set the remote connection port | 8050
username | remote jmx connection user name.
password | remote jmx connection password.
ref | Name of the internal connection referenz. With this attribute you can configure more the one connection inside the same ant projekt. | jmx.server
name | Full qualified JMX ObjectName -- Catalina:type=Server
echo | Echo condition usage (access and result) | false

Wait for server connection and that cluster backup node is accessable

      <target name="wait">
         <waitfor maxwait="${maxwait}" maxwaitunit="second" timeoutproperty="server.timeout" >
            <and>
                <socket server="${server.name}" port="${server.port}"/>
                <http url="${url}"/>
                <jmx:equals
                    host="localhost"
                    port="9014"
                    username="controlRole"
                    password="tomcat"
                    name="Catalina:type=IDataSender,host=localhost,senderAddress=192.168.111.1,senderPort=9025"
                    attribute="connected"
                    value="true"
                />
            </and>
        </waitfor>
        <fail if="server.timeout" message="Server ${url} don't answer inside ${maxwait} sec" />
        <echo message="Server ${url} alive" />
    </target>


Apache Tomcat 5.5 Servlet/JSP 容器 - 用代理服务器整合Apache和Tomcat

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

用代理服务器整合Apache和Tomcat
介绍

使用标准的Tomcat设置，WEB应用里的Servlet或JSP可以下面的方法，获得为用户服务的主机名称和使用 端口的号码。如果让Tomcat单独运行而不与其他WEB服务器捆绑，Tomcat一般可以转达用户请求里指定的 服务器名称和Tomcat设置里“Connector”所监听的端口。下面的 Servlet API里 面的方法可以用来解决这个问题：

  • ServletRequest.getServerName(): 用户请求里指定的主机名。
  • ServletRequest.getServerPort(): 用户请求里指定的端口。
  • ServletRequest.getLocalName(): 收到用户请求的主机名。
  • ServletRequest.getLocalPort(): 收到用户请求的主机端口。

当你的Tomcat在一个代理服务器(或一个被配置成与代理服务器行为一样的web服务器)后面运行，你 有时候希望根据用户的访问请求的服务器名和端口号码来正确处理，而不是Connector 本监听的那个端口和主机名。你可以使用 &lt;Connector&gt;元素里面的proxyName 和 proxyPort 属性来配置这些值。

用代理器来捆绑Tomcat和Apache可以有多种形式。下面的章节描述了几种常见情况的代理配置。

用代理器捆绑 Tomcat 和 Apache 1.3

Apache 1.3支持一个任选模块(mod_proxy)，这个任选模块用来配置web服务器， 让这个web服务器象代理服务器一样工作。这可以用来把指定的web应用程序的请求传递到一个 Tomcat 去，而不需要配置一个象mod_jk 的web connector。要做到这样， 你需要执行下面的任务：

  1. 修改你的Apache 配置,让它包含mod_proxy模块。如果你从源代码开始创建， 最容易的办法是把--enable-module=proxy指令包含在./configure 命令行上。
  2. 如果你还没有安装mod_proxy模块，你可以在httpd.conf文件里 使用下列指令来装载它：
    LoadModule proxy_module {path-to-modules}/mod_proxy.so
AddModule mod_proxy.c
  3. 对于每个你想要传递给Tomcat的web应用程序，在你的httpd.conf文件里包含 两个指令。例如：
    ProxyPass /myapp http://localhost:8081/mywebapp
ProxyPassReverse /myapp http://localhost:8081/mywebapp
    它告诉Apache把http://localhost/mywebapp/*形式的URLs传递给在端口8081上 监听的 Tomcat 连接器， /mywebapp 是Tomcat里的一个应用。
  4. 修改Tomcat 的 server.xml，让它包括一个特殊的&lt;Connector&gt;元素，以及相应 的代理设置，例如：
    &lt;Connector port="8081" ...
proxyName="www.mycompany.com"
proxyPort="80"/&gt;
    它会让这个web应用程序里边的servlets认为 所有的代理请求被导向端口80上的www.mycompany.com 。
  5. 从&lt;Connector&gt;元素里省略掉proxyName属性是合法的。 如果你这样做，由request.getServerName()返回的值将是Tomcat在它上面运行 的那个主机名字。 在上面的例子中，它就是localhost。
  6. 如果你还有一个在端口8080上监听的&lt;Connector&gt在Service元素里，向其中 任何一个端口发出的请求都将共享相同的虚拟主机和web应用程序。
  7. 你可以使用你的操作系统的IP过滤(filtering)来限制与端口8081的连接， 这个例子里，使用户不能直接连接到8081或8080端口上而一定要通过端口80上的Apache。
  8. 或者，你可以设置仅仅通过代理(proxying)才能被使用的一系列web应用程序，如下：
    • 为代理端口配置包含仅仅一个&lt;Connector&gt;元素的另外一个 &lt;Service&gt;。
    • 通过代理为虚拟主机和web应用程序配置相应的 Engine，Host， 和Context元素。
    • 或者，如早先描述的那样以IP过滤器保护端口8081。
  9. 当请求被Apache代理处理，Apache服务器的访问日志会记录这些请求。因此，你应该终止Tomcat本身 的访问日志。

当请求以这种形式被代理，配置过的web应用程序的所有请求都将由Tomcat处理 (包括对静态内容的请求)。你可以通过使用mod_jk web connector， 而不是mod_proxy 来提高性能。mod_jk可以配置成让web服务器来提供那些静态内容， 如果静态内容在web应用程序部署描述符/WEB-INF/web.xml被定义为必须经过过滤器或有 安全限制，这些内容仍然会由Tomcat来处理。

用代理器捆绑 Tomcat 与 Apache 2.0
在Apache 2.0里，可以忽略AddModule mod_proxy.c， 其它与1.3的说明相同。


Apache Tomcat 5.5 Servlet/JSP 容器 - 权限管理 - 域(Realm)的设置

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

权限管理 - 域(Realm)的设置
目录

快 速 上 手

什么是域（Realm）?
配置一个域（Realm）
域的共有属性
把密码加密（Digested）
应用程序示例
Tomcat管理员程序
在域（Realm）里面纪录日志
Tomcat现有的标准域（Realm）
JDBCRealm
DataSourceRealm
JNDIRealm
MemoryRealm
JAASRealm
UserDatabaseRealm

快 速 上 手

这个文档描述了怎样通过用一个现有"数据库"里的用户名,密码以及角色来配置 Tomcat，从而来支持容器管理的安全性(container managed security)。 如果你使用一个网络程序，而这个程序里包括了一个或多个<security-constraint> 元素，以及一个定义用户怎样认证他们自己的<login-config>元素，那你就需要设置 这些域（Realm）。如果你不使用这些功能，你就可以跳过这个文档。

关于容器管理安全性的基础背景知识，参看 Servlet 规范 (Version 2.4)，第12章。

关于使用Tomcat 5的一次性登录特性(允许用户只需认证他自己一次就可以使用和虚拟 主机相关的所有网络程序)的信息。请看这里。

概述
什么是域（Realm）?

域(Realm)是一个存储用户名,密码以及和用户名相联系的角色的”数据库”, 用户名,密码用来验证 用户对一个或多个web应用程序的有效性。访问应用程序中特定资源的权限是被授予了拥有特殊角色的用户， 而不是相关的用户名。通过用户名相关联，一个用户可以有任意数量的角色。

尽管Servlet规范描述了一个可以让应用程序声明它们安全性要求(在web.xml 部署描述符里)的机制，但是并没有的API(应用编程接口)来定义一个基于servlet容器和其 相关用户角色之间的界面(interface)。然而在许多情况下，最好能把一个servlet容器和那些已经存在 的认证数据库或机制“连接”起来。因此，Tomcat 5定义了一个 Java界面(org.apache.catalina.Realm)，它可以通过"插件"来实现 这种连接。这里提供了五个标准的插件，用来支持与各个认证信息来源的连接：

  • JDBCRealm - 通过JDBC驱动来访问贮存在关系数据库里的认证信息。
  • DataSourceRealm - 通过一个叫做JNDI JDBC 的 数据源(DataSource)来访问贮存在关系数据库里的认证信息。
  • JNDIRealm - 通过JNDI provider来访问贮存在基于 LDAP(轻量目录访问协议)的目录服务器里的认证信息。
  • MemoryRealm - 访问贮存在电脑内存里的认证信息，它是通过一个 XML文件(conf/tomcat-users.xml)来进行初始化的。
  • JAASRealm - 使用 Java Authentication & Authorization Service (JAAS).

也可以编写你自己的Realm implementation，然后与Tomcat整合在一起。你需要：

  • 实现org.apache.catalina.Realm
  • 把编译过的文件放置到&#036;CATALINA_HOME/server/lib里边
  • 象下面的"配置一个域（Realm）" 章节里描述的那样声明你的realm。
  • 用MBeans 描述符声明你的realm。

配置一个域（Realm）

在进入详细的标准Realm实现之前，弄懂怎样配置一个域（Realm）是很重要的。通常，你需要把 一个XML元素加入到你的conf/server.xml配置文件中，它看起来象这样：

&lt;Realm className="... class name for this implementation"
... other attributes for this implementation .../&gt;

<Realm>元素可以被套嵌在下列任何一个Container 元素里面。这个Realm元素所处的位置直接影响到这个域（Realm）的作用范围（比如，哪些web应用程序 会共享相同的认证信息）：

  • 在<Engine>元素里边 - 这个域（Realm）将会被所有虚拟主机上的所有 网络程序共享，除非它被嵌套在下级<Host> 或 <Context>元素里的Realm元素覆盖。
  • 在<Host>元素里边 - 这个域（Realm）将会被该虚拟主机上所有的 网络程序所共享，除非它被嵌套在下级<Context>元素里的Realm元素覆盖。
  • 在<Context>元素里边 - 这个域（Realm）只被该网络程序使用。
共有特性
把密码加密

对于每个现有的Realm实现里，用户的密码(默认情况下)以明文形式 被贮存。在许多环境中，这是不理想的，因为任何人看见了认证数据都可以收集足够信息成功登录，冒充 其他用户。为了避免这个问题，标准的实现支持digesting用户密码的概念。这被贮存的 密码是被加密后的(以一种不易被转换回去的形式)，但是Realm实现还是可以用它来认证。

当一个标准的realm通过取得贮存的密码并把它与用户提供的密码值作比较来认证时，你可通过在你 的元素<Realm>上指定digest属性选择digested密码。 这个属性的值必须是java.security.MessageDigest class (SHA, MD2, or MD5) 支持的digest 算法之一。当你选择这一选项，贮存在域（Realm）里的密码内容必须是这个密码的明文 形式，然后被指定的运算法则来加密。

当这个Realm的authenticate()方法被调用，用户指定的(明文) 密码被相同的运算法来加密，它的结果与Realm返回的值作比较。如果两个值对等的话，就意味着 原始密码的明文版与用户提供的一样，所以这个用户就被认证了。

要计算一个明文密码经过加密的值，Tomcat 支持下面两个便利的技术：

  • 如果你在编写一个需要自动加密密码的程序， 调用org.apache.catalina.realm.RealmBase类里的Digest()方法， 把明文密码和加密的算法名字作为参数传递过去。这种方法会返回的是经过加密的密码。
  • 如果你想要使用命令行设施来加密密码，简单地执行以下命令：
    java org.apache.catalina.realm.RealmBase \
-a {algorithm} {cleartext-password}
    这个明文密码的加密版本会以标准输出 形式返回。

如果使用加密的密码进行DIGEST认证，用于产生digest的明文是不一样的。在上面的例子中， {cleartext-password}必须被{username}:{realm}:{cleartext-password} 取代。比如说，在一个开发环境中它是这样的形式testUser:localhost:8080:testPassword。

要使用上面所说的任何一个技术，需要把$CATALINA_HOME/server/lib/catalina.jar 文件放在你的class path上，让RealmBase类可以被使用。另外，你还需要JMX.jar和 commons-logging.jar文件 (要么是 commons-logging-api.jar 要么是 commons-logging.jar)。 Tomcat包括有这俩个文件。

非ASCII的用户名和/或密码也被支持，但你需要使用下面的命令

java org.apache.catalina.realm.RealmBase \ -a {algorithm} -e {encoding} {input}
不过必须要保证这个非ASCII输入正确地传递给digester。这个digester会返回 {input}:{digest}值。如果返回的input有误，加密也就是无效的。

应用程序示例

和Tomcat一起的应用程序示例包括被安全限制保护的一个区域,需要使用基于-表格(form-based)的登录。 想要访问它，把浏览器指向http://localhost:8080/jsp-examples/security/protected/， 并使用默认的MemoryRealm里所描述的用户名和密码来登录。

Tomcat管理员程序

如果你想要使用管理员程序(Manager Application) 在运行的Tomcat安装里部署和删除应用程序，你必须在你选择的Realm实现中至少给一个用户名添加 "manager"角色。这是因为管理员网络应用程序本身使用一个安全限制， 需要"manager"的角色在这个程序里面访问任何请求URI。

因为安全的原因，在默认的Realm里(i.e. 使用 conf/tomcat-users.xml文件）没有用户名被指派"manager"角色。 因此，在Tomcat administrator特别地给一个或几个用户指派这个角色之前，没有人能够利用这个程序。

在域（Realm）里面纪录日志

每个Realm排错和异常信息将由与这个realm的容器相关的日志配置记录下来： 它的Context, Host, 或 Engine。

Tomcat现有的标准域（Realm）
JDBCRealm

简介

JDBCRealm是一个Tomcat Realm界面实现，它通过JDBC驱动来查看关系数据库 里的用户信息。这里配置的可塑性很大，它让你能够使用现存的表名和列名(column names)，只要你的 数据库结构与下面的要求一致：

  • 必须要有一个表格(table)存在，它必须是每一行包含一个这个Realm所能识别的 合法用户。下面引用叫做users的表格。
  • 这个用户表格必须包括至少两列(如果你的程序需要还可以有更多列)。
    • 可被Tomcat识别的用户登录名称(username)。
    • 可被Tomcat识别的用户登录密码。这个值可以是明文式(cleartext)或是被编码过(digested) 的形式 - 下面可查看更多信息。
  • 必须要有一个表格存在，它必须是每一行包含一个指派给某个特定用户的某个合法角色。 下面引用叫做user_roles的表格。
  • 这个user_roles表格必须包括至少两列(如果你的程序需要还可以有更多列)：
    • 可被Tomcat识别的用户登录名称(和users table里指定的值相同)。
    • 和这个user_name相关联的有效role_name。

快 速 上 手

要设置好Tomcat来使用JDBCRealm，你必须遵守下面这些步骤：

  1. 根据上面所描述的规定，在你的数据库里产生表格(tables)和列(columns)。
  2. 配置一个可供Tomcat使用的用户名称和密码，它至少应该有只读(read only)权限来访问上述表格。 (Tomcat从不会试图去改写这些表格)。
  3. 把你将要使用的JDBC驱动复制件放置到$CATALINA_HOME/server/lib目录 (如果你不想让网络程序使用它的话)或者放在$CATALINA_HOME/common/lib(如果 Tomcat 和你的程序都要使用它的话)。注意，唯一只有JAR文件才能 被识别。
  4. 象下面所描述的那样，在你的$CATALINA_HOME/conf/server.xml文件设置一个 <Realm>元素。
  5. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 JDBCRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

一个用于产生所需表格的SQL script示例也许看起来象这样(根据你特定的数据库需要做些语法上的改编):

create table users (
user_name varchar(15) not null primary key,
user_pass varchar(15) not null
);

create table user_roles (
user_name varchar(15) not null,
role_name varchar(15) not null,
primary key (user_name, role_name)
);

关于Realm元素的例子被包括在默认的$CATALINA_HOME/conf/server.xml 文件里(但被 commented out)。在下面的例子中，使用了一个叫做"authority"的 MySQL数据库，根据上面所描述的表格进行了配置，可以通过用户名"dbuser" 和 密码"dbpass"进行访问:

<Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="org.gjt.mm.mysql.Driver"
connectionURL="jdbc:mysql://localhost/authority?user=dbuser&amp;amp;password=dbpass"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

另外的注意事项

JDBCRealm根据下面的规则进行运作：

  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会传叫(call)这个Realm 的authenticate()方法。因此，你对于这个数据库所做的认何直接更改(新用户，更改 过的密码和角色等等)都会被立即反映出来。
  • 一但用户被认证，用户(以及其相关角色)在这个用户登录期间会被高速缓存(cache)在Tomcat里。 (对于是基于表单(FORM-based)认证的用户，在会话结束或者注销后认证失效；对于BASIC认证的用户， 要等到用户关闭窗口后认证才失效)。被高速缓存的用户不会 在会话系列之间被贮存或再生(restored)。对于已经被认证的用户，任何有关数据库信息的更改，一直 要等到下次用户再次登录后才会被显示出来。
  • 管理users和user_roles表格里的信息应该是你的应用程序的职责。Tomcat没有 提供任何built-in 能力来维护用户及其角色信息。
DataSourceRealm

简介

DataSourceRealm是一个Tomcat 5 Realm界面实现，它通过 一个叫做JDBC DataSource的JNDI来访问查询关系数据库里的用户信息。这里配置的可塑性很大，让你 能够使用现有的表名和列名，只要你的数据库结构与下面的要求一致：

  • 必须要有一个表格(table)存在，它必须是每一行包含一个这个Realm所能识别的 合法用户。下面引用叫做users的表格。
  • 这个用户表格必须包括至少两列(如果你的程序需要还可以有更多列)。
    • 可被Tomcat识别的用户登录名称(username)。
    • 可被Tomcat识别的用户登录密码。这个值可以是明文式(cleartext)或是被编码过(digested) 的形式 - 下面可查看更多信息。
  • 必须要有一个表格存在，它必须是每一行包含一个指派给某个特定用户的某个合法角色。下面引用叫 做用户角色的表格。
  • 这个用户角色表格必须包括至少两列(如果你的程序需要还可以有更多列)：
    • 可被Tomcat识别的用户登录名称(和users table里指定的值相同)。
    • 和这个用户相关联的有效角色名称。

快 速 上 手

要设置好Tomcat来使用DataSourceRealm，你必须遵守下面这些步骤：

  1. 根据上面所描述的规定，在你的数据库里产生表格(tables)和列(columns)。
  2. 配置一个可供Tomcat使用的用户名称和密码，它至少应该有只读(read only)权限来访问上述表格。 (Tomcat从不会试图去改写这些表格)。
  3. 为你的数据库配置一个叫做JDBC DataSource的JNDI。关于怎样配置一个叫做JDBC DataSource的 JNDI的信息请参看JNDI DataSource Example HOW-TO 。
  4. 象下面所描述的那样，在你的$CATALINA_HOME/conf/server.xml文件设置一个 <Realm>元素。
  5. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 DataSourceRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

一个用于产生所需表格的SQL script示例也许看起来象这样(根据你特定的数据库需要做些语法上的改编):

create table users (
user_name varchar(15) not null primary key,
user_pass varchar(15) not null
);

create table user_roles (
user_name varchar(15) not null,
role_name varchar(15) not null,
primary key (user_name, role_name)
);

在下面的例子中，使用了一个叫做"authority"的MySQL数据库，根据上面所描述的表格 进行了配置，可以通过"java:/comp/env/jdbc/authority"访问JNDI JDBC DataSource:

<Realm className="org.apache.catalina.realm.DataSourceRealm" debug="99"
dataSourceName="jdbc/authority"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

另外的注意事项

DataSourceRealm根据下面的规则进行运作：

  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会传叫(call)这个Realm的 authenticate()方法。因此，你对于这个数据库所做的认何直接更改(新用户，更改过的 密码和角色等等)都会被立即反映出来。
  • 一但用户被认证，用户(以及其相关角色)在这个用户登录期间会被高速缓存(cache)在Tomcat里。 (对于是基于表单(FORM-based)认证的用户，在会话结束或者注销后认证失效；对于BASIC认证的用户， 要等到用户关闭窗口后认证才失效)。被高速缓存的用户不会 在会话系列之间被贮存或再生(restored)。对于已经被认证的用户，任何有关数据库信息的更改，一直 要等到下次用户再次登录后才会被显示出来。
  • 管理users和user_roles角色表格里的信息应该是你的应用程序的职责。Tomcat没有 提供任何built-in 能力来维护用户及其角色信息。
JNDIRealm

简介

DataSourceRealm是一个Tomcat 5 Realm界面实现，它通过一个JNDI provider 来访问查询LDAP目录里的用户信息(通常是与JNDI API类一起的标准LDAP provider)。这个realm支持一系列使用目录来进行认证的方法。

与目录相连接

这个realm与目录的连接是由connectionURL配置属性定义的。这个URL的 格式又是由JNDI provider来定义的。它通常是一个LDAP URL，用来指定相连接的目录服务器的领域 名称，或者端口数码以及所需的root naming context的特殊名称。

如果你有不止一个供应者(provider)，你可以配置一个alternateURL。如果 不能在connectionURL与供应者连接上，机器就会试图使用alternateURL来连接。

在为了查询目录和搜索用户及其角色进行连接的时候，这个realm就通过connectionName 和 connectionPassword 属性指定的用户名称和密码来向这个目录认证它自己。 如果属性没有被指定，连接就是无名的。在许多情形下，这也足够了。

选择用户的目录进入

每一个能被认证的用户必须在目录里由一个单个登录(individual entry)来代表，这个单个登录与 初始DirContext里边被connectionURL属性定义的一个元素相 对应。这个用户登录必须有一个包含认证用的用户名称的属性(attribute).

通常这个用户登录的特殊名称包含提供给认证用的用户名，否则所有用户都一样。在这种情况下， userPattern这个属性也许可用来指定DN(特殊名称)，用"{0}" 来标记用户名在什么地方可被替代。

否则这个realm必须搜寻(search)目录才能找到包含用户名称的独特的登录。这样的搜寻由下面的这些 属性配置：

  • userBase - 这个输入是作为包含用户信息subtree的基础。如果没有 指定，search base是最上层context。
  • userSubtree - 搜寻范围。如果你想搜寻根基于 userBase entry的整个subtree，把它设置为true。 默认的值false要求仅仅包括上层的单层搜寻。
  • userSearch - 指定要使用的LDAP搜寻过滤器的模式

认证用户

  • 绑定模式

    在默认的情况下，realm通过与带有用户和用户密码的目录绑定在一起来认证一个用户。如果这个简单 的绑定成功的话，用户就被认为被认证过了。

    因为安全的原因，目录会储存digest形式的用户密码，而不是明码版本(更多信息请看 Digested 密码)。在这种情况下，作为简单绑定操作的一部分， 目录在与储存的值核对之前自动把用户提供的正文密码换算成正确的digest。因此在绑定模式里，域（realm） 没有参与digest过程。这个digest属性没有被使用，即使被设置了，也被忽略掉。

  • 比较模式

    另外，域（realm）可以从目录中取出储存的密码并与用户提供的值做直接比较。通过把 userPassword属性设定为带有密码的用户输入里的一个 directory attribute的名字来配置这个模式。

    比较模式有一些不利的地方。第一，connectionName 和 connectionPassword 属性必须配置能让realm去阅读在目录里的用户密码。 因为安全的原因，这通常是不可取的，事实上，许多目录implementations不允许，即使是目录管理员 也不允许阅读这些密码。另外，realm必须自己处理password digests，包括使用运算法则的变化， 和在目录里表示密码hashes的方法。不过，realm有时也需要访问储存的密码，例如，要支持 HTTP Digest Access Authentication (RFC 2069)。(注意，HTTP digest认证不同于上面所 讨论的在用户信息储藏室里的password digests储存)。

给用户指派角色

目录域（realm）支持下列两种方法来在目录里代表角色：

  • 作为显式目录输入的角色

    角色可以通过显式的目录输入来代表。一个role entry通常是一个LDAP group entry，它具有一个 包含这个角色的名字以及另一个值为这个角色的特殊名字或用户名的属性。下面的这些属性配置一个目录 搜寻来发现与这个认证过的用户相关联的角色名称。

    • roleBase - 角色搜寻的基础输入。如果没有指定，search base是顶层目录context。
    • roleSubtree - 搜寻范围。如果你想搜寻根基于roleBase entry的整个subtree，把它设置为true。默认的值false要求仅仅 包含顶层的单层搜寻。
    • roleSearch - 选择角色输入的LDAP搜寻过滤器。它可选择性地包含两个 模式替代："{0}" 代替被认证过的用户的特殊名字，以及/或者 "{1}" 代替 被认证过的用户的用户名。
    • roleName - 包含那个角色名字的role entry里的属性。

  • 作为用户输入的一个属性的角色

    角色名字也可以作为在用户目录输入里一个属性的值。使用userRoleName来 指定这个属性的名称。

这两种代表角色方法的组合也可以被使用。

快 速 上 手

要设置好Tomcat来使用JNDIRealm，你必须遵守下面这些步骤：

  1. 确保你的目录服务器是依据上面的要求配置的。
  2. 如果需要，配置一个可供Tomcat使用的用户名称和密码，它应该有只读(read only)权限来访问 上述表格。(Tomcat从不会试图去改写这些表格)。
  3. 把你将要使用的JNDI驱动(通常ldap.jar available with JNDI)复制件放置 到$CATALINA_HOME/server/lib目录(如果你不想让网络程序使用它的话)或者放在 $CATALINA_HOME/common/lib(如果Tomcat 5和你的程序都要使用它的话)。
  4. 象下面所描述的那样，在你的$CATALINA_HOME/conf/server.xml文件设置一个 <Realm>元素。
  5. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 JNDIRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

因为每个目录服务器的实现都不同，在你的目录服务器里产生相适宜的schema超出了本文的范围。在 下面的例子里，我们假设你使用的是OpenLDAP目录服务器(2.0.11或其后版本)，你可以从 http://www.openldap.org下载它。 假设你的slapd.conf文件包含下面的设置：

database ldbm
suffix dc="mycompany",dc="com"
rootdn "cn=Manager,dc=mycompany,dc=com"
rootpw secret

至于connectionURL，我们假设目录服务器和Tomcat一样在同一个机器上运行。 更多关于配置和使用JNDI LDAP provider的信息，请参看http://java.sun.com/products/jndi/docs.html 。

下一步，假设这个目录服务器具有下面这些元素(以LDIF格式):

# Define top-level entry
dn: dc=mycompany,dc=com
objectClass: dcObject
dc:mycompany

# Define an entry to contain people
# searches for users are based on this entry
dn: ou=people,dc=mycompany,dc=com
objectClass: organizationalUnit
ou: people

# Define a user entry for Janet Jones
dn: uid=jjones,ou=people,dc=mycompany,dc=com
objectClass: inetOrgPerson
uid: jjones
sn: jones
cn: janet jones
mail: j.jones@mycompany.com
userPassword: janet

# Define a user entry for Fred Bloggs
dn: uid=fbloggs,ou=people,dc=mycompany,dc=com
objectClass: inetOrgPerson
uid: fbloggs
sn: bloggs
cn: fred bloggs
mail: f.bloggs@mycompany.com
userPassword: fred

# Define an entry to contain LDAP groups
# searches for roles are based on this entry
dn: ou=groups,dc=mycompany,dc=com
objectClass: organizationalUnit
ou: groups

# Define an entry for the "tomcat" role
dn: cn=tomcat,ou=groups,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
cn: tomcat
uniqueMember: uid=jjones,ou=people,dc=mycompany,dc=com
uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com

# Define an entry for the "role1" role
dn: cn=role1,ou=groups,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
cn: role1
uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com

假设用户使用他们的uid (e.g. jjones)来登入应用程序，并且无名的连接足够用来搜索目录和取得 角色信息，如上面所描述配置的OpenLDAP目录服务器的Realm元素示例看起来象这样：

<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionURL="ldap://localhost:389"
userPattern="uid={0},ou=people,dc=mycompany,dc=com"
roleBase="ou=groups,dc=mycompany,dc=com"
roleName="cn"
roleSearch="(uniqueMember={0})"
/>

在这样的配置下，realm通过把用户名替代到userPattern里去来决定用户的特殊的 唯一名字，通过把这个特殊的唯一名字(DN)和用户提供的密码与目录绑定来认证，并搜索目录来发现用户的角色。

现在假设用户在登入时使用他们的email地址，而不是他们的userid。在这种情况下，realm必须搜索 目录来寻找用户的输入。(当用户输入被放在与不同的组织单位或公司位置相对应的多个subtrees里时， 搜索也是必要的)。

进一步，假设除了群体输入外，你想要使用关于用户输入的一个属性来保存角色信息。这里，关于Janet Jones的输入读起来象这样：

dn: uid=jjones,ou=people,dc=mycompany,dc=com
objectClass: inetOrgPerson
uid: jjones
sn: jones
cn: janet jones
mail: j.jones@mycompany.com
memberOf: role2
memberOf: role3
userPassword: janet

这个realm的配置应该满足这些新的要求：

<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionURL="ldap://localhost:389"
userBase="ou=people,dc=mycompany,dc=com"
userSearch="(mail={0})"
userRoleName="memberOf"
roleBase="ou=groups,dc=mycompany,dc=com"
roleName="cn"
roleSearch="(uniqueMember={0})"
/>

现在，当Janet Jones以"j.jones@mycompany.com"登录时，realm在目录里搜索具 有那个值作为它的mail属性的独特输入，并以所给的密码，及以下uid=jjones,ou=people,dc=mycompany,dc=com 与目录绑定。如果认证成功，她就被指派给三个角色："role2" and "role3"分别作为 她的目录输入里"memberOf"属性的值，"tomcat"作为唯一一个群体(她是其中 一个成员)输入"cn"属性的值。

最后，要想通过从目录中取得密码，并在realm里做局部比较来认证，你也许需要使用象这样的一个realm配置：

<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionName="cn=Manager,dc=mycompany,dc=com"
connectionPassword="secret"
connectionURL="ldap://localhost:389"
userPassword="userPassword"
userPattern="uid={0},ou=people,dc=mycompany,dc=com"
roleBase="ou=groups,dc=mycompany,dc=com"
roleName="cn"
roleSearch="(uniqueMember={0})"
/>

当然，正如上面所描述的，通常比较偏向使用默认的绑定模式来认证。

另外的注意事项

JNDIRealm根据下面的规则进行运作：

  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会调用这个Realm 的authenticate()方法。因此，你在目录里的任何更改(新用户，更改过的密码或角色， 等等)会立即被反映出来。
  • 一旦用户被认证过，这个用户(及其相关的角色)在这个用户登录期间被高速缓存(cached)在Tomcat 里。(对于基于-表格(FORM-based)的认证，这意味着直致会话时间结束或无效；对于BASIC认证，这 意味着用户关闭他们的浏览器)。被缓存的用户在会话系列之间不 被保存和再贮存。一个已经被认证过的用户的任何目录信息的更改，直到下次用户再登录时才会被反映出来。
  • 管理目录服务器里的信息是你的程序自身的责任。Tomcat不提供任何内在的功能来维持用户及角色信息。
MemoryRealm

简介

MemoryRealm是一个简单的Tomcat 5 Realm界面实现。它 不是为大量用户名称认证而设计的。在启动时，MemoryRealm从一个XML文件装载关于所有用户，以及他们相应的 角色的信息(在默认情况下，这个文件从$CATALINA_HOME/conf/tomcat-users.xml 被装载)。这个文件里的数据更改直到Tomcat被重新被启动后才会被识别。

Realm元素属性

为了配置一个 MemoryRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

用户文件格式

用户文件(默认文件conf/tomcat-users.xml必须是一个带有 根元素<tomcat-users>的XML文件。每个合法用户 的<user>元素嵌套在根元素里，包含有下列属性：

  • name(名称) - 这个用户必须用来登录的用户名。
  • password(密码)- 这个用户登录必须使用的密码(如果 在<Realm>元素上digest属性没有被设置，或者没有象 这里描述的那样正确地被digested)。
  • roles(角色) - 与这个用户相关的以逗号分隔开的角色名称列单。

例子

The default contents of the conf/tomcat-users.xml file is:

<tomcat-users>
<user name="tomcat" password="tomcat" roles="tomcat" />
<user name="role1" password="tomcat" roles="role1" />
<user name="both" password="tomcat" roles="tomcat,role1" />
</tomcat-users>

另外的注意事项

MemoryRealm根据下面的规则进行运作：

  • 当Tomcat第一次启动，它从用户文件装载了所有定义的用户以及他们的相关信息。直到Tomcat被 重新启动之前，这个文件里的数据的更改不会被识别出来。
  • 当一个用户第一次试图访问被保护的资源时，Tomcat 5会调用这个Realm 的authenticate()方法。
  • 一旦用户被认证过，这个用户(及其相关的角色)在这个用户登录期间被高速缓存(cached)在Tomcat 里。(对于基于-表格(FORM-based)的认证，这意味着直致会话时间结束或无效；对于BASIC认证，这意味 着用户关闭他们的浏览器)。被缓存的用户在会话系列之间不被保存和再贮存。
  • 管理目录服务器里的信息是你的程序自身的责任。Tomcat不提供任何内在的功能来维持用户及角色信息。
UserDatabaseRealm

简介

UserDatabaseRealm 是一个简单的Tomcat 5 Realm界面实现。所有用户和 他们的角色信息都来自于 JNDI 资源。这个 JNDI资源实现的是UserDatabase界面。

Realm元素属性

为了配置一个 UserDatabaseRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

缺省安装的Tomcat 5 配置的 UserDatabaseRealm 嵌套在<Engine>元素内， 所以它适用于所有虚拟主机和web应用。这个域（realm）使用与MemoryRealm相同的 tomcat-users.xml。

JAASRealm

简介

JAASRealm 是一个通过Java Authentication & Authorization Service (JAAS)框架认证用户的Tomcat 4 Realm 接口 的实现，而这个JAAS是一个Java软件包，它在Java 2 SDK 1.3里是作为选择性软件包被使用，在 SDK 1.4里它则完全整合在其中了。

使用JAASRealm给予开发人员这种能力，那就是把任何可想象的安全realm与 Tomcat 的CMA组合在一起。

JAASRealm是基于JAAS的J2EE 1.4版本的J2EE认证框架的原型(prototype)，它是在 JCP Specification Request 196 基础上来加强容器-管理的安全性，并促进不依赖于容器 的实现的'pluggable'认证机制。 JCP Specification Request 196

在JAAS登录模块和原则(参看javax.security.auth.spi.LoginModule 和javax.security.Principal)的基础上，你可以开发你自己的安全机制或者把第三方 的机制与Tomcat执行的CMA整合包裹在一起。

快 速 上 手

要设置好Tomcat来与你自己JAAS login模块一起使用JAASRealm，你必须遵守下面这些步骤：

  1. 在JAAS (参看the JAAS Authentication Tutorial 和 the JAAS Login Module Developer's Guide)基础上编写你自己的由JAAS Login Context (javax.security.auth.login.LoginContext) 管理的 LoginModule, User 和Role 类。在开发你的LoginModule时，注意JAASRealm自身具有的 CallbackHandler目前仅仅能识别NameCallback 和PasswordCallback。 the JAAS Authentication Tutorial the JAAS Login Module Developer's Guide
  2. 尽管JAAS里没有指明，但你还是应该通过扩展javax.security.Principal产生 不同的类来区分用户和角色，这样Tomcat可以从你的login module返回的Principals中区别 哪个是用户，哪个是角色（参看org.apache.catalina.realm.JAASRealm）。 不然的话，返回的第一个Principal总是被当作用户Principal。
  3. 把编译过的类放置在Tomcat的classpath上。
  4. 设置一个Java的login.config文件(参看JAAS LoginConfig file)，并对JVM指明 这个文件的位置告诉Tomcat到哪里去找到它。例如，可以把环境变量设置如下： JAVA_OPTS=-DJAVA_OPTS=-Djava.security.auth.login.config==$CATALINA_HOME/conf/jaas.config 。 JAAS LoginConfig file JAVA_OPTS=-DJAVA_OPTS=-Djava.security.auth.login.config==$CATALINA_HOME/conf/jaas.config
  5. 在你的web.xml文件里为你想要保护的资源配置安全-限制(security-constraints) 。
  6. 在你的server.xml文件里配置JAASRealm模块(module)。
  7. 如果Tomcat 5已经在运行，重新启动它。

Realm元素属性

为了配置一个 JAASRealm, 你必须如上面描述的那样在 $CATALINA_HOME/conf/server.xml文件里产生一个<Realm>元素 该元素支持的属性可在Realm 配置里面找到。

例子

你的server.xml文件看起来应该象这个例子这样。

<Realm className="org.apache.catalina.realm.JAASRealm"
appName="MyFooRealm"
userClassNames="org.foobar.realm.FooUser"
roleClassNames="org.foobar.realm.FooRole"
debug="99"/>

是你的login模块的责任来产生并保存代表用户的Principals的( javax.security.auth.Subject ) User和Role对象(objects)。如果你的login模块没有产生一个user object ，也没有抛出一个login异常， 那么Tomcat CMA 会终断，你会被停留在http://localhost:8080/myapp/j_security_check URI 或其他未指定的位置。

JAAS方法的可塑性有两层：

  • 你可以在你自己的login模块里实现任何你需要的程序处理。
  • 不用对你的应用程序编码有任何更改，你可以通过更改配置并重新启动服务器来插入(plug in)一个完全 不同的LoginModule。

另外的注意事项

  • 当一个用户第一次试图访问一个被保护的资源，Tomcat 5会调用这个Realm的 authenticate()方法。这样一来，你在这个安全机制里做的任何更改（新用户，更改密码 和角色，等等）会立即被反映出来。
  • 一旦用户被认证过，这个用户(及其相关的角色)在这个用户登录期间被零时缓存(cached)在Tomcat里。 对于基于-表格(FORM-based)的认证，这意味着直致会话时间结束或无效；对于BASIC认证，这意味着直到 用户关闭他们的浏览器。对于被认证过的用户，任何安全信息更改在这个用户再次登录之前都不 会被反映出来。
  • 和其他Realm实现一样，如果server.xml 里面的 <Realm>元素包含有一个digest属性，digested密码就被支持； JAASRealm 的 CallbackHandler在把密码传递回LoginModule 之前会先digest密码。


Apache Tomcat 5.5 Servlet/JSP 容器 - Tomcat的系统安全管理

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Tomcat的系统安全管理
背景知识

Java的SecurityManager允许浏览器在它可执行的范围内运行，这样可以 防止不可靠的程序读写用户在局部文件系统里的文件，或者未经授权进行网络连接，等等。同样， SecurityManager可用来防止不可靠的程序在你的浏览器上运行，在运行Tomcat时，使用 SecurityManager可以保护你的服务器不受到类似于木马的servlets, JSPs, JSP beans 和标签库（tag libraries）的影响，或者发生错误。

试想某个被允许在你的网站上发表JSPs的人不慎包括了以下的语句在他们的JSP里：

&lt;%System.exit(1);%&gt;

每次Tomcat运行该JSP都会导致Tomcat中断。使用Java SecurityManager 如同多了一层防护， 可以让服务器更加安全可靠。

警告——虽然Tomcat 5 的程序通过了安全检查，最重要的程序包都已被 保护，新的安全机制也已实施，但在允许用户发表网络程序，JSPs, servlets, beans, 或 标签库（tag libraries）之前，你还是有必要确保 SecurityManager 的各项配置符合你的要求。 当然，有SecurityManager绝对比没有它要安全的多。

许可 Permissions

Java的Permission类是用来定义Tomcat载入的类所拥有的权限。Java本身包括了一些 Permission类，你也可以在你的网络应用中加入你自己的Permission类。 这两种技术在Tomcat 5里都被应用。

标准许可

这里将简单总结标准系统中适用于Tomcat的SecurityManager 和 Permission 类。 更多信息请参看 http://java.sun.com/security/。

  • java.util.PropertyPermission - 控制读/写Java虚拟器的属性，如java.home 。
  • java.lang.RuntimePermission - 控制使用一些系统/运行时(System/Runtime)的功能，如exit() 和 exec()。它也控制包(package)的访问/定义。
  • java.io.FilePermission - 控制对文件和目录的读/写/执行操作。
  • java.net.SocketPermission - 控制使用网路sockets连接。
  • java.net.NetPermission - 控制使用multicast网路连接。
  • java.lang.reflect.ReflectPermission - 控制使用reflection来对类进行检视。
  • java.security.SecurityPermission - 控制对安全方法的访问。
  • java.security.AllPermission - 给予所有访问权限，就如你运行一个没有SecurityManager的Tomcat 。
Tomcat 中可修改的许可

Tomcat利用一个叫做org.apache.naming.JndiPermission 许可类。它用来控制以JNDI命名的文件资源的可读权限。该许可的名称是以JNDI来表达， 没有命令。在给予许可时，"*"的结尾可以用来以wild card方式映射JNDI命名 的文件资源。例如，你可以在你的政策(policy)文件加入以下一行：

permission org.apache.naming.JndiPermission "jndi://localhost/examples/*";

一个象这样的许可(Permission)会在部署网络程序时被自动产生，允许它读取它自己的静态资源， 但不允许它使用文件访问权来读取其它文件(除非你明确地给出访问那些文件的许可).

并且, Tomcat 总是自动产生以下文件许可:

permission java.io.FilePermission "** your application context**", "read";

这里**your application context**代表那个拥有你的应用程序的文件夹(或者是WAR文件)。

改变 Tomcat 中的 SecurityManager

政策文件的格式

由Java SecurityManager实现的安全政策被配置存放在 $CATALINA_HOME/conf/catalina.policy 文件里。这个文件完全替代了 JDK系统目录里的java.policy文件。这个catalina.policy 文件可以手动修改， 或者使用Java 1.2 及其后版本的 policytool 程序修改。

catalina.policy 文件中的条文使用了标准的java.policy 文件格式，如下：

// Example policy file entry

grant [signedBy &lt;signer&gt;,] [codeBase &lt;code source&gt;] {
permission &lt;class&gt; [&lt;name&gt; [, &lt;action list&gt;]];
};

其中signedBy 和 codeBase是选择项。 注释行是以"//"开始，直到该行结束。codeBase是URL的格式，文件的URL中可用如 ${java.home}和${catalina.home}等属性(这些属性会被扩展到由环境变量 JAVA_HOME 和 CATALINA_HOME为他们定义的目录路径)。

缺省政策文件

缺省$CATALINA_HOME/conf/catalina.policy 文件看起来象这样：

// ============================================================================
// catalina.corepolicy - Security Policy Permissions for Tomcat 5
//
// This file contains a default set of security policies to be enforced (by the
// JVM) when Catalina is executed with the "-security" option.  In addition
// to the permissions granted here, the following additional permissions are
// granted to the codebase specific to each web application:
//
// * Read access to the document root directory
//
// $Id: security-manager-howto.xml 301460 2003-01-15 03:40:45Z glenn $
// ============================================================================

// ========== SYSTEM CODE PERMISSIONS =========================================
// ========== 系统源码许可控制 ===============

// These permissions apply to javac
// 下面的许可适用于javac
grant codeBase "file:${java.home}/lib/-" {
        permission java.security.AllPermission;
};

// These permissions apply to all shared system extensions
// 下面的许可适用于java的扩展
grant codeBase "file:${java.home}/jre/lib/ext/-" {
        permission java.security.AllPermission;
};

// These permissions apply to javac when ${java.home] points at $JAVA_HOME/jre
// 下面的许可适用于当${java.home] 是 $JAVA_HOME/jre时的 javac
grant codeBase "file:${java.home}/../lib/-" {
        permission java.security.AllPermission;
};

// These permissions apply to all shared system extensions when
// 下面的许可适用于java的扩展
// ${java.home} points at $JAVA_HOME/jre
grant codeBase "file:${java.home}/lib/ext/-" {
        permission java.security.AllPermission;
};

// ========== CATALINA CODE PERMISSIONS =======================================
// ========== CATALINA的源码许可控制 =============

// These permissions apply to the launcher code
// 以下许可适用于启动Tomcat的程序
grant codeBase "file:${catalina.home}/bin/commons-launcher.jar" {
        permission java.security.AllPermission;
};

// These permissions apply to the server startup code
// 以下许可适用于启动服务器的程序
grant codeBase "file:${catalina.home}/bin/bootstrap.jar" {
        permission java.security.AllPermission;
};

// These permissions apply to the servlet API classes
// and those that are shared across all class loaders
// located in the "common" directory
// 以下许可适用于 Servlet 的 API 和 common目录里的程序
grant codeBase "file:${catalina.home}/common/-" {
        permission java.security.AllPermission;
};

// These permissions apply to the container's core code, plus any additional
// libraries installed in the "server" directory
// 下面的许可适用于Tomcat的核心和 server 目录里的程序
grant codeBase "file:${catalina.home}/server/-" {
        permission java.security.AllPermission;
};

// ========== WEB APPLICATION PERMISSIONS =====================================
// ========== WEB 应用的许可 ===========

// These permissions are granted by default to all web applications
// In addition, a web application will be given a read FilePermission
// and JndiPermission for all files and directories in its document root.
// 缺省情况下，所有WEB 应用拥有下面这些许可，另外还有 它们本身文件夹里的 “read” FilePermission
// 和JndiPermission。

grant {
        // Required for JNDI lookup of named JDBC DataSource's and
        // javamail named MimePart DataSource used to send mail
        permission java.util.PropertyPermission "java.home", "read";
        permission java.util.PropertyPermission "java.naming.*", "read";
        permission java.util.PropertyPermission "javax.sql.*", "read";

        // OS Specific properties to allow read access
    permission java.util.PropertyPermission "os.name", "read";
    permission java.util.PropertyPermission "os.version", "read";
    permission java.util.PropertyPermission "os.arch", "read";
    permission java.util.PropertyPermission "file.separator", "read";
    permission java.util.PropertyPermission "path.separator", "read";
    permission java.util.PropertyPermission "line.separator", "read";

        // JVM properties to allow read access
        permission java.util.PropertyPermission "java.version", "read";
        permission java.util.PropertyPermission "java.vendor", "read";
        permission java.util.PropertyPermission "java.vendor.url", "read";
        permission java.util.PropertyPermission "java.class.version", "read";
    permission java.util.PropertyPermission "java.specification.version", "read";
    permission java.util.PropertyPermission "java.specification.vendor", "read";
    permission java.util.PropertyPermission "java.specification.name", "read";

    permission java.util.PropertyPermission "java.vm.specification.version", "read";
    permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
    permission java.util.PropertyPermission "java.vm.specification.name", "read";
    permission java.util.PropertyPermission "java.vm.version", "read";
    permission java.util.PropertyPermission "java.vm.vendor", "read";
    permission java.util.PropertyPermission "java.vm.name", "read";

        // Required for getting BeanInfo
        permission java.lang.RuntimePermission "accessClassInPackage.sun.beans.*";

        // Required for OpenJMX
        permission java.lang.RuntimePermission "getAttribute";

    // Allow read of JAXP compliant XML parser debug
    permission java.util.PropertyPermission "jaxp.debug", "read";
};

// 你还可以给某个特定的WEB应用赋予其它许可。
// You can assign additional permissions to particular web applications by
// adding additional "grant" entries here, based on the code base for that
// application, /WEB-INF/classes/, or /WEB-INF/lib/ jar files.
//
// Different permissions can be granted to JSP pages, classes loaded from
// the /WEB-INF/classes/ directory, all jar files in the /WEB-INF/lib/
// directory, or even to individual jar files in the /WEB-INF/lib/ directory.
//
// For instance, assume that the standard "examples" application
// included a JDBC driver that needed to establish a network connection to the
// corresponding database and used the scrape taglib to get the weather from
// the NOAA web server.  You might create a "grant" entries like this:
//
// The permissions granted to the context root directory apply to JSP pages.
// grant codeBase "file:${catalina.home}/webapps/examples/-" {
//      permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect";
//      permission java.net.SocketPermission "*.noaa.gov:80", "connect";
// };
//
// The permissions granted to the context WEB-INF/classes directory
// grant codeBase "file:${catalina.home}/webapps/examples/WEB-INF/classes/-" {
// };
//
// The permission granted to your JDBC driver
// grant codeBase "jar:file:${catalina.home}/webapps/examples/WEB-INF/lib/driver.jar!/-" {
//      permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect";
// };
// The permission granted to the scrape taglib
// grant codeBase "jar:file:${catalina.home}/webapps/examples/WEB-INF/lib/scrape.jar!/-" {
//      permission java.net.SocketPermission "*.noaa.gov:80", "connect";
// };

启动附带SecurityManager的Tomcat

在你配置好与SecurityManager一起使用的catalina.policy文件之后， 你可以使用"-security"选项来启动Tomcat。

$CATALINA_HOME/bin/catalina.sh start -security (Unix)
%CATALINA_HOME%\bin\catalina start -security (Windows)
Configuring Package Protection in Tomcat

从Tomcat 5开始，现在可以配置Tomcat内部包的许可。更多信息请参阅 http://java.sun.com/security/seccodeguide.html 。

警告：删除缺省的包保护，可能打开一个安全漏洞。

缺省的属性文件

缺省的$CATALINA_HOME/conf/catalina.properties 文件看起来象这样：

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,org.apache.catalina.,org.apache.coyote.,org.apache.tomcat.,
org.apache.jasper.
#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageDefinition unless the
# corresponding RuntimePermission ("defineClassInPackage."+package) has
# been granted.
#
# by default, no packages are restricted for definition, and none of
# the class loaders supplied with the JDK call checkPackageDefinition.
#
package.definition=sun.,java.,org.apache.catalina.,org.apache.coyote.,
org.apache.tomcat.,org.apache.jasper.

当你完成配置SecurityManager所需的catalina.properties 文件，记住要重新启动Tomcat。

故障排除

如果你的网络应用程序试图执行没有许可而被阻止的操作，SecurityManager探查出这样的违规后， 就会抛出一个AccessControLException 或 SecurityException。 要查出究竟缺少哪个许可往往非常困难，一个方法是打印执行过程中的所有关于安全决定的排错信息。 这可以在启动Tomcat之前通过设置系统属性来实现。最简单的办法是修改CATALINA_OPTS 环境变量。在启动Tomcat之前，执行下面这个命令：

export CATALINA_OPTS=-Djava.security.debug=all (Unix)
set CATALINA_OPTS=-Djava.security.debug=all (Windows)

（在启动Tomcat之前）。

警告——这会产生很多megabytes的输出。不过，通过 查找"FAILED"这个词可以帮助你搜索问题所在，并确定哪个许可是要找的问题。 请参看Java安全文档资料，那里有你可指定的更多选项。


Apache Tomcat 5.5 Servlet/JSP 容器 - 安装 TOMCAT

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

安装 TOMCAT

介绍

这篇文档介绍了几种在不同的操作平台上运行Tomcat的安装方法。请注意，这里没包含一些高级 的设置问题：完整发布版 (ZIP 文件 or tarball)里有一个叫做RUNNING.txt的文件来讨论这些 问题。如果下面的信息不能回答你的某些问题的话，我们建议你再参考一下RUNNING.txt文件。

Windows下使用安装版安装

用Window安装版可以很简单地在Windows上安装Tomcat。 它的接口和功能与此其它安装程序相似，只需要几个有关的项目就行了。

  • 安装为系统服务：不管选什么样的设置，Tomcat都将被安装 成Windows NT/2K/XP 的系统服务。在组件那一页上，选中"auto" （“自动”） 运行，这样启动Windows时，Tomcat 就会自动启动。 从最佳安全性考虑，这种服务应该作为单独的用户来运行，它的操作权限也应被限制 (参看Windows服务管理工具以及帮助文档)。
  • Java路径：安装程式利用登记名册(registry)的信息，或者 JAVA_HOME 环境变量(variable)来决定J2SE 5 JRE的基础(base)路径(path)。
  • 任务栏图标: 当 Tomcat 作为服务运行时, 任务栏图标将不会出现。 如果你在安装的最后步骤选择运行 Tomcat，任务栏图标会同时出现一次。
  • 关于怎样把Tomcat作为Windows NT service进行管理的信息，请参考 Windows Service HOW-TO 。

安装程式会产生一个快捷方式允许启动和配置Tomcat。必须注意Tomcat管理web应用程序只有在 Tomcat运行时才能被使用。

如果使用J2SE 1.4 JRE，应该下载其相应的软件包并把它扩展在安装Tomcat所放置的文件夹里。

Unix daemon

应用commons-daemon项目里的jsvc工具可以很好地运行Tomcat。 Tomcat二进制(binaries) 里有jsvc的source tarballs, 需要被编译。 建立(building) jsvc需要用C ANSI编译器(如 GCC), GNU, Autoconf, and a JDK。

在运行脚本(script)之前， JAVA_HOME的环境变量要被设定在JDK的基础路径 (base path)里，或者在调用(calling) ./configure脚本时， 用--with-java 参数(parameter)来设定JDK的路径， 比如./configure --with-java=/usr/java。

应用下面的指令(command)可以产生一个编译过的jsvc二进制(文件)，这个文件放在 $CATALINA_HOME/bin文件夹。 这里假设使用了GNU TAR, 同时 $CATALINA_HOME环境变量(environment variable)被设定在Tomcat安装的基础 路径上。 $CATALINA_HOME/bin

请注意,你要用GNU make(g make),而不是用FreeBSD系统(system)本身的BSD make.

    cd $CATALINA_HOME/bin
    tar xvfz jsvc.tar.gz
    cd jsvc-src
    autoconf
    ./configure
    make
    cp jsvc ..
    cd ..

然后Tomcat就可以用下面的命令很好地运行:

    cd $CATALINA_HOME
    ./bin/jsvc -Djava.endorsed.dirs=./common/endorsed -cp ./bin/bootstrap.jar \
        -outfile ./logs/catalina.out -errfile ./logs/catalina.err \
        org.apache.catalina.startup.Bootstrap

javc还有其他的有用的参数，就象-user(用户)，在daemon初始化(initialization) 完成以后，使它转换到另一个用户。这样，既使没有特使权的用户来运行Tomcat，也可以使用特定 的端口(privileged port)。 jsvc --help 会提供全面的jsvc使用信息。 特别是-debug 选项在jsvc运行时对排错很有用。

文件$CATALINA_HOME/bin/jsvc/native/tomcat.sh 可被用作样板(template)，在 开机时从/etc/init.d 自动启动Tomcat。 这个文件目前被设置来运行 Tomcat 4.1x， 所以需要修订一下，把类名(classname) BootstrapService 改成Bootstrap。 $CATALINA_HOME/bin/jsvc/native/tomcat.sh

Commons-Daemon的JAR文件一定要在运行时的 classpath里面。如果你因为 Commons-Daemon 得到一个 ClassNotFoundException 或 NoClassDefFoundError， 请把 Commons-Daemon 的 JAR 用 -cp 选项加入到 classpath 里面，然后再启动 jsvc.


Apache Tomcat 5.5 Servlet/JSP 容器 - SSI How To

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

SSI How To
简介

SSI (Server Side Includes)是放置在HTML页面里的指令(directives)，在HTML页面被使用的 同时在服务器上被评估。这样可以让你把新产生的内容添加到现存的HTML页面上，而不需要同过CGI程序， 或其他动态的技术来产生整个页面。

当你使用Tomcat作为你的HTTP服务器，并要求有SSI支持，你可以把SSI支持添加到Tomcat里面。 通常在你不想要运行一个象Apache的web服务器的开发过程中它就被完成了。

Tomcat SSI 支持实施与Apache相同的指令。关于使用SSI指令的信息， 请参看 Apache Introduction to SSI 。

Tomcat里面SSI的支持是通过使用Servlet或过滤器来完成的。你必须选择其中一个来支持你的SSI， 而不能同时使用两个。

基于Servlet的SSI是通过实现 org.apache.catalina.ssi.SSIServlet来完成的。按照SSI的习惯，这个Servlet 然后被映射成以 "*.shtml" 结尾的 URL。

基于过滤器的 SSI 是通过实现 org.apache.catalina.ssi.SSIFilter来完成的。 按规矩, 这个过滤器过滤所有 以"*.shtml"结尾的 URL，你也可以用 "*" 映射，让它过滤所有URL，但它会根据 不同的文件种类 （mime types）来决定是否启用SSI。使用初始值 contentType 可以让你决定是否要用 SSI 来处理 JSP， Javascript 或其他内容的网页。

在缺省情况下设置是 Tomcat 不自动启用 SSI。

安装

警告——SSI指令可以用于执行Tomcat JVM外部的程序。如果你在使用 Java SecurityManager，它可以绕过你的catalina.policy里的安全政策配置。

把$CATALINA_BASE/server/lib/servlets-ssi.renametojar 改名为 $CATALINA_BASE/server/lib/servlets-ssi.jar 。

如果选择使用基于Servlet的SSI，请把$CATALINA_BASE/conf/web.xml里面被 注释掉的关于SSI 的 servlet 和 servlet-mapping 定义重新激活。

如果选择基于过滤器的 SSI， 清激活 $CATALINA_BASE/conf/web.xml 关于 SSI 的 filter 和 filter-mapping的设置。 .

Servlet 设置

有几个servlet起始参数可以用来配置SSI servlet的行为。

  • buffered - 这个servlet的输出是不是应该被缓冲？(0=false, 1=true) 默认是 0 (false).
  • debug - 由这个servlet日志的排错消息的详细程度。默认是0。
  • expires - 带有SSI指令的页面失效之前的秒数。默认行为是对于每一个请求都要评估所用的SSI指令。
  • isVirtualWebappRelative - “虚拟”SSI指令路径是否应该被解释为 相对于context root，而不是server root。 (0=false, 1=true) 默认是 0 (false)。
  • inputEncoding - 如果无法决定所调用资源的文字编码，SSI应该使用的编码。 缺省数值是系统的文字编码。
  • outputEncoding - 输出结果的文字编码，缺省值是 UTF-8。

过滤器设置

过滤器的性能可通过修改几个不同的初始值来调整。

  • contentType - 用一个正则表达式来就定那种网页类型应该调用 SSI。在 决定正则表达式时，不要忘记在网页内容种类的定义里可以有文字编码的选项， 它的标准是："mime/type; charset=set"，其中 charset=set 是选择项。 contentType的缺省值是："text/x-server-parsed-html(;.*)?".
  • debug - 由这个servlet日志的排错消息的详细程度。默认是0。
  • expires - 带有SSI指令的页面失效之前的秒数。默认行为是对于每一个请求都要评估所有的SSI指令。
  • isVirtualWebappRelative - “虚拟”SSI指令路径是不是应该被解释为相对于 context root相关，还是相对于server root (0=false, 1=true) 默认是 0 (false)。

Tomcat 允许 SSI 指令

SSI是通过 嵌入在 HTML的指令来完成的实现动态网页的。这些指令在HTML里面如同HTML的注释，在 运行Tomcat会把它替换为响应的内容。这些指令的标准格式是：

<!--#directive [parm=value] -->

有效指令有：

  • config - <!--#config timefmt="%B %Y" --> 用来指定SSI输出的时间日期或其他内容的格式
  • echo - <!--#echo var="VARIABLE_NAME" --> 替换所指定的数值
  • exec - 运行所在系统的命令
  • include - <!--#include virtual="file-name" --> 插入内容
  • flastmod - <!--#flastmod file="filename.shtml" --> 文件最后修改时间
  • fsize - <!--#fsize file="filename.shtml" --> 文件大小
  • printenv - <!--#printenv --> 打印所有环境变量
  • set - <!--#set var="foo" value="Bar" --> 用来为用户定义变量赋值
  • if elif endif else - 用于条件判断，例如：
    • <!--#config timefmt="%A" -->
    <!--#if expr="$DATE_LOCAL = /Monday/" -->
    <p>Meeting at 10:00 on Mondays</p>
    <!--#elif expr="$DATE_LOCAL = /Friday/" -->
    <p>Turn in your time card</p>
    <!--#else -->
    <p>Yoga class at noon.</p>
    <!--#endif -->

阅读更多SSI相关内容：

Apache SSI入门

Variables

SSI Servlet 现在支持下列变量：

变量名称 | 描述
AUTH_TYPE | 用来验证用户的方法，可以是：BASIC, FORM, 等
CONTENT_LENGTH | 从FORM传来的数据长度，单位是 bytes 或字符的个数
CONTENT_TYPE | MIME种类, 例如 "text/html"
DATE_GMT | 现在的国际标准时间 GMT
DATE_LOCAL | 当地时间
DOCUMENT_NAME | 调用的文件名
DOCUMENT_URI | 文件的虚拟路径
GATEWAY_INTERFACE | 服务器如果激活了 CGI 的话，显示支持的 CGI 版本，如 "CGI/1.1"
HTTP_ACCEPT | 所有允许的 MIME 种类
HTTP_ACCEPT_ENCODING | 列出所有客户端允许的压缩方式
HTTP_ACCEPT_LANGUAGE | 列出所有客户端接受的语言
HTTP_CONNECTION | 客户端接受的连接管理方法，如 "Close" or "Keep-Alive"
HTTP_HOST | 用户请求访问的网站
HTTP_REFERER | 连接到本网页的网页地址，用户来自于的网页网页
HTTP_USER_AGENT | 浏览器的名称
LAST_MODIFIED | 当前文件的最后修改时间
PATH_INFO | 传给服务器的路径信息
PATH_TRANSLATED | 经过转换的 PATH_INFO 路径
QUERY_STRING | 浏览器地址栏里 "?" 之后的值
QUERY_STRING_UNESCAPED | Undecoded query string with all shell metacharacters escaped with "\"
REMOTE_ADDR | 用户的IP地址
REMOTE_HOST | 用户的网址
REMOTE_PORT | 用户所用的端口号码
REMOTE_USER | 经确认的用户名字
REQUEST_METHOD | 用户请求访问所使用的方法，如 "GET", "POST" 等
REQUEST_URI | 用户所要求访问的网址
SCRIPT_FILENAME | 目前用户实际访问的网页在服务器上的文件名
SCRIPT_NAME | 网页的文件名
SERVER_ADDR | 服务器的IP地址
SERVER_NAME | 服务器电脑的名称或IP
SERVER_PORT | 服务器等待用户访问的端口
SERVER_PROTOCOL | 服务器使用的协议，如： "HTTP/1.1"
SERVER_SOFTWARE | 服务器所使用的软件名称和版本数
UNIQUE_ID | 服务器与用户目前如果开始会话的特有ID


Apache Tomcat 5.5 Servlet/JSP 容器 - 如何设置SSL

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

如何设置SSL
速成

文档说明：本文件适用于用JSSE设置Tomcat的SSL。 如果使用 APR, Tomcat是通过 OpenSSL来实现SSL，设置会不同。

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

你需要按照下列简单步骤在Tomcat 5上安装和配置SSL支持。更多信息，请阅读这个帮助的其余部分。

  1. 如果你在使用1.3 JVM，从http://java.sun.com/products/jsse/ 下载JSSE 1.0.3 (或其后的版本)， 然后，或者把它作为系统上installed extension，或者把它设置为一个环境变量 JSSE_HOME，让它指向你所安装JSSE的目录。

  2. 通过执行下面的命令产生一个认可的keystore。
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

    Unix

    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

    并指定一个密码值为"changeit"。

  3. 把$CATALINA_HOME/conf/server.xml中的 "SSL HTTP/1.1 Connector" 去掉注释，并根据需要修改。

SSL简介

SSL, 或者Secure Socket Layer，是一种允许web浏览器和web服务器通过一个安全的连接进行 交流的技术。这意味着将被发送的数据在一端被翻译成密码，传送出去，然后在另一端解开密码， 再进行处理。这是一个双向的过程，也就是浏览器和服务器都需要在发送数据之前对它们进行加密。

SSL协定的另一个重要方面是认证(Authentication)。这就是说，在你开始试图通过一个安全连接 与一个web服务器交流的时候，这个服务器会要求你的浏览器出示一组证件，通过“鉴定”的方式来证明这 就是你所声明的网站。在某些情况下，服务器还会要求你的web浏览器的认证书，证明你就是你所说的那 个人。这就是所知的“客户认证”，尽管实际情况中，更多地用在商务-对-商务(B2B)交易，而不是对个人 用户。大多数有SSL功能的web服务器不要求客户认证(Client Authentication)。

SSL 和 Tomcat

必须要注意，配置Tomcat来利用secure sockets仅仅在它作为一个独立的web服务器时才有必要。 当Tomcat主要作为在另外一个web服务器,如Apache 或Microsoft IIS, 后面的Servlet/JSP容器 运行时，通常有必要把主要的web服务器配置来处理与用户的SSL连接。通常，这个服务器会对所有的 SSL-相关的功能进行交涉，然后再把对Tomcat容器的请求解密后传递过去。同样，Tomcat会返回 明码的回应，这个回应将被加密后才被送到用户浏览器。在这样的环境下，Tomcat知道与主要web服务器 和客户的交流是通过一个安全连接才发生的(因为你的程序需要询问这些情况)，但是它本身并没有参与 加密和解密。

认证书：Certificate

为了能实施SSL，一个web服务器对每个接受安全连接的外部接口(IP 地址)必须要有相应的认 证书(Certificate)。关于这个设计的理论是一个服务器必须提供某种合理的保证以证明这个服务器的 主人就是你所认为的那个人，特别是在接收任何敏感信息之前要这样做。关于Certificates的更广泛 的解释超过了这个文档资料的范围，就把一个认证书当作一个英特网地址的“数码驾驶执照”。这个认证书 要陈述与这个网站相关联的公司，以及这个网站的所有者或系统管理员的一些基本联系信息。

这个"驾驶执照"由所有人以密码方式签字，其他人非常难伪造。对于进行电子商务 (e-commerce)的网站，或其他身份认证至关重要的任何商业交易，认证书要向大家所熟知的认证权威 (Certificate Authority (CA))如VeriSign或Thawte来购买。这样的认证书可用电子 技术证明属实——实际上，认证权威单位会担保它发出的认证书的真实性，如果你信任发出认证书的 认证权威单位的话，你就可以相信这个认证书是有效的。

在许多情况下，认证并不是真正使人担忧的事。系统管理员或许只想要保证被服务器传送和接收的 数据是秘密的，不会被连接线上的偷窃者盗窃到。庆幸的是，Java提供相对简单的被称 为keytool的命令行工具，可以简单地产生“自己签名”的认证书。自己签名的认证书 只是用户产生的认证书，没有正式在大家所熟知的认证权威那里注册过，因此不能确保它的真实性。 认证也许很重要，也许不重要，完全决定于你的需要。

使用SSL需要考虑的地方

用户第一次试图到你的网站访问被安全保卫的页面时,他(她)通常会被要求提供关于认证的 详细信息(如公司名称和联系姓名)，并询问他(她)是否愿意接受这个认证的合法性，并继续进行交易。 一些浏览器会提供一个选项来永久地接受所给的认证的合法性，这样一来用户就不用在每次访问你的网站 时麻烦地去填写认证信息。有的浏览器没有这一选项。一旦用户认可后，这个认证至少在整个浏览器 会话期间被认为是合法的。

虽然SSL协议的设计尽量做到既安全又高效，但是加密和解密是复杂耗时的计算过程。通常没有必要让整个 网站都通过SSL来传输，开发人员可以选择部分网页用SSL，部分网页不用SSL。对于一个相对繁忙的网站 来说，可以选择保护那些比较敏感的信息，如登陆、个人信息、购物车、付账、信用卡等。那些网页只要 把网页地址里http:改为https:，浏览器就会自动把信息按照指定的 协议传输出去。

最后,使用根据网名决定的虚拟主机来进行安全连接可能会出现问题。这是SSL协定本身的设计局限。 SSL handshake，就是客户浏览器接受服务器认证，在HTTP请求访问之前必须产生。因此，包含虚拟 主机名字的请求信息在认证之前不能被确定，所以不可能给单个IP地址分配多个认证书。如果在单个IP 地址上的所有的虚拟主机需要对照同一个认证书来认证的话，再添加多个虚拟主机不应该干扰服务器上 正常的SSL操作。不过要当心，大多数的客户浏览器会按认证书上列出的domain names(主要是官方的， CA-签署的认证书)对照比较服务器的domain name。如果领域名(domain names)不相配，这些浏览器 会向客户端用户显示警告。总的来说，只有address-based虚拟主机通常和SSL一起在生产环境中 被使用。

设置
检查你是否需要下载 JSSE

Java 1.4或更新的版本已经包括了JSSE。如果你使用 1.4或更新版本，你不需要另外下载JSSE。 你可以跳过本节

从下面的网站下载Java Secure Socket Extensions (JSSE) 版本 1.0.3或更新版。 http://java.sun.com/products/jsse/.

在扩展这个软件包后，有两种方法让Tomcat可以使用它(选择其中之一):

  • 通过把所有这三个JAR文件(jcert.jar , jnet.jar , 和 jsse.jar)复制到$JAVA_HOME/jre/lib/ext 目录中去，让JSSE成为 安装好的扩充目录。
  • 产生一个新的环境变量JSSE_HOME，让它包含绝对路径，指向你拆装(unpacked) JSSE二进制分布的目录。
产生 Keystore

Tomcat 现在只支持 JKS或PKCS12 格式的keystores. JKS格式是 Java 的标准 KeyStore格式，它可以用 Java 的 keytool 来产生。这个工具在 Java 的 bin 目录里。 PKCS12 格式时互联网的标准，可以用 OpenSSL 和微软的 Key-Manager来修改。

To import an existing certificate into a JKS keystore, please read the documentation (in your JDK documentation package) about keytool. Note that openssl often adds a readable comments before the key, keytooldoes not support that, so remove the openssl comments if they exist before importing the key using keytool.

使用OpenSSL把一个现存的被你自己CA签署的认证书输入到PKCS12 keystore里面，你会执行象这样的一个命令：

openssl pkcs12 -export -in mycert.crt -inkey mykey.key \
                        -out mycert.p12 -name tomcat -CAfile myCA.crt \
                        -caname root -chain
更深层的情况，请查阅OpenSSL documententation。

要从头开始产生一个新的keystore，包含一个自签的认证书，从一个终端命令行执行下面的命令：

视窗

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

Unix

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

( 应该把RSA运算法则作为主要安全运算法则，这保证了与其它服务器和组件的兼容性。)

这个命令会在用户的home directory产生一个叫做" .keystore " 的新文件。要指定一个不同的位置(location)或文件名，在上面所示的keytool 命令里添加-keystore参数，后面紧跟着你的keystore文件的全部路径名。你还需要把 这个新的位置在server.xml配置文件中反映出来，这在后面将有描述。例如：

视窗

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA \
-keystore \path\to\my\keystore

Unix

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA \
-keystore \path\to\my\keystore

在执行这个命令后，你首先被要求出示keystore密码。Tomcat使用的默认密码是 " changeit "(全都是小写字母)，如果你愿意，你可以指定你自己的 密码。你还需要在server.xml配置文件里指定自己的密码，这在以后会有描述。

下一步，你会被要求出示关于这个认证书的一般性信息，如公司，联系人名称，等等。这些信息会 显示给那些试图访问你程序里安全网页的用户，以确保这里提供的信息与他们期望的相对应。

最后，你会被要求出示密钥(key)密码，也就是这个认证书所特有的密码(与其它的 储存在同一个keystore文件里的认证书不同)。你必须在这里使用与keystore 密码相同的密码。(目前，keytool会提示你按ENTER键会自动帮你做这些)。

如果一切顺利，你现在就拥有了一个可以被你的服务器使用的有认证书的keystore文件。

注意： 你的 private key 的密码和 keystore 的密码应该相同。 如果不同的话你会得到一下错误信息： java.io.IOException: Cannot recover key 这是一个已知的错误，详细请看： Bugzilla issue 38217

Edit the Tomcat Configuration File

最后的步骤是把你的secure socket配置在$CATALINA_HOME/conf/server.xml文件里, $CATALINA_HOME代表你在其中安装Tomcat 5 的目录。一个例子是SSL连接器 的&lt;Connector&gt;元素被包括在和Tomcat一起安装的缺省server.xml文件里。 它看起来象是这样：

<-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<!--
<Connector
           port="8443" minProcessors="5" maxProcessors="75"
           enableLookups="true" disableUploadTimeout="true"
           acceptCount="100" debug="0" scheme="https" secure="true";
           clientAuth="false" sslProtocol="TLS"/>
-->

你会注意到Connector元素本身，其默认形式是被注释掉的(commented out)，所以你需要把它周围 的注释标志删除掉。然后，你可以根据需要客户化(自己设置)特定的属性。关于各种选项的详细信息， 请查阅Server Configuration Reference 。下面的讨论 仅仅涵盖设置SSL通信(communication)时大家最感兴趣的那些属性。

这个port属性(默认值是8443)是 TCP/IP端口数码，Tomcat在其上监听安全连接。 你可以把它更改成任何你愿意要的数值(如默认的https通信，数目是443)。不过，在许 多操作系统中，要想在比1024小的端口数码上运行Tomcat，需要特殊的设置(它超出了这个文档资料 的范围)。

如果你在这里更改端口数值，你还必须更改在non-SSL连接器上的redirectPort 这个属性特定的值。这允许Tomcat自动地redirect那些试图访问有安全限制页面的用户，指明根据 Servlet 2.4 Specification要求，SSL是必需的。

有一些额外的选项被用来配置SSL协定。依赖于你早先怎样配置你的keystore，你也许需要添加或更改下列属性值：

属性 | 描述
clientAuth | 如果你想要Tomcat要求所有的SSL客户在使用这个socket时出示用户认证书，把这个值设定为 true 。如果你想要Tomcat要求出示用户认证书，但是如果没有认证书也可以， 就把这个值设定为want 。
keystoreFile | 如果你产生的keystore文件不在Tomcat期望的默认地方(一个叫做.keystore 的文件在Tomcat运行的主目录)，就添加这个属性。你可以指定一个绝对路径名称， 或者一个由$CATALINA_BASE环境变量而派生的相对路径名称。
keystorePass | 如果你使用一个不同的keystore(以及认证书)密码，而不是Tomcat期望的密码 (就是changeit)，添加这个元素。
keystoreType | 如果使用一个PKCS12 keystore的话，就添加这个element。 有效的值是JKS 和 PKCS12 。
sslProtocol | 要在这个socket上被使用的加密／解密协定。如果你在使用Sun的JVM，我们不提倡更改 这个值。据报道，TLS协定的IBM's 1.4.1 实现与一些通用的浏览器不兼容。 如果是这样，就使用value SSL 。
ciphers | 这个socket允许使用的由逗号分隔开的加密密码列单。默认的情况下，任何可用的密码都允许被使用。
algorithm | 可用的X509算法。默认是Sun的实现( SunX509 )。 对于IBM JVMs，你应该使用值 IbmX509。对于其他卖主，查阅JVM文档资料来 找正确的值。
truststoreFile | 用来验证用户认证书的TrustStore文件。
truststorePass | 访问TrustStore的密码。默认值就是keystorePass的值。
truststoreType | 如果你在使用与KeyStore不同格式的TrustStore，添加这个元素。 合法的值是JKS和PKCS12。
keyAlias | 如果 keystore 里面有多个 key，你可以为用这个选项为加入的 key 起一个名字。 如果没有指定名字，使用时 keystore 内的第一个 key 将会被使用。

在完成这些配置更改后，你必须象通常那样重新启动Tomcat，然后你就可以工作了。 你应该可以通过SSL访问Tomcat支持的任何web应用程序。例如，试一下下面的指令：

https://localhost:8443

你应该看到通常的Tomcat splash页面(除非你修改过ROOT web应用程序)。如果不行的话， 下面的章节包含一些排除故障的提示。

安装和获取认证权威颁发的认证书

要从认证权威(如verisign.com, thawte.com 或 trustcenter.de)获得并安装认证书， 你应该先阅读前面章节，然后再按照下面的指示进行：

产生一个认证签名请求 (CSR)

为了从你选择的认证权威那里获得认证书，你必须产生一个所谓的认证签名请求(Certificate Signing Request (CSR))。这个认证签名请求被认证权威用来产生鉴定你的网站是“安全的”的认证书。 按照下列步骤产生一个CSR：

  • 产生一个局部认证书(如前面章节描述那样):
    keytool -genkey -alias tomcat -keyalg RSA \
   -keystore &lt;your_keystore_filename&gt;
    注意：在某些情况下， 要产生一个工作认证书，你必须在“"first- and lastname" field 键入你的网站的域名 (例如www.jaxmao.org)。
  • 然后用下列指令产生CSR ：
    keytool -certreq -keyalg RSA -alias tomcat
-file certreq.csr \
   -keystore &lt;your_keystore_filename&gt;

执行这个命令之后你会得到一个文件叫 certreq.csr。然后你可以到发送到认证权威， 然后你就可以得到你的认证书。具体步骤可以参考他们的网站的帮助文件。

导入认证书

现在你有了认证书，你可以把它输入到你局部的keystore里。首先你必须输入一个叫做证书链 Chain Certificate 或 Root Certificate 到你的 keystore 里去。在这之后，你可以开始 输入你的认证书。

  • 从你获得认证书的认证权威那里下载一个Chain Certificate 。
    For Verisign.com commercial certificates go to: http://www.verisign.com/support/install/intermediate.html
    For Verisign.com trial certificates go to: http://www.verisign.com/support/verisign-intermediate-ca/Trial_Secure_Server_Root/index.html For Trustcenter.de go to: http://www.trustcenter.de/certservices/cacerts/en/en.htm#server
    对于Thawte.com ， 去http://www.thawte.com/certs/trustmap.html下载
  • 把Chain Certificate 输入到你的keystore里边
    keytool -import -alias root -keystore &lt;your_keystore_filename&gt; \
   -trustcacerts -file &lt;filename_of_the_chain_certificate&gt;
  • 最后输入你的新的认证书
    keytool -import -alias tomcat -keystore &lt;your_keystore_filename&gt; \
   -trustcacerts -file &lt;your_certificate_filename&gt;
Troubleshooting

这里是一些你在设置SSL通信时也许会遇到的常见问题，以及如何解决它们。

  • 我在我的日志文件中得到"java.security.NoSuchAlgorithmException"错误。

    JVM找不到JSSE JAR 文件。按照所有的指导说明 下载并安装JSSE。

  • 当Tomcat启动时，我得到一个象 "java.io.FileNotFoundException: {some-directory}/{some-file} not found"的异常。

    一个可能的解释是Tomcat不能在它要找的地方找到 keystore文件。在默认的情况下， Tomcat预计 keystore文件在Tomcat运行的用户主目录里被命名为.keystore。 如果 keystore存放在别的什么地方，你需要向Tomcat配置文件里的 &lt;Factory&gt;元素添加一个 keystoreFile属性。

  • 当Tomcat启动时，我得到一个象"java.io.FileNotFoundException: Keystore was tampered with, or password was incorrect"的异常。

    如果没有其他人 试图 修改你的 keystore 文件，最可能的情况是 Tomcat 用了错误的密码。你可以尝试重新产生 keystore 文件，或修改 Tomcat 设置文件里 <Connector> 元素的 keystorePass 属性，还请记住密码是分大小写的。

如果你仍然有问题，一个好的地方你可找到帮助是 TOMCAT-USER 邮件列表。你可以 用下面的地址订阅。 http://tomcat.apache.org/lists.html.

Miscellaneous Tips and Bits

你可以用下面的办法获取用户 SSL session 的 ID：
String sslID = (String)request.getAttribute("javax.servlet.request.ssl_session");
你可从下面的网址获得更多这方面的信息： Bugzilla.


Apache Tomcat 5.5 Servlet/JSP 容器 - Project Status

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

Project Status
前言

本文的意图是为各位介绍Tomcat开发的现状，而没有提供有关某个臭虫是否已经被改正或 Tomcat是否支持某个功能。

This page is updated roughly once per every couple of Tomcat minor releases, so for day-to-day status you should check the tomcat-user and tomcat-dev mailing lists. You can always inquire there as to the availability or status of a specific feature or component.

Current Status Summary

Tomcat 5.0.27 在2004 年6月17日发表。 那时起 TOMCAT_5_0 在 CVS 里面开始分枝， Tomcat 5.5正是开始开发。 Tomcat 5.5 已经发表了几个稳定版。Tomcat 5.5是现在所有工作的 重点。Tomcat 5.0只是处于维护状态，它的修正版会发表的越来越少。

Tomcat 5.5 有几个主要目标。可以从下面的连接看到。 MARC. The status of some of these items is detailed below. Once 5.5 releases are available, please refer to the Changelog accompanying each release for detailed changes, enhancements, and fixes.

Tomcat 4.1.x is no longer actively developed. It is maintained to address only showstopper, security, and Servlet Specification compliance issues. Maintenance for Tomcat 4.1.x will likely cease once a stable release or two of Tomcat 5.5 are out. Users of Tomcat 4.1.x are strongly encouraged to upgrade to the latest stable Tomcat 5.0 release.

Tomcat 4.0.x is relatively old, and not actively maintained or supported. It is strongly recommended that users of these releases upgrade to the latest stable Tomcat 5.0 release or at least the latest stable Tomcat 4.1 release.

Tomcat 3.3.x is in roughly the same maintenance mode as Tomcat 4.1.x.

Tomcat 3.2 and earlier are in roughly the same support state as Tomcat 4.0.x. Users should upgrade to Tomcat 3.3.x or the latest stable Tomcat 5.0.x.

How to read the report

The columns in this report contain the following information:

  • Priority - A sense of how important it is to address this issue in the short term.
  • Action Item - Concise description of the action item to be completed. Where relevant, Java package names of the primary classes involved are listed in [square brackets]
  • Volunteers - Login of those developers who have volunteered to assist in the design, implementation, testing, and documentation of this action item's changes to Tomcat.
Developers can nominate themselves to work on particular action items by asking a Committer to add their name address to those items. The developers working on each item should discuss and agree upon the approach to be used for implementing the item's changes to the project source code and documentation, prior to completing those changes. Such discussions should take place on the tomcat-dev mailing list so that everyone can stay apprised of what is going on, or chime in if they want to contribute ideas and suggestions.

TODO List
Priority | Action Item | Volunteers
High | Refactor ClassLoaders for Tomcat 5.5 to allow container plugins. | costin
Medium | Enhance Cluster functionality for Tomcat 5.5. | fhanik
Medium | Continue fixing bugs and updating docs. | everyone
Open bugs

The list of the bugs which are in an unresolved state for Tomcat 5 can be seen here. Aspiring volunteers and others are strongly encouraged to attempt to comment and help resolve these issues.


Apache Tomcat 5.5 Servlet/JSP 容器 - 如何把Tomcat注册为视窗的服务

Apache Tomcat Servlet/JSP 容器

Apache Tomcat 5.5 Servlet/JSP 容器

如何把Tomcat注册为视窗的服务
NOTICE

本说明适用于procrun 1.0，现已淘汰。

Tomcat5应用程序

Tomcat5 是一个可以在视窗NT下注册为服务的程序。

Tomcat5w监视程序

Tomcat5w 是一个可用来监视和修改 Tomcat 设置的程序，它有方便使用的界面。

指令选项：

//ES// | 修改设置 | 这是却省是的选项。 运行命令的名称将以servicenameW.exe出现
//MS// | 监视程序运行状况 | 代表程序运行的小图标会出现在视窗有下角

指令行选项

指令行选项的格式为： //XX//ServiceName

现有指令行的选项：

//TS// | 把服务按控制台模式运行 | 不过没有提供其他选项，这是缺省运行模式。其中ServiceName时是可运行文件的名字去 掉exe后缀，这里是Tomcat5
//RS// | 运行为系统的服务 | 由系统ServiceManager来执行
//SS// | 停止服务
//US// | 更新属性
//IS// | 把Tomcat安装为系统的服务
//DS// | 删除Tomcat服务 | 如果Tomcat服务正在运行，这个指令首先终止Tomcat

指令行允许的属性

每个属性都以--开始。以++的属性会给附加在已有的属性里。 如果有系统环境变量的名称与指令的属性相同，有PR_前缀的优先。 例如：

set PR_CLASSPATH=xx.jar

与下面的指令项属性效果一样：

--Classpath=xx.jar

属性名称 | 默认值 | 描述
--Description | 描述Tomcat服务，最多1024个字符
--DisplayName | 名称 | 服务显示的名称
--Install | procrun.exe //RS//ServiceName | 安装服务
--Startup | manual | 启动服务的状态，可以是 auto 或 manual
--DependsOn | 罗列Tomcat服务必须依赖的其他系统服务。如果有多个服务，用# 或 ;符号来分开
--Environment | 罗列需要提供给该服务的环境变量。格式为： key=value. 用 # 或 ; 符号来区分
--User | 用来运行该指令的用户名。只是用在 StartMode 下的 java 或 exe，这样可以使Tomcat服务以没有 LogonAsService 特权的用户的名义来运行。
--Password | --User 所列用户的密码
JAVA_HOME | JAVA_HOME | 可以定义一个不同于系统的JAVA_HOME环境变量，指定使用不同的Java
--Jvm | auto | 允许的值为auto或jvm.dll的完整路径。 路径中可以有环境变量出现。
--JvmOptions | -Xrs | Java虚拟机器的选项。都用-D or -X开始， 将会被传递给JVM。 选项间用 # or ;字符隔开。
--Classpath | 设置Java的classpath环境变量
--JvmMs | 指定开始时所用的内存，单位是MB
--JvmMx | 最大内存，单位用MB
--JvmSs | Thread stack size in KB
--StartImage | 可运行文件
--StartPath | 程序运行时的工作目录
--StartClass | 程序开始时执行的类
--StartParams | 需要传递个程序的变量数值，变量用#或 ;字符分隔
--StartMethod | main | 如果开始执行类中的方法名称，可以不是 main()
--StartMode | 可运行文件 exe | 可以是jvm java 或 exe
--StopImage | 收到终止信号后运行的文件名
--StopPath | 收到终止信号后运行文件的工作目录
--StopClass | 收到终止信号后运行的Java类
--StopParams | 需要传递个终止信号后运行文件的变量数值。变量用# 或 ; 字符分开
--StopMethod | main | 收到终止信号后运行的Java类中的开始方法，可以不是main()
--StopMode | 运行文件 | 可以是jvm java 或exe；中的一个
--StopTimeout | 没有限制 | 定义 procrun 需要等待多少秒让程序安全退出。
--LogPath | 工作目录 | 定义日志所在目录
--LogPrefix | jakarta_service | 定义日志文件名称
--LogLevel | info | 定义日志写入的底限，可以是 error, info, warn 或 debug
--StdOutput | 把标准输出导入到文件的文件名
--StdError | 把错误输出stderr导入到文件的文件名

安装服务

最方便安全的办法是用 Tomcat 提供的service.bat脚本文件。

安装名为'Tomcat5'的服务
C:\> service.bat install

如果你使用 tomcat5.exe，你需要用//IS//选项

安装名为'Tomcat5'的服务
C:\> tomcat5 //IS//Tomcat5 --DisplayName="Apache Tomcat 5" \
C:\> --Install="C:\Program Files\Tomcat\bin\tomcat5.exe" --Jvm=auto \
C:\> --StartMode=jvm --StopMode=jvm \
C:\> --StartClass=org.apache.catalina.startup.Bootstrap --StartParams=start \
C:\> --StopClass=org.apache.catalina.startup.Bootstrap --StopParams=stop

更新服务

更新服务的变量，用 //US// 选项

更新服务'Tomcat5
C:\> tomcat5 //US//Tomcat5 --Description="Apache Tomcat Server - http://tomcat.apache.org/ " \
C:\> --Startup=auto --Classpath=%JAVA_HOME%\lib\tools.jar;%CATALINA_HOME%\bin\bootstrap.jar

删除服务

如果你要删除服务，用 //DS// 变量。
如果该服务正在运行，它先会被终止运行，然后删除。

删除名为'Tomcat5'的服务
C:\> tomcat5 //DS//Tomcat5

纠错

如果需要让服务在控制台运行，用 //TS// 选项。 该服务可用 CTRL+C 或 CTRL+BREAK终止。 如果你把 tomcat5.exe 重新命名为 testservice.exe， 那么你只要运行 testservice.exe， 控制模式是缺省的模式。

用控制台模式运行 'Tomcat5'
C:\> tomcat5 //TS//Tomcat5 [更多变量]
或简单运行:
C:\> tomcat5