Tomcat翻譯--JNDI Resources HOW-TO

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

Introduction(介紹)java

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

[Tomcat爲在其中運行的每一個web應用都提供了一個JNDI InitialContext實現實例,這些實例與Java Enterprise Edition應用服務器所提供的實例相兼容。Java EE在/WEB-INF/web.xml文件中提供了一系列標準元素來引用或者定義資源。]sql

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所支持的特性:]apache

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配置)tomcat

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便可。]

相關文章
相關標籤/搜索