原文:http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html

Introduction(介绍)

Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.xml file to reference/define resources.

[Tomcat为在其中运行的每个web应用都提供了一个JNDI InitialContext实现实例,这些实例与Java Enterprise Edition应用服务器所提供的实例相兼容。Java EE在/WEB-INF/web.xml文件中提供了一系列标准元素来引用或者定义资源。]

See the following Specifications for more information about programming APIs for JNDI, and for the features supported by Java Enterprise Edition (Java EE) servers, which Tomcat emulates for the services that it provides:

[参考下面的手册来获取更多关于JNDI的编程API信息,以及Java EE所支持的特性:]

Java Naming and Directory Interface (included in JDK 1.4 onwards)

Java EE Platform Specification (in particular, see Chapter 5 on Naming)

web.xml configuration(web.xml配置)

The following elements may be used in the web application deployment descriptor (/WEB-INF/web.xml) of your web application to define resources:

[在web应用的/WEB-INF/web.xml文件中定义资源时,可能会使用到如下元素:]

<env-entry> - Environment entry, a single-value parameter that can be used to configure how the application will operate.

<resource-ref> - Resource reference, which is typically to an object factory for resources such as a JDBC DataSource, a JavaMail Session, or custom object factories configured into Tomcat.

<resource-env-ref> - Resource environment reference, a new variation of resource-ref added in Servlet 2.4 that is simpler to configure for resources that do not require authentication information.

[<env-entry> - 环境条目,是一个单值参数,可以被用来配置应用如何操作。

<resource-ref> - 资源引用,典型的是对对象工厂资源的引用,比如对一个JDBC数据源的引用,对一个JavaMail Session的引用,或者对配置在Tomcat中的用户自定义工厂的引用。

<resource-env-ref> - 资源环境引用,是在Servlet2.4中新增的一个新的resource-ref变量,用来配置不需要验证信息的资源。]

Providing that Tomcat is able to identify an appropriate resource factory to use to create the resource and that no further configuration information is required, Tomcat will use the information in /WEB-INF/web.xml to create the resource.

[Tomcat会使用/WEB-INF/web.xml文件中的信息,利用合适的资源工厂来创建资源,而且不需要多余的配置信息。]

Tomcat provides a number of Tomcat specific options for JNDI resources that cannot be specified in web.xml. These include closeMethod that enables faster cleaning-up of JNDI resources when a web application stops and singleton that controls whether or not a new instance of the resource is created for every JNDI lookup. To use these configuration options the resource must be specified in a web application's <Context> element or in the <GlobalNamingResources> element of $CATALINA_BASE/conf/server.xml.

[Tomcat为JNDI资源提供了很多不能在web.xml中指定的选项,比如当web应用停止时,使得JNDI资源可以快速被清理的closeMethod选项,以及当JNDI查找资源时,是否会返回一个新的资源实例的singleton选项。要使用这些配置选项,必须在web应用的<Context>元素中,或者在server.xml文件的<GlobalNamingResources>元素中指定相应的资源。]

context.xml configuration(context.xml配置)

If Tomcat is unable to identify the appropriate resource factory and/or additional configuration information is required, additional Tomcat specific configuration must be specified before Tomcat can create the resource. Tomcat specific resource configuration is entered in the <Context> elements that can be specified in either $CATALINA_BASE/conf/server.xml or, preferably, the per-web-application context XML file (META-INF/context.xml).

[如果tomcat不能识别出合适的资源工厂,或者需要额外的配置信息,则在创建资源之前,需要指定额外的tomcat特定配置。这些特定配置信息放在<Context>元素中,或者servler.xml文件中,或者更好的做法是放在/META-INF/context.xml文件中。]

Tomcat specific resource configuration is performed using the following elements in the <Context> element:

[tomcat特定资源配置使用<Context>元素中的如下元素执行:]

<Environment> - Configure names and values for scalar environment entries that will be exposed to the web application through the JNDI InitialContext (equivalent to the inclusion of an <env-entry> element in the web application deployment descriptor).

<Resource> - Configure the name and data type of a resource made available to the application (equivalent to the inclusion of a <resource-ref> element in the web application deployment descriptor).

<ResourceLink> - Add a link to a resource defined in the global JNDI context. Use resource links to give a web application access to a resource defined in the <GlobalNamingResources> child element of the <Server> element.

<Transaction> - Add a resource factory for instantiating the UserTransaction object instance that is available at java:comp/UserTransaction.

[<Environment> - 配置环境条目的名称和值,web应用可以通过JNDI InitialContext查找到该名称和值(相当于web.xml中配置的<env-entry>元素。

<Resource> - 配置应用可以使用的资源的名称和数据类型(相当于web.xml中配置的<resource-ref>元素。

<ResourceLink> - 在全局JNDI context中添加一个资源定义连接,使用资源链接可以让web应用得到在<Server>元素下的子元素<GlobalNamingResources>中的资源定义。

<Transaction> - 添加一个用于实例化UserTransaction对象的资源工厂,该UserTransaction对象可以通过java:comp/UserTransaction得到。]

Any number of these elements may be nested inside a <Context> element and will be associated only with that particular web application.

[<Context>元素中可以嵌套任意多个以上的元素,并且这些元素只与该web应用关联。]

If a resource has been defined in a <Context> element it is not necessary for that resource to be defined in /WEB-INF/web.xml. However, it is recommended to keep the entry in /WEB-INF/web.xml to document the resource requirements for the web application.

[如果在<Context>元素中定义了资源,则不需要在/WEB-INF/web.xml中再次定义该资源。但是,推荐在web.xml文件中记录该web应用要用到的资源。]

Where the same resource name has been defined for a <env-entry> element included in the web application deployment descriptor (/WEB-INF/web.xml) and in an <Environment> element as part of the <Context> element for the web application, the values in the deployment descriptor will take precedence only if allowed by the corresponding <Environment> element (by setting the override attribute to "true").

[当在web.xml定义了<env-entry>元素,又在<Context>元素中嵌套了<Environment>元素,则当且仅当<Environment>元素的override属性为true时,才会优先考虑web.xml文件中的元素。]

Global configuration(全局配置)

Tomcat maintains a separate namespace of global resources for the entire server. These are configured in the <GlobalNamingResources> element of $CATALINA_BASE/conf/server.xml. You may expose these resources to web applications by using a <ResourceLink> to include it in the per-web-application context.

[tomcat为整个服务器维护了一个单独的全局资源命名空间,这些资源配置在server.xml文件的<GlobalNamingResources>元素中,可以通过在/META-INF/context.xml文件中使用<ResourceLink>来获取这些资源。]

If a resource has been defined using a <ResourceLink>, it is not necessary for that resource to be defined in /WEB-INF/web.xml. However, it is recommended to keep the entry in /WEB-INF/web.xml to document the resource requirements for the web application.

[如果已经使用<ResourceLink>定义了一个资源,则不需要在web.xml文件中再次定义。但是,推荐在web.xml中记录该web应用所需的资源。]

Using resources(使用资源)

The InitialContext is configured as a web application is initially deployed, and is made available to web application components (for read-only access). All configured entries and resources are placed in the java:comp/env portion of the JNDI namespace, so a typical access to a resource - in this case, to a JDBC DataSource - would look something like this:

[InitialContext被配置为一个web应用,它会被初始化部署到tomcat服务器中,并且可以被web应用组件获取到(以只读的形式)。所有已配置的条目和资源都被放在JNDI命名空间的java:comp/env中,因此,在这种情况下,获取一个资源(比如JDBC数据源)的典型方法如下:]

Tomcat Standard Resource Factories(Tomcat标准资源工厂)

Tomcat includes a series of standard resource factories that can provide services to your web applications, but give you configuration flexibility (via the <Context> element) without modifying the web application or the deployment descriptor. Each subsection below details the configuration and usage of the standard resource factories.

[Tomcat包含了一系列的标准资源工厂,它们可以为你的web应用提供服务,同时不会修改你的web应用以及web.xml文件。下面的每一个子部分都详细的说明了标准资源工厂的配置和使用。]

See Adding Custom Resource Factories for information about how to create, install, configure, and use your own custom resource factory classes with Tomcat.

[参考Adding Custom Resource Factories获取更多关于如何在tomat中创建、安装、配置、和使用自定义的资源工厂类的信息。]

NOTE - Of the standard resource factories, only the "JDBC Data Source" and "User Transaction" factories are mandated to be available on other platforms, and then they are required only if the platform implements the Java Enterprise Edition (Java EE) specs. All other standard resource factories, plus custom resource factories that you write yourself, are specific to Tomcat and cannot be assumed to be available on other containers.

[注意,在标准资源工厂中,只有JDBC数据源和User Transaction工厂被授权可以在其他平台上使用,其他的标准资源工厂,以及用户自定义工厂,都只能在tomcat中使用,而不能在其他容器中使用。]

Generic JavaBean Resources(通用JavaBean资源)

0. Introduction(介绍)

This resource factory can be used to create objects of any Java class that conforms to standard JavaBeans naming conventions (i.e. it has a zero-arguments constructor, and has property setters that conform to the setFoo() naming pattern. The resource factory will only create a new instance of the appropriate bean class every time a lookup() for this entry is made if the singleton attribute of the factory is set to false.

[该资源工厂可以备用来创建任何符合标准JavaBeans命名规范的Java类对象(比如有一个无参的构造函数,有set方法)。如果singleton属性设为false,则每次调用lookup()查找这个条目时,该资源工厂都会创建一个新的合适的javabean实例。]

The steps required to use this facility are described below.

[使用该工具的步骤描述如下。]

1. Create Your JavaBean Class(创建你的JavaBean类)

Create the JavaBean class which will be instantiated each time that the resource factory is looked up. For this example, assume you create a class com.mycompany.MyBean, which looks like this:

[创建JavaBean类。资源工厂每次查找时都会生成该类的一个实例,比如,假设你创建了一个名为com.mycompany.MyBean的类,如下:]

2. Declare Your Resource Requirements(声明你的资源需求)

Next, modify your web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will request new instances of this bean. The simplest approach is to use a <resource-env-ref> element, like this:

[接下来,修改web.xml文件来声明JNDI名称,将来你会根据该名称请求这个bean的实例。最简单的做法是使用一个<resource-env-ref>元素,如下:]

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

[警告,确保你遵守了web.xml中的DTD,参考Servlet Specification获取详细信息。]

3. Code Your Application's Use Of This Resource(使用该资源)

A typical use of this resource environment reference might look like this:

[资源环境引用的典型使用方式如下:]

4. Configure Tomcat's Resource Factory(配置tomcat的资源工厂)

To configure Tomcat's resource factory, add an element like this to the <Context> element for this web application.

[可以在web应用的<Context>元素中添加如下代码来配置tomcat的资源工厂。]

Note that the resource name (here, bean/MyBeanFactory must match the value specified in the web application deployment descriptor. We are also initializing the value of the bar property, which will cause setBar(23) to be called before the new bean is returned. Because we are not initializing the foo property (although we could have), the bean will contain whatever default value is set up by its constructor.

[注意,资源名(这里是bean/MyBeanFactory)必须与web.xml文件中的相同。我们也可以初始化bar属性的值,这会在新bean返回之前调用setBar(23)方法设置bar属性的值。因为我们没有初始化foo属性(尽管可以这么做),所以bean中的foo属性的值保持为缺省值。]

Some beans have properties with types that can not automatically be converted from a string value. Setting such properties using the Tomcat BeanFactory will fail with a NamingException. In cases were those beans provide methods to set the properties from a string value, the Tomcat BeanFactory can be configured to use these methods. The configuration is done with the forceString attribute.

[有些bean的属性的类型不能通过string自动转换过来,用Tomcat的BeanFactory设置这种属性会抛出一个NamingException异常。在这种情况下,这些bean应该提供一个方法来用string值设置属性,Tomcat BeanFactory可以配置forceString属性来使用这些方法。]

Assume our bean looks like this:

[假设我们的bean如下:]

The bean has two properties, both are of type InetAddress. The first property local has an additional setter taking a string argument. By default the Tomcat BeanFactory would try to use the automatically detected setter with the same argument type as the property type and then throw a NamingException, because it is not prepared to convert the given string attribute value to InetAddress. We can tell the Tomcat BeanFactory to use the other setter like that:

[这个bean有两个属性,类型都是InetAddress。第一个属性local有一个额外的setter,形参是string类型。默认情况下,Tomcat BeanFactory会尝试使用参数类型与属性类型相同的setter,因为此时BeanFactory不能将给定的String属性值转换为IntetAddress,与会抛出NamingException异常。我们可以告诉BeanFactory使用另一个setter,如下:]

The bean property remote can also be set from a string, but one has to use the non-standard method name host. To set local and remote use the following configuration:

[bean属性remote也可以通过一个字符串进行设置,但必须使用非标准方法来命名host。可以通过如下配置设置local和remote:]

Multiple property descriptions can be combined in forceString by concatenation with comma as a separator. Each property description consists of either only the property name in which case the BeanFactory calls the setter method. Or it consist of name=method in which case the property named name is set by calling method method. For properties of types String or of primitive type or of their associated primitive wrapper classes using forceString is not needed. The correct setter will be automatically detected and argument conversion will be applied.

[forceString中可以描述多个属性,属性间用逗号分隔。每个属性的描述要么只包含属性名,在这种情况下,BeanFactory会调用setter方法;要么包含name=method,在这种情况下,BeanFactory会调用method方法来设置名为name的属性。属性的类型如果为String、基本数据类型、或者基本数据类型的包装类,则不需要使用forceString,此时,BeanFactory会自动选择正确的setter,并且提供相应的参数转换。]

UserDatabase Resources(用户数据库资源)

0. Introduction(介绍)

UserDatabase resources are typically configured as global resources for use by a UserDatabase realm. Tomcat includes a UserDatabaseFactory that creates UserDatabase resources backed by an XML file - usually tomcat-users.xml

[用户数据库资源的典型应用是作为全局资源进行配置,并被一个UserDatabase realm使用。Tomcat中包含一个创建用户数据库资源的UserDatabaseFacotry,其内部使用的是一个xml文件(通常是tomcat-user.xml)。]

The steps required to set up a global UserDatabase resource are described below.

[创建一个全局的用户数据库资源步骤如下。]

1. Create/edit the XML file(创建或编辑一个xml文件)

The XML file is typically located at $CATALINA_BASE/conf/tomcat-users.xml however, you are free to locate the file anywhere on the file system. It is recommended that the XML files are placed in $CATALINA_BASE/conf. A typical XML would look like:

[典型的xml文件放置在conf/tomcat-user.xml中,你也可以把该文件放在文件系统的任何位置,但推荐放在conf目录下。一个典型的xml文件如下:]

2. Declare Your Resource(声明你的资源)

Next, modify $CATALINA_BASE/conf/server.xml to create the UserDatabase resource based on your XML file. It should look something like this:

[接下来,修改conf/server.xml文件根据你的xml文件来创建用户数据库资源。如下:]

The pathname attribute can be absolute or relative. If relative, it is relative to $CATALINA_BASE.

[pathname属性可以是绝对的,也可以是相对与$CATALINA_BASE的路径。]

The readonly attribute is optional and defaults to true if not supplied. If the XML is writeable then it will be written to when Tomcat starts. WARNING: When the file is written it will inherit the default file permissions for the user Tomcat is running as. Ensure that these are appropriate to maintain the security of your installation.

[readonly属性是可选的,缺省值true。如果该xml文件是可写的,则在tomcat启动时会写入该xml文件。]

3. Configure the Realm(配置Realm)

Configure a UserDatabase Realm to use this resource as described in the Realm configuration documentation.

[参考Realm configuration documentation来配置UserDatabase Realm,从而使用该资源。]

JavaMail Sessions

0. Introduction(介绍)

In many web applications, sending electronic mail messages is a required part of the system's functionality. The Java Mail API makes this process relatively straightforward, but requires many configuration details that the client application must be aware of (including the name of the SMTP host to be used for message sending).

[在很多web应用中,发送电子邮件是系统功能的一个必须部分。Java Mail API使得这个过程相对简单直接,但它要求客户端程序注意很多配置细节(包括用来发送电子邮件的SMTP服务器的名字)。]

Tomcat includes a standard resource factory that will create javax.mail.Session session instances for you, already configured to connect to an SMTP server. In this way, the application is totally insulated from changes in the email server configuration environment - it simply asks for, and receives, a preconfigured session whenever needed.

[tomcat包含一个标准的资源工厂,可以用来创建javax.mail.Session实例对象,并且这个实例对象已经被配置可以连上一个SMTP服务器。这样,就降低了与邮件服务器配置环境之间的耦合度。]

The steps required for this are outlined below.

[配置步骤如下:]

1. Declare Your Resource Requirements(声明你的资源要求)

The first thing you should do is modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured sessions. By convention, all such names should resolve to the mail subcontext (relative to the standard java:comp/env naming context that is the root of all provided resource factories. A typical web.xml entry might look like this:

[你应该做的第一件事情是修改web.xml文件来声明你要查找的预配置session的JNDI名称。按惯例,所有这样的名称应该被解析成mail subcontext(相对于java:comp/env,这是标准的命名context,它是所有已提供的资源工厂的根命名context)。一个典型的web.xml条目如下:]

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

[警告,确保你遵守了web.xml中的DTD,参考Servlet Specification获取详细信息。]

2. Code Your Application's Use Of This Resource(使用该资源)

A typical use of this resource reference might look like this:

[该资源引用的一个典型用法如下:]

Note that the application uses the same resource reference name that was declared in the web application deployment descriptor. This is matched up against the resource factory that is configured in the <Context> element for the web application as described below.

[注意,应用使用的是在web.xml文件中定义的资源引用名,该名称必须与配置在<Context>元素中的资源工厂相对应。]

3. Configure Tomcat's Resource Factory(配置资源工厂)

To configure Tomcat's resource factory, add an elements like this to the <Context> element for this web application.

[在应用的<Context>元素中增加如下元素,即可以配置tomcat的资源工厂。]

Note that the resource name (here, mail/Session) must match the value specified in the web application deployment descriptor. Customize the value of the mail.smtp.host parameter to point at the server that provides SMTP service for your network.

[注意,资源名称(这里是mail/Session)必须与在web.xml中定义的名称相同。自定义mail.smtp.host参数的值来指明提供SMTP服务的服务器。]

Additional resource attributes and values will be converted to properties and values and passed to javax.mail.Session.getInstance(java.util.Properties) as part of the java.util.Properties collection. In addition to the properties defined in Annex A of the JavaMail specification, individual providers may also support additional properties.

[额外的资源属性和值会被转换为javax.mail.Session.getInstance(java.util.Properties)中的java.util.Properties的属性。除了JavaMail specification的附录A中定义的属性外,单个的提供商可能会提供额外的属性。]

If the resource is configured with a password attribute and either a mail.smtp.user or mail.user attribute then Tomcat's resource factory will configure and add a javax.mail.Authenticator to the mail session.

[如果该资源配置了密码属性,比如mail.smtp.user或者mail.user属性,则tomcat的资源工厂会在mail session中增加一个javax.mail.Authenticator。]

4. Install the JavaMail libraries(安装JavaMail库)

Download the JavaMail API.

[下载JavaMail API。]

Unpackage the distribution and place mail.jar into $CATALINA_HOME/lib so that it is available to Tomcat during the initialization of the mail Session Resource. Note: placing this jar in both $CATALINA_HOME/lib and a web application's lib folder will cause an error, so ensure you have it in the $CATALINA_HOME/lib location only.

[将解压后的jar包放到$CATALINA_HOME/lib目录下,以便tomcat在初始化mail Session时使用。注意,同时将jar包放在$CATALINA_HOME/lib和web应用的lib目录下会导致错误,因此确保只在$CATALINA_HOME/lib下有该文件。]

5. Restart Tomcat(重启tomcat)

For the additional JAR to be visible to Tomcat, it is necessary for the Tomcat instance to be restarted.

[为了是附加的JAR对tomcat可见,有必要重启tomcat。]

WARNING - The default configuration assumes that there is an SMTP server listing on port 25 on localhost. If this is not the case, edit the <Context> element for this web application and modify the parameter value for the mail.smtp.host parameter to be the host name of an SMTP server on your network.

[警告,默认配置中假设SMTP服务器的端口是25,如果不是这样,请编辑该web应用的<Context>,并修改smtp.smtp.host参数的值。]

JDBC Data Sources(JDBC数据源)

0. Introduction(介绍)

Many web applications need to access a database via a JDBC driver, to support the functionality required by that application. The Java EE Platform Specification requires Java EE Application Servers to make available a DataSource implementation (that is, a connection pool for JDBC connections) for this purpose. Tomcat offers exactly the same support, so that database-based applications you develop on Tomcat using this service will run unchanged on any Java EE server.

[许多web应用都需要通过JDBC驱动来连接数据库,从而为所需的功能提供支持。Java EE Platform Specification要求Java EE应用服务器提供一个数据源实现(也就是一个JDBC连接池)。为了这个目的,tomcat提供了完全相同的支持,因此使用这种服务在tomcat中开发的基于数据库的应用可以在其他任何Java EE服务器中运行,而不需要做任何改变。]

For information about JDBC, you should consult the following:

[你可以通过以下内容了解JDBC       ]

http://www.oracle.com/technetwork/java/javase/jdbc/index.html - Home page for information about Java Database Connectivity.

http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html - The JDBC 2.1 API Specification.

http://java.sun.com/products/jdbc/jdbc20.stdext.pdf - The JDBC 2.0 Standard Extension API (including the javax.sql.DataSource API). This package is now known as the "JDBC Optional Package".

http://www.oracle.com/technetwork/java/javaee/overview/index.htm - The Java EE Platform Specification (covers the JDBC facilities that all Java EE platforms must provide to applications).

NOTE - The default data source support in Tomcat is based on the DBCP connection pool from the Commons project. However, it is possible to use any other connection pool that implements javax.sql.DataSource, by writing your own custom resource factory, as described below.

[注意,tomcat中默认提供的数据源是基于Commons项目中的DBCP连接池,但也可以使用任何其他实现了javax.sql.DataSource的连接池。]

1. Install Your JDBC Driver(安装JDBC驱动)

Use of the JDBC Data Sources JNDI Resource Factory requires that you make an appropriate JDBC driver available to both Tomcat internal classes and to your web application. This is most easily accomplished by installing the driver's JAR file(s) into the $CATALINA_HOME/lib directory, which makes the driver available both to the resource factory and to your application.

[只有在tomcat内部类和web应用中提供合适的JDBC驱动,才能使用JDBC数据源JNDI资源工厂。可以在$CATALINA_HOME/lib目录下安装驱动的JAR文件来实现这一点。]

2. Declare Your Resource Requirements(声明你的资源要求)

Next, modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured data source. By convention, all such names should resolve to the jdbc subcontext (relative to the standard java:comp/env naming context that is the root of all provided resource factories. A typical web.xml entry might look like this:

[接下来,修改web.xml文件来声明要查找的预配置数据源的JNDI名称。按惯例,所有的这些名称应该被解析为jdbc subcontext(相对于java:comp/env,即相对于java:comp/env,这是标准的命名context,它是所有已提供的资源工厂的根命名context) 。一个典型的web.xml条目如下:]

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

[警告,确保你遵守了web.xml中的DTD,参考Servlet Specification获取详细信息。]

3. Code Your Application's Use Of This Resource(使用该资源)

A typical use of this resource reference might look like this:

[该资源引用的一个典型用法如下:]

Note that the application uses the same resource reference name that was declared in the web application deployment descriptor. This is matched up against the resource factory that is configured in the <Context> element for the web application as described below.

[注意,应用使用的是在web.xml文件中定义的资源引用名,该名称必须与配置在<Context>元素中的资源工厂相对应。]

4. Configure Tomcat's Resource Factory(配置资源工厂)

To configure Tomcat's resource factory, add an elements like this to the <Context> element for this web application.

[在应用的<Context>元素中增加如下元素,即可以配置tomcat的资源工厂。]

Note that the resource name (here, jdbc/EmployeeDB) must match the value specified in the web application deployment descriptor.

[注意,资源名称(这里是jdbc / EmployeeDB)必须与在web.xml中定义的名称相同。]

This example assumes that you are using the HypersonicSQL database JDBC driver. Customize the driverClassName and driverNameparameters to match your actual database's JDBC driver and connection URL.

[例子中假设你使用的是HypersonicSQL数据库的JDBC驱动。driverClassName和driverName参数值是实际的数据库的JDBC驱动和连接URL。]

The configuration properties for Tomcat's standard data source resource factory (org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory) are as follows:

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

driverClassName - Fully qualified Java class name of the JDBC driver to be used.

username - Database username to be passed to our JDBC driver.

password - Database password to be passed to our JDBC driver.

url - Connection URL to be passed to our JDBC driver. (For backwards compatibility, the property driverName is also recognized.)

initialSize - The initial number of connections that will be created in the pool during pool initialization. Default: 0

maxActive - The maximum number of connections that can be allocated from this pool at the same time. Default: 8

minIdle - The minimum number of connections that will sit idle in this pool at the same time. Default: 0

maxIdle - The maximum number of connections that can sit idle in this pool at the same time. Default: 8

maxWait - The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception. Default: -1 (infinite)

[driverClassName - 要使用的JDBC驱动的java类全称

username - 连接数据库的用户名

password - 连接数据库的密码

url - 连接数据库的url(为了后向兼容,也可以写为driverName属性

initialSize - 连接池启动时创建的初始化连接数量

maxActive - 同一时刻可以从连接池中分配的最大连接数(高峰单机器在20并发左右,自己根据应用场景定)

minIdle - 同一时刻连接池中处于非活动状态的最小连接数

maxIdle - 同一时刻连接池中处于非活动状态的最大连接数(超过的空闲连接将被释放,如果设置为负数表示不限制,maxIdle不能设置太小,因为假如在高负载的情况下,连接的打开时间比关闭的时间快,会引起连接池中idle的个数上升超过maxIdle,而造成频繁的连接销毁和创建,类似于jvm参数中的Xmx设置)

maxWait - 当连接池中没有可用连接时,新的连接请求的等待时间(单位:毫秒),超时将抛出异常,缺省值为-1(表示无穷]

Some additional properties handle connection validation:

[一些处理连接验证的附加属性如下:]

validationQuery - SQL query that can be used by the pool to validate connections before they are returned to the application. If specified, this query MUST be an SQL SELECT statement that returns at least one row.

validationQueryTimeout - Timeout in seconds for the validation query to return. Default: -1 (infinite)

testOnBorrow - true or false: whether a connection should be validated using the validation query each time it is borrowed from the pool. Default: true

testOnReturn - true or false: whether a connection should be validated using the validation query each time it is returned to the pool. Default: false

[validationQuery - 一个SQL语句,用于在连接被返回给应用前的连接验证。如果指定该参数,则该查询必须是至少返回一行记录的SQL SELECT语句。

validationQueryTimeout - 返回validation query的超时时间(单位:秒),缺省值为-1(即无穷)

testOnBorrow - 取值为true或false。每次从连接池中取得连接时,是否使用validation query进行验证,缺省为true。

testOnReturn - 取值为true或false。每次将连接返回给连接池时,是否使用validation query进行验证,缺省为false。]

The optional evictor thread is responsible for shrinking the pool by removing any connections which are idle for a long time. The evictor does not respect minIdle. Note that you do not need to activate the evictor thread if you only want the pool to shrink according to the configured maxIdle property.

[可选的清除线程用来清除闲置过久的连接,从而减轻连接池的负担。清除线程不考虑minIdle设置。注意,如果仅仅想要根据maxIdle来减轻连接池的负担,则不需要激活清除线程。]

The evictor is disabled by default and can be configured using the following properties:

[默认情况下,清除线程不启动。可以用如下属性来配置清除线程:]

timeBetweenEvictionRunsMillis - The number of milliseconds between consecutive runs of the evictor. Default: -1 (disabled)

numTestsPerEvictionRun - The number of connections that will be checked for idleness by the evictor during each run of the evictor. Default: 3

minEvictableIdleTimeMillis - The idle time in milliseconds after which a connection can be removed from the pool by the evictor. Default: 30*60*1000 (30 minutes)

testWhileIdle - true or false: whether a connection should be validated by the evictor thread using the validation query while sitting idle in the pool. Default: false

[timeBetweenEvictionRunsMillis - 每timeBetweenEvictionRunsMillis毫秒检查一次连接池中是否有空闲连接,缺省值为-1(即不检查空闲连接)

numTestsPerEvictionRun - 每次检查连接的数量,缺省值为3

minEvictableIdleTimeMillis - 连接的空闲时间超过minEvictableIdleTimeMillis时,则该连接将被从连接池中移除。缺省值为30分钟

testWhileIdle - 取值为true或false。当连接空闲时是否使用validation query验证连接。]

Another optional feature is the removal of abandoned connections. A connection is called abandoned if the application does not return it to the pool for a long time. The pool can close such connections automatically and remove them from the pool. This is a workaround for applications leaking connections.

[还有一些附加特性是针对移除废弃连接的。当应用长时间不把一个连接返回给连接池时,该连接就被称为废弃连接。连接池会自动关闭这些连接并把它们从连接池冲移除,这是防止连接泄露的一种做法。]

The abandoning feature is disabled by default and can be configured using the following properties:

[默认情况下,废弃特性没有被启用。可以利用如下属性来配置:]

removeAbandoned - true or false: whether to remove abandoned connections from the pool. Default: false

removeAbandonedTimeout - The number of seconds after which a borrowed connection is assumed to be abandoned. Default: 300

logAbandoned - true or false: whether to log stack traces for application code which abandoned a statement or connection. This adds serious overhead. Default: false

[removeAbandoned - 取值为true或false。是否从连接池中移除废弃连接,缺省为false

removeAbandonedTimeout - 超过removeAbandonedTimeout秒后,从连接池得到的连接即被假定为废弃连接,缺省值为300秒

logAbandoned - 取值为true或false。废弃一个语句或连接时,是否打印程序的stack traces日志。该配置会严重增加开销,缺省值为false。]

Finally there are various properties that allow further fine tuning of the pool behaviour:

[最后,还有多种属性可以用来微调连接池的行为:]

defaultAutoCommit - true or false: default auto-commit state of the connections created by this pool. Default: true

defaultReadOnly - true or false: default read-only state of the connections created by this pool. Default: false

defaultTransactionIsolation - This sets the default transaction isolation level. Can be one of NONE, READ_COMMITTED, READ_UNCOMMITTED, REPEATABLE_READ, SERIALIZABLE. Default: no default set

poolPreparedStatements - true or false: whether to pool PreparedStatements and CallableStatements. Default: false

maxOpenPreparedStatements - The maximum number of open statements that can be allocated from the statement pool at the same time. Default: -1 (unlimited)

defaultCatalog - The name of the default catalog. Default: not set

connectionInitSqls - A list of SQL statements run once after a Connection is created. Separate multiple statements by semicolons (;). Default: no statement

connectionProperties - A list of driver specific properties passed to the driver for creating connections. Each property is given as name=value, multiple properties are separated by semicolons (;). Default: no properties

accessToUnderlyingConnectionAllowed - true or false: whether accessing the underlying connections is allowed. Default: false

[defaultAutoCommit - 取值为true或false。设置从连接池得到的连接默认是否自动提交语句,缺省值为true

defaultReadOnly - 取值为true或false。设置冬连接池得到的连接默认是否为只读,缺省值为fasle

defaultTransactionIsolation - 设置默认的事务隔离级,取值为NONE、READ_COMMITED、READ_UNCOMMITED、REPEATABLE_READ、SERIALIZABLE,没有缺省值

poolPreparedStatements - 取值为true或false。设置是否缓存PreparedStatements和CallableStatements,缺省值为false

maxOpenPreparedStatements - 设置statement池在同一时刻可以打开的statements的最大数量,缺省值为-1(即无限制)

defaultCatalog - 设置默认的catalog名称,没有缺省值

connectionInitSqls - 一旦创建一个连接,则connectionInitSqls中的SQL statements列表都会被执行。多条statements用分号(;)分隔。该属性的缺省值为空

connectionProperties - 传递给驱动用来创建连接的属性列表。每个属性的格式都是name=value,多个属性间用分号(;)分隔。该属性的缺省值为空

accessToUnderlyingConnectionAllowed - 取值为true或false。是否允许获取内部连接,缺省为false。]

For more details, please refer to the commons-dbcp documentation.

[参考commons-dbcp文档获取更多信息。]

Adding Custom Resource Factories(添加自定义资源工厂)

If none of the standard resource factories meet your needs, you can write your own factory and integrate it into Tomcat, and then configure the use of this factory in the <Context> element for the web application. In the example below, we will create a factory that only knows how to create com.mycompany.MyBean beans from the Generic JavaBean Resources example above.

[如果所有的标准资源工厂都不能满足你的需求,那么你可以自定义一个工厂,并将其集成到tomcat中,然后在web应用的<Context>元素中配置使用这个工厂。在如下的例子中,我们会创建一个工厂,该工厂的作用是根据上面的Generic JavaBean Resources例子来创建com.mycompany.MyBean的实例对象。]

1. Write A Resource Factory Class(写一个资源工厂类)

You must write a class that implements the JNDI service provider javax.naming.spi.ObjectFactory interface. Every time your web application calls lookup() on a context entry that is bound to this factory (assuming that the factory is configured with singleton="false"), the getObjectInstance() method is called, with the following arguments:

[你必须写一个javax.naming.spi.ObjectFactory接口(该接口提供了JNDI服务)的实现类。每次当你的web应用在一个已经绑定该工厂(假设该工厂的singleton属性设为false)的context条目上调用lookup()函数时,都会调用getObjectInstance()方法,该方法的参数如下:]

Object obj - The (possibly null) object containing location or reference information that can be used in creating an object. For Tomcat, this will always be an object of type javax.naming.Reference, which contains the class name of this factory class, as well as the configuration properties (from the <Context> for the web application) to use in creating objects to be returned.

Name name - The name to which this factory is bound relative to nameCtx, or null if no name is specified.

Context nameCtx - The context relative to which the name parameter is specified, or null if name is relative to the default initial context.

Hashtable environment - The (possibly null) environment that is used in creating this object. This is generally ignored in Tomcat object factories.

[Object obj - 该对象(可能为null)包含可以位置和引用信息,可以被用来创建一个对象。在tomcat中,这总是一个类型为javax.naming.Reference的对象,其中包含工厂类的类名以及用来创建返回对象的配置属性(从web应用的<Context>中获得)。

Name name - 工厂绑定的相对于nameCtx的名称,如果不指定,则为null。

Context nameCtx - 参数name相对的context,如果name是相对于缺省的initial context,则为null。

Hashtable environment - 用来创建对象的环境(可能为null),该参数在tomcat对象工厂中通常被忽略。]

To create a resource factory that knows how to produce MyBean instances, you might create a class like this:

[可以按照如下操作创建一个知道如何生成MyBean实例的资源工厂:]

In this example, we are unconditionally creating a new instance of the com.mycompany.MyBean class, and populating its properties based on the parameters included in the <ResourceParams> element that configures this factory (see below). You should note that any parameter named factory should be skipped - that parameter is used to specify the name of the factory class itself (in this case, com.mycompany.MyBeanFactory) rather than a property of the bean being configured.

[在上面的例子中,我们无条件的创建一个com.mycompany.MyBean类的实例,并用配置该工厂(见下文)的<ResourceParams>元素中的参数来填充实例的属性。]

For more information about ObjectFactory, see the JNDI Service Provider Interface (SPI) Specification.

[参考JNDI Service Provider Interface (SPI) Specification获取更多关于ObjectFactory的信息。]

You will need to compile this class against a class path that includes all of the JAR files in the $CATALINA_HOME/lib directory. When you are through, place the factory class (and the corresponding bean class) unpacked under $CATALINA_HOME/lib, or in a JAR file inside $CATALINA_HOME/lib. In this way, the required class files are visible to both Catalina internal resources and your web application.

[你需要依赖$CATALINA_HOME/lib目录下的jar文件来编译该类,编译完成后,将工厂类和对应的bean类放到$CATALINA_HOME/lib目录下(直接放值或者打成jar文件),这样,Catalina的内部资源以及你的web应用就都能看见这些类文件了。]

2. Declare Your Resource Requirements(声明你的资源要求)

Next, modify your web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will request new instances of this bean. The simplest approach is to use a <resource-env-ref> element, like this:

[接下来,修改web.xml文件来声明要生成的bean实例的JNDI名称。可以通过<resource-env-ref>元素来完成这点,如下:]

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

[警告,确保你遵守了web.xml中的DTD,参考Servlet Specification获取详细信息。]

3. Code Your Application's Use Of This Resource(使用该资源)

A typical use of this resource environment reference might look like this:

[该资源环境引用的一个典型用法如下:]

4. Configure Tomcat's Resource Factory(配置资源工厂)

To configure Tomcat's resource factory, add an elements like this to the <Context> element for this web application.

[在应用的<Context>元素中增加如下元素,即可以配置tomcat的资源工厂。]

Note that the resource name (here, bean/MyBeanFactory must match the value specified in the web application deployment descriptor. We are also initializing the value of the bar property, which will cause setBar(23) to be called before the new bean is returned. Because we are not initializing the foo property (although we could have), the bean will contain whatever default value is set up by its constructor.

[注意,资源名称(这里是bean/MyBeanFactory)必须与web.xml中指定的值相同。我们也初始化了bar属性的值,这会在返回新的bean之前调用setBar(23)。因为我们没有初始化foo属性(尽管可以这么做),因此bean会将其赋值为构造函数中的初始值。]

You will also note that, from the application developer's perspective, the declaration of the resource environment reference, and the programming used to request new instances, is identical to the approach used for the Generic JavaBean Resources example. This illustrates one of the advantages of using JNDI resources to encapsulate functionality - you can change the underlying implementation without necessarily having to modify applications using the resources, as long as you maintain compatible APIs.

[还要注意的是,从应用开发者的角度来说,声明资源环境引用以及用来请求新实例的代码,与Generic JavaBean Resources例子中使用的完全相同。这一点说明了使用JNDI资源来封装功能的一个优势,就是你可以改变内在的实现,而不用修改使用该资源的应用,只用维护兼容的API即可。]

Tomcat翻译--JNDI Resources HOW-TO的更多相关文章

  1. 帆软报表FineReport中数据连接之Tomcat配置JNDI连接

    1. 问题描述 在帆软报表FineReport中,通过JNDI方式定义数据连接,首先在Tomcat服务器配置好JNDI,然后在设计器中直接调用JNDI的名字,即可成功使用JNDI连接,连接步骤如下: ...

  2. tomcat下jndi配置

    jndi(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API.命名服务将名称和对象联系起来,使得我们可以用 ...

  3. tomcat下jndi的三种配置方式

    jndi(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API.命名服务将名称和对象联系起来,使得我们可以用 ...

  4. tomcat+dbcp+jndi 配置

    1)添加jar包 tomcat6中 TOMCAT_HOME/lib 下是公用jar包 dbcp需要3个jar包:Jakarta-Commons DBCP,Jakarta-Commons Collect ...

  5. 【转】tomcat下jndi的三种配置方式

    jndi(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API.命名服务将名称和对象联系起来,使得我们可以用 ...

  6. Tomcat通过JNDI方式链接MySql数据库

    原文:Tomcat通过JNDI方式链接MySql数据库 拷贝MySQL的JDBC驱动到Tomcat的lib路径下 配置全局数据源或者单个Web应用的局部数据源 局部数据源 在Tomcat的conf/C ...

  7. Tomcat配置JNDI

    JNDI是什么?使用JNDI有什么好处? JNDI是 Java 命名与目录接口(Java Naming and Directory Interface),在J2EE规范中是重要的规范之一. 我个人对j ...

  8. 使用Tomcat、JNDI与ActiveMQ实现JMS消息通信服务

    前言 之所以使用JNDI 是出于通用性考虑,该例子使用JMS规范提供的通用接口,没有使用具体JMS提供者的接口,这样可以保证我们编写的程序适用于任何一种JMS实现(ActiveMQ.HornetQ等) ...

  9. Tomcat翻译--Context Container

    原文:http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Resource_Definitions The Context Cont ...

随机推荐

  1. STL学习笔记— —容器map和multimap

    简单介绍 在头文件<map> 中定义 namespace std { template <typename Key, typename T, typename Compare = l ...

  2. jquerymobile模板

    <!DOCTYPE html> <html> <head> <title>Page Title</title> <meta name= ...

  3. Ubuntu Server 16.04安装xfce4图形界面远程控制

    1.首先连接上你的服务器,然后安装vncserver,命令如下 apt-get install vnc4server 2.安装图形界面 apt-get install xfce4如果安装不上,就 ap ...

  4. C#编写图书列表winform

    Book.cs文件 using System; using System.Collections.Generic; using System.Linq; using System.Text; usin ...

  5. qt的登录设置(转)

    1.下面添加代码来实现使用用户名和密码登录,这里只是简单将用户名和密码设置为了固定的字符串,如果以后学习了数据库,还可以通过读取数据库来获取用户名和密码.到logindialog.cpp文件中将登录按 ...

  6. qnx 黑莓系统

    qnx 黑莓图形系统框架 http://www.360doc.com/content/07/0807/10/38907_658192.shtml http://blog.csdn.net/keyboa ...

  7. python中编写无参数decorator

    Python的 decorator 本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数. 使用 decorator 用Python提供的 @ 语法,这样可以避免手动编写 f = de ...

  8. 跨平台移动开发 Xuijs超轻量级的框架 Dom与Event简洁代码实现文本展开收起

    Dom与Event简洁代码实现文本展开收起 Xuijs超轻量级的框架 Dom与Event实现文本展开收起 效果图 示例代码 <!DOCTYPE html PUBLIC "-//W3C/ ...

  9. 20145230《java学习笔记》第九周学习总结

    20145230 <Java程序设计>第9周学习总结 教材学习内容 JDBC JDBC简介 JDBC是用于执行SQL的解决方案,开发人员使用JDBC的标准接口,数据库厂商则对接口进行操作, ...

  10. JavaWeb Session

    1. Session概述 1.1. 什么是Session Session一般译为会话,是解决Http协议的无状态问题的方案,可以将一次会话中的数据存储在服务器端的内存中,保证在下一次的会话中可以使用. ...