blob: 5783e79d6ca8daf0ff66d1e1183e2ecc9ef1eac6 [file] [log] [blame]
刘洪青6266f992017-05-15 21:21:03 +08001<html><head><META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Apache Tomcat 7 (7.0.77) - JNDI Resources HOW-TO</title><meta name="author" content="Craig R. McClanahan"><meta name="author" content="Yoav Shapira"><style type="text/css" media="print">
2 .noPrint {display: none;}
3 td#mainBody {width: 100%;}
4</style><style type="text/css">
5code {background-color:rgb(224,255,255);padding:0 0.1em;}
6code.attributeName, code.propertyName {background-color:transparent;}
7
8
9table {
10 border-collapse: collapse;
11 text-align: left;
12}
13table *:not(table) {
14 /* Prevent border-collapsing for table child elements like <div> */
15 border-collapse: separate;
16}
17
18th {
19 text-align: left;
20}
21
22
23div.codeBox pre code, code.attributeName, code.propertyName, code.noHighlight, .noHighlight code {
24 background-color: transparent;
25}
26div.codeBox {
27 overflow: auto;
28 margin: 1em 0;
29}
30div.codeBox pre {
31 margin: 0;
32 padding: 4px;
33 border: 1px solid #999;
34 border-radius: 5px;
35 background-color: #eff8ff;
36 display: table; /* To prevent <pre>s from taking the complete available width. */
37 /*
38 When it is officially supported, use the following CSS instead of display: table
39 to prevent big <pre>s from exceeding the browser window:
40 max-width: available;
41 width: min-content;
42 */
43}
44
45div.codeBox pre.wrap {
46 white-space: pre-wrap;
47}
48
49
50table.defaultTable tr, table.detail-table tr {
51 border: 1px solid #CCC;
52}
53
54table.defaultTable tr:nth-child(even), table.detail-table tr:nth-child(even) {
55 background-color: #FAFBFF;
56}
57
58table.defaultTable tr:nth-child(odd), table.detail-table tr:nth-child(odd) {
59 background-color: #EEEFFF;
60}
61
62table.defaultTable th, table.detail-table th {
63 background-color: #88b;
64 color: #fff;
65}
66
67table.defaultTable th, table.defaultTable td, table.detail-table th, table.detail-table td {
68 padding: 5px 8px;
69}
70
71
72p.notice {
73 border: 1px solid rgb(255, 0, 0);
74 background-color: rgb(238, 238, 238);
75 color: rgb(0, 51, 102);
76 padding: 0.5em;
77 margin: 1em 2em 1em 1em;
78}
79</style></head><body bgcolor="#ffffff" text="#000000" link="#525D76" alink="#525D76" vlink="#525D76"><table border="0" width="100%" cellspacing="0"><!--PAGE HEADER--><tr><td><!--PROJECT LOGO--><a href="http://tomcat.apache.org/"><img src="./images/tomcat.gif" align="right" alt="
Hongqing Liufd5ee812014-05-10 16:32:51 +080080 The Apache Tomcat Servlet/JSP Container
刘洪青6266f992017-05-15 21:21:03 +080081 " border="0"></a></td><td><h1><font face="arial,helvetica,sanserif">Apache Tomcat 7</font></h1><font face="arial,helvetica,sanserif">Version 7.0.77, Mar 28 2017</font></td><td><!--APACHE LOGO--><a href="http://www.apache.org/"><img src="./images/asf-logo.svg" align="right" alt="Apache Logo" border="0" style="width: 266px;height: 83px;"></a></td></tr></table><table border="0" width="100%" cellspacing="4"><!--HEADER SEPARATOR--><tr><td colspan="2"><hr noshade size="1"></td></tr><tr><!--LEFT SIDE NAVIGATION--><td width="20%" valign="top" nowrap class="noPrint"><p><strong>Links</strong></p><ul><li><a href="index.html">Docs Home</a></li><li><a href="http://wiki.apache.org/tomcat/FAQ">FAQ</a></li><li><a href="#comments_section">User Comments</a></li></ul><p><strong>User Guide</strong></p><ul><li><a href="introduction.html">1) Introduction</a></li><li><a href="setup.html">2) Setup</a></li><li><a href="appdev/index.html">3) First webapp</a></li><li><a href="deployer-howto.html">4) Deployer</a></li><li><a href="manager-howto.html">5) Manager</a></li><li><a href="realm-howto.html">6) Realms and AAA</a></li><li><a href="security-manager-howto.html">7) Security Manager</a></li><li><a href="jndi-resources-howto.html">8) JNDI Resources</a></li><li><a href="jndi-datasource-examples-howto.html">9) JDBC DataSources</a></li><li><a href="class-loader-howto.html">10) Classloading</a></li><li><a href="jasper-howto.html">11) JSPs</a></li><li><a href="ssl-howto.html">12) SSL/TLS</a></li><li><a href="ssi-howto.html">13) SSI</a></li><li><a href="cgi-howto.html">14) CGI</a></li><li><a href="proxy-howto.html">15) Proxy Support</a></li><li><a href="mbeans-descriptors-howto.html">16) MBeans Descriptors</a></li><li><a href="default-servlet.html">17) Default Servlet</a></li><li><a href="cluster-howto.html">18) Clustering</a></li><li><a href="balancer-howto.html">19) Load Balancer</a></li><li><a href="connectors.html">20) Connectors</a></li><li><a href="monitoring.html">21) Monitoring and Management</a></li><li><a href="logging.html">22) Logging</a></li><li><a href="apr.html">23) APR/Native</a></li><li><a href="virtual-hosting-howto.html">24) Virtual Hosting</a></li><li><a href="aio.html">25) Advanced IO</a></li><li><a href="extras.html">26) Additional Components</a></li><li><a href="maven-jars.html">27) Mavenized</a></li><li><a href="security-howto.html">28) Security Considerations</a></li><li><a href="windows-service-howto.html">29) Windows Service</a></li><li><a href="windows-auth-howto.html">30) Windows Authentication</a></li><li><a href="jdbc-pool.html">31) Tomcat's JDBC Pool</a></li><li><a href="web-socket-howto.html">32) WebSocket</a></li></ul><p><strong>Reference</strong></p><ul><li><a href="RELEASE-NOTES.txt">Release Notes</a></li><li><a href="config/index.html">Configuration</a></li><li><a href="api/index.html">Tomcat Javadocs</a></li><li><a href="servletapi/index.html">Servlet Javadocs</a></li><li><a href="jspapi/index.html">JSP 2.2 Javadocs</a></li><li><a href="elapi/index.html">EL 2.2 Javadocs</a></li><li><a href="websocketapi/index.html">WebSocket 1.1 Javadocs</a></li><li><a href="http://tomcat.apache.org/connectors-doc/">JK 1.2 Documentation</a></li></ul><p><strong>Apache Tomcat Development</strong></p><ul><li><a href="building.html">Building</a></li><li><a href="changelog.html">Changelog</a></li><li><a href="http://wiki.apache.org/tomcat/TomcatVersions">Status</a></li><li><a href="developers.html">Developers</a></li><li><a href="architecture/index.html">Architecture</a></li><li><a href="funcspecs/index.html">Functional Specs.</a></li><li><a href="tribes/introduction.html">Tribes</a></li></ul></td><!--RIGHT SIDE MAIN BODY--><td width="80%" valign="top" align="left" id="mainBody"><h1>JNDI Resources HOW-TO</h1><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Table of Contents"><!--()--></a><a name="Table_of_Contents"><strong>Table of Contents</strong></a></font></td></tr><tr><td><blockquote>
Hongqing Liufd5ee812014-05-10 16:32:51 +080082<ul><li><a href="#Introduction">Introduction</a></li><li><a href="#web.xml_configuration">web.xml configuration</a></li><li><a href="#context.xml_configuration">context.xml configuration</a></li><li><a href="#Global_configuration">Global configuration</a></li><li><a href="#Using_resources">Using resources</a></li><li><a href="#Tomcat_Standard_Resource_Factories">Tomcat Standard Resource Factories</a><ol><li><a href="#Generic_JavaBean_Resources">Generic JavaBean Resources</a></li><li><a href="#UserDatabase_Resources">UserDatabase Resources</a></li><li><a href="#JavaMail_Sessions">JavaMail Sessions</a></li><li><a href="#JDBC_Data_Sources">JDBC Data Sources</a></li></ol></li><li><a href="#Adding_Custom_Resource_Factories">Adding Custom Resource Factories</a></li></ul>
83</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Introduction"><strong>Introduction</strong></a></font></td></tr><tr><td><blockquote>
84
刘洪青6266f992017-05-15 21:21:03 +080085<p>Tomcat provides a JNDI <strong>InitialContext</strong> implementation
86instance for each web application running under it, in a manner that is
87compatible with those provided by a
88<a href="http://www.oracle.com/technetwork/java/javaee/overview/index.html">
89Java Enterprise Edition</a> application server. The Java EE standard provides
90a standard set of elements in the <code>/WEB-INF/web.xml</code> file to
91reference/define resources.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +080092
93<p>See the following Specifications for more information about programming APIs
刘洪青6266f992017-05-15 21:21:03 +080094for JNDI, and for the features supported by Java Enterprise Edition (Java EE)
Hongqing Liufd5ee812014-05-10 16:32:51 +080095servers, which Tomcat emulates for the services that it provides:</p>
96<ul>
刘洪青6266f992017-05-15 21:21:03 +080097<li><a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/index.html">
98 Java Naming and Directory Interface</a> (included in JDK 1.4 onwards)</li>
99<li><a href="http://www.oracle.com/technetwork/java/javaee/documentation/index.html">
100 Java EE Platform Specification</a> (in particular, see Chapter 5 on <em>Naming</em>)</li>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800101</ul>
102
103</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="web.xml configuration"><!--()--></a><a name="web.xml_configuration"><strong>web.xml configuration</strong></a></font></td></tr><tr><td><blockquote>
104
105<p>The following elements may be used in the web application deployment
106descriptor (<code>/WEB-INF/web.xml</code>) of your web application to define
107resources:</p>
108<ul>
109<li><code><strong>&lt;env-entry&gt;</strong></code> - Environment entry, a
110 single-value parameter that can be used to configure how the application
111 will operate.</li>
112<li><code><strong>&lt;resource-ref&gt;</strong></code> - Resource reference,
113 which is typically to an object factory for resources such as a JDBC
114 <code>DataSource</code>, a JavaMail <code>Session</code>, or custom
刘洪青6266f992017-05-15 21:21:03 +0800115 object factories configured into Tomcat.</li>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800116<li><code><strong>&lt;resource-env-ref&gt;</strong></code> - Resource
117 environment reference, a new variation of <code>resource-ref</code>
118 added in Servlet 2.4 that is simpler to configure for resources
119 that do not require authentication information.</li>
120</ul>
121
122<p>Providing that Tomcat is able to identify an appropriate resource factory to
123use to create the resource and that no further configuration information is
124required, Tomcat will use the information in <code>/WEB-INF/web.xml</code> to
125create the resource.</p>
刘洪青6266f992017-05-15 21:21:03 +0800126
127<p>Tomcat provides a number of Tomcat specific options for JNDI resources that
128cannot be specified in web.xml. These include <code>closeMethod</code> that
129enables faster cleaning-up of JNDI resources when a web application stops and
130<code>singleton</code> that controls whether or not a new instance of the
131resource is created for every JNDI lookup. To use these configuration options
132the resource must be specified in a web application's
133<a href="config/context.html"><code>&lt;Context&gt;</code></a> element or in the
134<a href="config/globalresources.html">
135<code><strong>&lt;GlobalNamingResources&gt;</strong></code></a> element of
136<code>$CATALINA_BASE/conf/server.xml</code>.</p>
137
Hongqing Liufd5ee812014-05-10 16:32:51 +0800138</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="context.xml configuration"><!--()--></a><a name="context.xml_configuration"><strong>context.xml configuration</strong></a></font></td></tr><tr><td><blockquote>
139
140<p>If Tomcat is unable to identify the appropriate resource factory and/or
141additional configuration information is required, additional Tomcat specific
142configuration must be specified before Tomcat can create the resource.
143Tomcat specific resource configuration is entered in
144the <a href="config/context.html"><code>&lt;Context&gt;</code></a> elements that
145can be specified in either <code>$CATALINA_BASE/conf/server.xml</code> or,
146preferably, the per-web-application context XML file
147(<code>META-INF/context.xml</code>).</p>
148
149<p>Tomcat specific resource configuration is performed using the following
150elements in the <a href="config/context.html"><code>&lt;Context&gt;</code></a>
151element:</p>
152
153<ul>
刘洪青6266f992017-05-15 21:21:03 +0800154<li><a href="config/context.html#Environment_Entries">&lt;Environment&gt;</a> -
Hongqing Liufd5ee812014-05-10 16:32:51 +0800155 Configure names and values for scalar environment entries that will be
156 exposed to the web application through the JNDI
157 <code>InitialContext</code> (equivalent to the inclusion of an
158 <code>&lt;env-entry&gt;</code> element in the web application
159 deployment descriptor).</li>
刘洪青6266f992017-05-15 21:21:03 +0800160<li><a href="config/context.html#Resource_Definitions">&lt;Resource&gt;</a> -
Hongqing Liufd5ee812014-05-10 16:32:51 +0800161 Configure the name and data type of a resource made available to the
162 application (equivalent to the inclusion of a
163 <code>&lt;resource-ref&gt;</code> element in the web application
164 deployment descriptor).</li>
刘洪青6266f992017-05-15 21:21:03 +0800165<li><a href="config/context.html#Resource_Links">&lt;ResourceLink&gt;</a> -
166 Add a link to a resource defined in the global JNDI context. Use resource
167 links to give a web application access to a resource defined in
Hongqing Liufd5ee812014-05-10 16:32:51 +0800168 the <a href="config/globalresources.html">&lt;GlobalNamingResources&gt;</a>
169 child element of the <a href="config/server.html">&lt;Server&gt;</a>
170 element.</li>
171<li><a href="config/context.html#Transaction">&lt;Transaction&gt;</a> -
刘洪青6266f992017-05-15 21:21:03 +0800172 Add a resource factory for instantiating the UserTransaction object
Hongqing Liufd5ee812014-05-10 16:32:51 +0800173 instance that is available at <code>java:comp/UserTransaction</code>.</li>
174
175</ul>
176
177<p>Any number of these elements may be nested inside a
178<a href="config/context.html"><code>&lt;Context&gt;</code></a> element and will
179be associated only with that particular web application.</p>
180
181<p>If a resource has been defined in a
182<a href="config/context.html"><code>&lt;Context&gt;</code></a> element it is not
183necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
184However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
185to document the resource requirements for the web application.</p>
186
187<p>Where the same resource name has been defined for a
188<code>&lt;env-entry&gt;</code> element included in the web application
189deployment descriptor (<code>/WEB-INF/web.xml</code>) and in an
190<code>&lt;Environment&gt;</code> element as part of the
191<a href="config/context.html"><code>&lt;Context&gt;</code></a> element for the
192web application, the values in the deployment descriptor will take precedence
193<strong>only</strong> if allowed by the corresponding
194<code>&lt;Environment&gt;</code> element (by setting the <code>override</code>
195attribute to "true").</p>
196
197</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Global configuration"><!--()--></a><a name="Global_configuration"><strong>Global configuration</strong></a></font></td></tr><tr><td><blockquote>
198
刘洪青6266f992017-05-15 21:21:03 +0800199<p>Tomcat maintains a separate namespace of global resources for the
200entire server. These are configured in the
Hongqing Liufd5ee812014-05-10 16:32:51 +0800201<a href="config/globalresources.html">
刘洪青6266f992017-05-15 21:21:03 +0800202<code><strong>&lt;GlobalNamingResources&gt;</strong></code></a> element of
203<code>$CATALINA_BASE/conf/server.xml</code>. You may expose these resources to
204web applications by using a
205<a href="config/context.html#Resource_Links">&lt;ResourceLink&gt;</a> to
Hongqing Liufd5ee812014-05-10 16:32:51 +0800206include it in the per-web-application context.</p>
207
刘洪青6266f992017-05-15 21:21:03 +0800208<p>If a resource has been defined using a
209<a href="config/context.html#Resource_Links">&lt;ResourceLink&gt;</a>, it is not
Hongqing Liufd5ee812014-05-10 16:32:51 +0800210necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
211However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
212to document the resource requirements for the web application.</p>
213
214</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Using resources"><!--()--></a><a name="Using_resources"><strong>Using resources</strong></a></font></td></tr><tr><td><blockquote>
215
216<p>The <code>InitialContext</code> is configured as a web application is
217initially deployed, and is made available to web application components (for
218read-only access). All configured entries and resources are placed in
219the <code>java:comp/env</code> portion of the JNDI namespace, so a typical
220access to a resource - in this case, to a JDBC <code>DataSource</code> -
221would look something like this:</p>
222
刘洪青6266f992017-05-15 21:21:03 +0800223<div class="codeBox"><pre><code>// Obtain our environment naming context
Hongqing Liufd5ee812014-05-10 16:32:51 +0800224Context initCtx = new InitialContext();
225Context envCtx = (Context) initCtx.lookup("java:comp/env");
226
227// Look up our data source
228DataSource ds = (DataSource)
229 envCtx.lookup("jdbc/EmployeeDB");
230
231// Allocate and use a connection from the pool
232Connection conn = ds.getConnection();
233... use this connection to access the database ...
刘洪青6266f992017-05-15 21:21:03 +0800234conn.close();</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800235
236</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Tomcat Standard Resource Factories"><!--()--></a><a name="Tomcat_Standard_Resource_Factories"><strong>Tomcat Standard Resource Factories</strong></a></font></td></tr><tr><td><blockquote>
237
刘洪青6266f992017-05-15 21:21:03 +0800238 <p>Tomcat includes a series of standard resource factories that can
Hongqing Liufd5ee812014-05-10 16:32:51 +0800239 provide services to your web applications, but give you configuration
240 flexibility (via the
241 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element)
242 without modifying the web application or the deployment descriptor. Each
243 subsection below details the configuration and usage of the standard resource
244 factories.</p>
245
刘洪青6266f992017-05-15 21:21:03 +0800246 <p>See <a href="#Adding_Custom_Resource_Factories">Adding Custom
Hongqing Liufd5ee812014-05-10 16:32:51 +0800247 Resource Factories</a> for information about how to create, install,
248 configure, and use your own custom resource factory classes with
刘洪青6266f992017-05-15 21:21:03 +0800249 Tomcat.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800250
251 <p><em>NOTE</em> - Of the standard resource factories, only the
252 "JDBC Data Source" and "User Transaction" factories are mandated to
253 be available on other platforms, and then they are required only if
刘洪青6266f992017-05-15 21:21:03 +0800254 the platform implements the Java Enterprise Edition (Java EE) specs.
Hongqing Liufd5ee812014-05-10 16:32:51 +0800255 All other standard resource factories, plus custom resource factories
256 that you write yourself, are specific to Tomcat and cannot be assumed
257 to be available on other containers.</p>
258
259 <table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#828DA6"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Generic JavaBean Resources"><!--()--></a><a name="Generic_JavaBean_Resources"><strong>Generic JavaBean Resources</strong></a></font></td></tr><tr><td><blockquote>
260
刘洪青6266f992017-05-15 21:21:03 +0800261 <h5>0. Introduction</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800262
263 <p>This resource factory can be used to create objects of <em>any</em>
264 Java class that conforms to standard JavaBeans naming conventions (i.e.
265 it has a zero-arguments constructor, and has property setters that
266 conform to the setFoo() naming pattern. The resource factory will
刘洪青6266f992017-05-15 21:21:03 +0800267 only create a new instance of the appropriate bean class every time a
268 <code>lookup()</code> for this entry is made if the <code>singleton</code>
269 attribute of the factory is set to <code>false</code>.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800270
271 <p>The steps required to use this facility are described below.</p>
272
刘洪青6266f992017-05-15 21:21:03 +0800273 <h5>1. Create Your JavaBean Class</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800274
275 <p>Create the JavaBean class which will be instantiated each time
276 that the resource factory is looked up. For this example, assume
277 you create a class <code>com.mycompany.MyBean</code>, which looks
278 like this:</p>
279
刘洪青6266f992017-05-15 21:21:03 +0800280<div class="codeBox"><pre><code>package com.mycompany;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800281
282public class MyBean {
283
284 private String foo = "Default Foo";
285
286 public String getFoo() {
287 return (this.foo);
288 }
289
290 public void setFoo(String foo) {
291 this.foo = foo;
292 }
293
294 private int bar = 0;
295
296 public int getBar() {
297 return (this.bar);
298 }
299
300 public void setBar(int bar) {
301 this.bar = bar;
302 }
303
304
刘洪青6266f992017-05-15 21:21:03 +0800305}</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800306
刘洪青6266f992017-05-15 21:21:03 +0800307 <h5>2. Declare Your Resource Requirements</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800308
309 <p>Next, modify your web application deployment descriptor
310 (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under which
311 you will request new instances of this bean. The simplest approach is
312 to use a <code>&lt;resource-env-ref&gt;</code> element, like this:</p>
313
刘洪青6266f992017-05-15 21:21:03 +0800314<div class="codeBox"><pre><code>&lt;resource-env-ref&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800315 &lt;description&gt;
316 Object factory for MyBean instances.
317 &lt;/description&gt;
318 &lt;resource-env-ref-name&gt;
319 bean/MyBeanFactory
320 &lt;/resource-env-ref-name&gt;
321 &lt;resource-env-ref-type&gt;
322 com.mycompany.MyBean
323 &lt;/resource-env-ref-type&gt;
刘洪青6266f992017-05-15 21:21:03 +0800324&lt;/resource-env-ref&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800325
326 <p><strong>WARNING</strong> - Be sure you respect the element ordering
327 that is required by the DTD for web application deployment descriptors!
328 See the
329 <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
330 Specification</a> for details.</p>
331
刘洪青6266f992017-05-15 21:21:03 +0800332 <h5>3. Code Your Application's Use Of This Resource</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800333
334 <p>A typical use of this resource environment reference might look
335 like this:</p>
336
刘洪青6266f992017-05-15 21:21:03 +0800337<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
Hongqing Liufd5ee812014-05-10 16:32:51 +0800338Context envCtx = (Context) initCtx.lookup("java:comp/env");
339MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
340
341writer.println("foo = " + bean.getFoo() + ", bar = " +
刘洪青6266f992017-05-15 21:21:03 +0800342 bean.getBar());</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800343
刘洪青6266f992017-05-15 21:21:03 +0800344 <h5>4. Configure Tomcat's Resource Factory</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800345
346 <p>To configure Tomcat's resource factory, add an element like this to the
347 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
348 this web application.</p>
349
刘洪青6266f992017-05-15 21:21:03 +0800350<div class="codeBox"><pre><code>&lt;Context ...&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800351 ...
352 &lt;Resource name="bean/MyBeanFactory" auth="Container"
353 type="com.mycompany.MyBean"
354 factory="org.apache.naming.factory.BeanFactory"
355 bar="23"/&gt;
356 ...
刘洪青6266f992017-05-15 21:21:03 +0800357&lt;/Context&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800358
359 <p>Note that the resource name (here, <code>bean/MyBeanFactory</code>
360 must match the value specified in the web application deployment
361 descriptor. We are also initializing the value of the <code>bar</code>
362 property, which will cause <code>setBar(23)</code> to be called before
363 the new bean is returned. Because we are not initializing the
364 <code>foo</code> property (although we could have), the bean will
365 contain whatever default value is set up by its constructor.</p>
366
刘洪青6266f992017-05-15 21:21:03 +0800367 <p>Some beans have properties with types that can not automatically be
368 converted from a string value. Setting such properties using the Tomcat
369 BeanFactory will fail with a NamingException. In cases were those beans
370 provide methods to set the properties from a string value, the Tomcat
371 BeanFactory can be configured to use these methods. The configuration is
372 done with the <code>forceString</code> attribute.</p>
373
374 <p>Assume our bean looks like this:</p>
375
376<div class="codeBox"><pre><code>package com.mycompany;
377
378import java.net.InetAddress;
379import java.net.UnknownHostException;
380
381public class MyBean2 {
382
383 private InetAddress local = null;
384
385 public InetAddress getLocal() {
386 return local;
387 }
388
389 public void setLocal(InetAddress ip) {
390 local = ip;
391 }
392
393 public void setLocal(String localHost) {
394 try {
395 local = InetAddress.getByName(localHost);
396 } catch (UnknownHostException ex) {
397 }
398 }
399
400 private InetAddress remote = null;
401
402 public InetAddress getRemote() {
403 return remote;
404 }
405
406 public void setRemote(InetAddress ip) {
407 remote = ip;
408 }
409
410 public void host(String remoteHost) {
411 try {
412 remote = InetAddress.getByName(remoteHost);
413 } catch (UnknownHostException ex) {
414 }
415 }
416
417}</code></pre></div>
418
419 <p>The bean has two properties, both are of type <code>InetAddress</code>.
420 The first property <code>local</code> has an additional setter taking a
421 string argument. By default the Tomcat BeanFactory would try to use the
422 automatically detected setter with the same argument type as the property
423 type and then throw a NamingException, because it is not prepared to convert
424 the given string attribute value to <code>InetAddress</code>.
425 We can tell the Tomcat BeanFactory to use the other setter like that:</p>
426
427<div class="codeBox"><pre><code>&lt;Context ...&gt;
428 ...
429 &lt;Resource name="bean/MyBeanFactory" auth="Container"
430 type="com.mycompany.MyBean2"
431 factory="org.apache.naming.factory.BeanFactory"
432 forceString="local"
433 local="localhost"/&gt;
434 ...
435&lt;/Context&gt;</code></pre></div>
436
437 <p>The bean property <code>remote</code> can also be set from a string,
438 but one has to use the non-standard method name <code>host</code>.
439 To set <code>local</code> and <code>remote</code> use the following
440 configuration:</p>
441
442<div class="codeBox"><pre><code>&lt;Context ...&gt;
443 ...
444 &lt;Resource name="bean/MyBeanFactory" auth="Container"
445 type="com.mycompany.MyBean2"
446 factory="org.apache.naming.factory.BeanFactory"
447 forceString="local,remote=host"
448 local="localhost"
449 remote="tomcat.apache.org"/&gt;
450 ...
451&lt;/Context&gt;</code></pre></div>
452
453 <p>Multiple property descriptions can be combined in
454 <code>forceString</code> by concatenation with comma as a separator.
455 Each property description consists of either only the property name
456 in which case the BeanFactory calls the setter method. Or it consist
457 of <code>name=method</code> in which case the property named
458 <code>name</code> is set by calling method <code>method</code>.
459 For properties of types <code>String</code> or of primitive type
460 or of their associated primitive wrapper classes using
461 <code>forceString</code> is not needed. The correct setter will be
462 automatically detected and argument conversion will be applied.</p>
463
Hongqing Liufd5ee812014-05-10 16:32:51 +0800464 </blockquote></td></tr></table>
465
466
467 <table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#828DA6"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="UserDatabase Resources"><!--()--></a><a name="UserDatabase_Resources"><strong>UserDatabase Resources</strong></a></font></td></tr><tr><td><blockquote>
468
刘洪青6266f992017-05-15 21:21:03 +0800469 <h5>0. Introduction</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800470
471 <p>UserDatabase resources are typically configured as global resources for
刘洪青6266f992017-05-15 21:21:03 +0800472 use by a UserDatabase realm. Tomcat includes a UserDatabaseFactory that
Hongqing Liufd5ee812014-05-10 16:32:51 +0800473 creates UserDatabase resources backed by an XML file - usually
474 <code>tomcat-users.xml</code></p>
475
476 <p>The steps required to set up a global UserDatabase resource are described
477 below.</p>
478
刘洪青6266f992017-05-15 21:21:03 +0800479 <h5>1. Create/edit the XML file</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800480
刘洪青6266f992017-05-15 21:21:03 +0800481 <p>The XML file is typically located at
Hongqing Liufd5ee812014-05-10 16:32:51 +0800482 <code>$CATALINA_BASE/conf/tomcat-users.xml</code> however, you are free to
483 locate the file anywhere on the file system. It is recommended that the XML
484 files are placed in <code>$CATALINA_BASE/conf</code>. A typical XML would
485 look like:</p>
486
刘洪青6266f992017-05-15 21:21:03 +0800487<div class="codeBox"><pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800488&lt;tomcat-users&gt;
489 &lt;role rolename="tomcat"/&gt;
490 &lt;role rolename="role1"/&gt;
491 &lt;user username="tomcat" password="tomcat" roles="tomcat"/&gt;
492 &lt;user username="both" password="tomcat" roles="tomcat,role1"/&gt;
493 &lt;user username="role1" password="tomcat" roles="role1"/&gt;
刘洪青6266f992017-05-15 21:21:03 +0800494&lt;/tomcat-users&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800495
刘洪青6266f992017-05-15 21:21:03 +0800496 <h5>2. Declare Your Resource</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800497
498 <p>Next, modify <code>$CATALINA_BASE/conf/server.xml</code> to create the
刘洪青6266f992017-05-15 21:21:03 +0800499 UserDatabase resource based on your XML file. It should look something like
Hongqing Liufd5ee812014-05-10 16:32:51 +0800500 this:</p>
501
刘洪青6266f992017-05-15 21:21:03 +0800502<div class="codeBox"><pre><code>&lt;Resource name="UserDatabase"
Hongqing Liufd5ee812014-05-10 16:32:51 +0800503 auth="Container"
504 type="org.apache.catalina.UserDatabase"
505 description="User database that can be updated and saved"
506 factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
507 pathname="conf/tomcat-users.xml"
刘洪青6266f992017-05-15 21:21:03 +0800508 readonly="false" /&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800509
刘洪青6266f992017-05-15 21:21:03 +0800510 <p>The <code>pathname</code> attribute can be a URL, an absolute path or a
511 relative path. If relative, it is relative to <code>$CATALINA_BASE</code>.
512 </p>
513
Hongqing Liufd5ee812014-05-10 16:32:51 +0800514 <p>The <code>readonly</code> attribute is optional and defaults to
515 <code>true</code> if not supplied. If the XML is writeable then it will be
516 written to when Tomcat starts. <strong>WARNING:</strong> When the file is
517 written it will inherit the default file permissions for the user Tomcat
518 is running as. Ensure that these are appropriate to maintain the security
519 of your installation.</p>
520
刘洪青6266f992017-05-15 21:21:03 +0800521 <h5>3. Configure the Realm</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800522
523 <p>Configure a UserDatabase Realm to use this resource as described in the
524 <a href="config/realm.html">Realm configuration documentation</a>.</p>
525
526 </blockquote></td></tr></table>
527
528
529 <table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#828DA6"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="JavaMail Sessions"><!--()--></a><a name="JavaMail_Sessions"><strong>JavaMail Sessions</strong></a></font></td></tr><tr><td><blockquote>
530
刘洪青6266f992017-05-15 21:21:03 +0800531 <h5>0. Introduction</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800532
533 <p>In many web applications, sending electronic mail messages is a
534 required part of the system's functionality. The
刘洪青6266f992017-05-15 21:21:03 +0800535 <a href="http://www.oracle.com/technetwork/java/javamail/index.html">Java Mail</a> API
Hongqing Liufd5ee812014-05-10 16:32:51 +0800536 makes this process relatively straightforward, but requires many
537 configuration details that the client application must be aware of
538 (including the name of the SMTP host to be used for message sending).</p>
539
刘洪青6266f992017-05-15 21:21:03 +0800540 <p>Tomcat includes a standard resource factory that will create
Hongqing Liufd5ee812014-05-10 16:32:51 +0800541 <code>javax.mail.Session</code> session instances for you, already
542 configured to connect to an SMTP server.
543 In this way, the application is totally insulated from changes in the
544 email server configuration environment - it simply asks for, and receives,
545 a preconfigured session whenever needed.</p>
546
547 <p>The steps required for this are outlined below.</p>
548
刘洪青6266f992017-05-15 21:21:03 +0800549 <h5>1. Declare Your Resource Requirements</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800550
551 <p>The first thing you should do is modify the web application deployment
552 descriptor (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
553 which you will look up preconfigured sessions. By convention, all such
554 names should resolve to the <code>mail</code> subcontext (relative to the
555 standard <code>java:comp/env</code> naming context that is the root of
556 all provided resource factories. A typical <code>web.xml</code> entry
557 might look like this:</p>
刘洪青6266f992017-05-15 21:21:03 +0800558<div class="codeBox"><pre><code>&lt;resource-ref&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800559 &lt;description&gt;
560 Resource reference to a factory for javax.mail.Session
561 instances that may be used for sending electronic mail
562 messages, preconfigured to connect to the appropriate
563 SMTP server.
564 &lt;/description&gt;
565 &lt;res-ref-name&gt;
566 mail/Session
567 &lt;/res-ref-name&gt;
568 &lt;res-type&gt;
569 javax.mail.Session
570 &lt;/res-type&gt;
571 &lt;res-auth&gt;
572 Container
573 &lt;/res-auth&gt;
刘洪青6266f992017-05-15 21:21:03 +0800574&lt;/resource-ref&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800575
576 <p><strong>WARNING</strong> - Be sure you respect the element ordering
577 that is required by the DTD for web application deployment descriptors!
578 See the
579 <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
580 Specification</a> for details.</p>
581
刘洪青6266f992017-05-15 21:21:03 +0800582 <h5>2. Code Your Application's Use Of This Resource</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800583
584 <p>A typical use of this resource reference might look like this:</p>
刘洪青6266f992017-05-15 21:21:03 +0800585<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
Hongqing Liufd5ee812014-05-10 16:32:51 +0800586Context envCtx = (Context) initCtx.lookup("java:comp/env");
587Session session = (Session) envCtx.lookup("mail/Session");
588
589Message message = new MimeMessage(session);
590message.setFrom(new InternetAddress(request.getParameter("from")));
591InternetAddress to[] = new InternetAddress[1];
592to[0] = new InternetAddress(request.getParameter("to"));
593message.setRecipients(Message.RecipientType.TO, to);
594message.setSubject(request.getParameter("subject"));
595message.setContent(request.getParameter("content"), "text/plain");
刘洪青6266f992017-05-15 21:21:03 +0800596Transport.send(message);</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800597
598 <p>Note that the application uses the same resource reference name
599 that was declared in the web application deployment descriptor. This
600 is matched up against the resource factory that is configured in the
601 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element
602 for the web application as described below.</p>
603
刘洪青6266f992017-05-15 21:21:03 +0800604 <h5>3. Configure Tomcat's Resource Factory</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800605
606 <p>To configure Tomcat's resource factory, add an elements like this to the
607 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
608 this web application.</p>
609
刘洪青6266f992017-05-15 21:21:03 +0800610<div class="codeBox"><pre><code>&lt;Context ...&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800611 ...
612 &lt;Resource name="mail/Session" auth="Container"
613 type="javax.mail.Session"
614 mail.smtp.host="localhost"/&gt;
615 ...
刘洪青6266f992017-05-15 21:21:03 +0800616&lt;/Context&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800617
618 <p>Note that the resource name (here, <code>mail/Session</code>) must
619 match the value specified in the web application deployment descriptor.
620 Customize the value of the <code>mail.smtp.host</code> parameter to
621 point at the server that provides SMTP service for your network.</p>
622
623 <p>Additional resource attributes and values will be converted to properties
624 and values and passed to
625 <code>javax.mail.Session.getInstance(java.util.Properties)</code> as part of
626 the <code>java.util.Properties</code> collection. In addition to the
627 properties defined in Annex A of the JavaMail specification, individual
刘洪青6266f992017-05-15 21:21:03 +0800628 providers may also support additional properties.
629 </p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800630
刘洪青6266f992017-05-15 21:21:03 +0800631 <p>If the resource is configured with a <code>password</code> attribute and
632 either a <code>mail.smtp.user</code> or <code>mail.user</code> attribute
633 then Tomcat's resource factory will configure and add a
634 <code>javax.mail.Authenticator</code> to the mail session.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800635
刘洪青6266f992017-05-15 21:21:03 +0800636 <h5>4. Install the JavaMail libraries</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800637
刘洪青6266f992017-05-15 21:21:03 +0800638 <p><a href="http://javamail.java.net/">
639 Download the JavaMail API</a>.</p>
640
641 <p>Unpackage the distribution and place mail.jar into $CATALINA_HOME/lib so
642 that it is available to Tomcat during the initialization of the mail Session
643 Resource. <strong>Note:</strong> placing this jar in both $CATALINA_HOME/lib
644 and a web application's lib folder will cause an error, so ensure you have
645 it in the $CATALINA_HOME/lib location only.
Hongqing Liufd5ee812014-05-10 16:32:51 +0800646 </p>
647
刘洪青6266f992017-05-15 21:21:03 +0800648 <h5>5. Restart Tomcat</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800649
刘洪青6266f992017-05-15 21:21:03 +0800650 <p>For the additional JAR to be visible to Tomcat, it is necessary for the
651 Tomcat instance to be restarted.</p>
652
653
654 <h5>Example Application</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800655
656 <p>The <code>/examples</code> application included with Tomcat contains
657 an example of utilizing this resource factory. It is accessed via the
658 "JSP Examples" link. The source code for the servlet that actually
659 sends the mail message is in
660 <code>/WEB-INF/classes/SendMailServlet.java</code>.</p>
661
662 <p><strong>WARNING</strong> - The default configuration assumes that there
663 is an SMTP server listing on port 25 on <code>localhost</code>. If this is
664 not the case, edit the
665 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
666 this web application and modify the parameter value for the
667 <code>mail.smtp.host</code> parameter to be the host name of an SMTP server
668 on your network.</p>
669
670 </blockquote></td></tr></table>
671
672 <table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#828DA6"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="JDBC Data Sources"><!--()--></a><a name="JDBC_Data_Sources"><strong>JDBC Data Sources</strong></a></font></td></tr><tr><td><blockquote>
673
刘洪青6266f992017-05-15 21:21:03 +0800674 <h5>0. Introduction</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800675
676 <p>Many web applications need to access a database via a JDBC driver,
刘洪青6266f992017-05-15 21:21:03 +0800677 to support the functionality required by that application. The Java EE
678 Platform Specification requires Java EE Application Servers to make
Hongqing Liufd5ee812014-05-10 16:32:51 +0800679 available a <em>DataSource</em> implementation (that is, a connection
刘洪青6266f992017-05-15 21:21:03 +0800680 pool for JDBC connections) for this purpose. Tomcat offers exactly
Hongqing Liufd5ee812014-05-10 16:32:51 +0800681 the same support, so that database-based applications you develop on
刘洪青6266f992017-05-15 21:21:03 +0800682 Tomcat using this service will run unchanged on any Java EE server.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800683
684 <p>For information about JDBC, you should consult the following:</p>
685 <ul>
刘洪青6266f992017-05-15 21:21:03 +0800686 <li><a href="http://www.oracle.com/technetwork/java/javase/jdbc/index.html">
687 http://www.oracle.com/technetwork/java/javase/jdbc/index.html</a> -
Hongqing Liufd5ee812014-05-10 16:32:51 +0800688 Home page for information about Java Database Connectivity.</li>
刘洪青6266f992017-05-15 21:21:03 +0800689 <li><a href="http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html">http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html</a> -
Hongqing Liufd5ee812014-05-10 16:32:51 +0800690 The JDBC 2.1 API Specification.</li>
691 <li><a href="http://java.sun.com/products/jdbc/jdbc20.stdext.pdf">http://java.sun.com/products/jdbc/jdbc20.stdext.pdf</a> -
692 The JDBC 2.0 Standard Extension API (including the
693 <code>javax.sql.DataSource</code> API). This package is now known
694 as the "JDBC Optional Package".</li>
刘洪青6266f992017-05-15 21:21:03 +0800695 <li><a href="http://www.oracle.com/technetwork/java/javaee/overview/index.htm">
696 http://www.oracle.com/technetwork/java/javaee/overview/index.htm</a> -
697 The Java EE Platform Specification (covers the JDBC facilities that
698 all Java EE platforms must provide to applications).</li>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800699 </ul>
700
701 <p><strong>NOTE</strong> - The default data source support in Tomcat
702 is based on the <strong>DBCP</strong> connection pool from the
703 <a href="http://commons.apache.org/">Commons</a>
704 project. However, it is possible to use any other connection pool
705 that implements <code>javax.sql.DataSource</code>, by writing your
706 own custom resource factory, as described
刘洪青6266f992017-05-15 21:21:03 +0800707 <a href="#Adding_Custom_Resource_Factories">below</a>.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800708
刘洪青6266f992017-05-15 21:21:03 +0800709 <h5>1. Install Your JDBC Driver</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800710
711 <p>Use of the <em>JDBC Data Sources</em> JNDI Resource Factory requires
712 that you make an appropriate JDBC driver available to both Tomcat internal
713 classes and to your web application. This is most easily accomplished by
714 installing the driver's JAR file(s) into the
715 <code>$CATALINA_HOME/lib</code> directory, which makes the driver
716 available both to the resource factory and to your application.</p>
717
刘洪青6266f992017-05-15 21:21:03 +0800718 <h5>2. Declare Your Resource Requirements</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800719
720 <p>Next, modify the web application deployment descriptor
721 (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
722 which you will look up preconfigured data source. By convention, all such
723 names should resolve to the <code>jdbc</code> subcontext (relative to the
724 standard <code>java:comp/env</code> naming context that is the root of
725 all provided resource factories. A typical <code>web.xml</code> entry
726 might look like this:</p>
刘洪青6266f992017-05-15 21:21:03 +0800727<div class="codeBox"><pre><code>&lt;resource-ref&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800728 &lt;description&gt;
729 Resource reference to a factory for java.sql.Connection
730 instances that may be used for talking to a particular
731 database that is configured in the &lt;Context&gt;
刘洪青6266f992017-05-15 21:21:03 +0800732 configuration for the web application.
Hongqing Liufd5ee812014-05-10 16:32:51 +0800733 &lt;/description&gt;
734 &lt;res-ref-name&gt;
735 jdbc/EmployeeDB
736 &lt;/res-ref-name&gt;
737 &lt;res-type&gt;
738 javax.sql.DataSource
739 &lt;/res-type&gt;
740 &lt;res-auth&gt;
741 Container
742 &lt;/res-auth&gt;
刘洪青6266f992017-05-15 21:21:03 +0800743&lt;/resource-ref&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800744
745 <p><strong>WARNING</strong> - Be sure you respect the element ordering
746 that is required by the DTD for web application deployment descriptors!
747 See the
748 <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
749 Specification</a> for details.</p>
750
刘洪青6266f992017-05-15 21:21:03 +0800751 <h5>3. Code Your Application's Use Of This Resource</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800752
753 <p>A typical use of this resource reference might look like this:</p>
刘洪青6266f992017-05-15 21:21:03 +0800754<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
Hongqing Liufd5ee812014-05-10 16:32:51 +0800755Context envCtx = (Context) initCtx.lookup("java:comp/env");
756DataSource ds = (DataSource)
757 envCtx.lookup("jdbc/EmployeeDB");
758
759Connection conn = ds.getConnection();
760... use this connection to access the database ...
刘洪青6266f992017-05-15 21:21:03 +0800761conn.close();</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800762
763 <p>Note that the application uses the same resource reference name that was
764 declared in the web application deployment descriptor. This is matched up
765 against the resource factory that is configured in the
766 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
767 the web application as described below.</p>
768
刘洪青6266f992017-05-15 21:21:03 +0800769 <h5>4. Configure Tomcat's Resource Factory</h5>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800770
771 <p>To configure Tomcat's resource factory, add an element like this to the
772 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
773 the web application.</p>
774
刘洪青6266f992017-05-15 21:21:03 +0800775<div class="codeBox"><pre><code>&lt;Context ...&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800776 ...
777 &lt;Resource name="jdbc/EmployeeDB"
778 auth="Container"
779 type="javax.sql.DataSource"
780 username="dbusername"
781 password="dbpassword"
782 driverClassName="org.hsql.jdbcDriver"
783 url="jdbc:HypersonicSQL:database"
784 maxActive="8"
785 maxIdle="4"/&gt;
786 ...
刘洪青6266f992017-05-15 21:21:03 +0800787&lt;/Context&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800788
789 <p>Note that the resource name (here, <code>jdbc/EmployeeDB</code>) must
790 match the value specified in the web application deployment descriptor.</p>
791
792 <p>This example assumes that you are using the HypersonicSQL database
793 JDBC driver. Customize the <code>driverClassName</code> and
794 <code>driverName</code> parameters to match your actual database's
795 JDBC driver and connection URL.</p>
796
797 <p>The configuration properties for Tomcat's standard data source
798 resource factory
799 (<code>org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory</code>) are
800 as follows:</p>
801 <ul>
802 <li><strong>driverClassName</strong> - Fully qualified Java class name
803 of the JDBC driver to be used.</li>
804 <li><strong>username</strong> - Database username to be passed to our
805 JDBC driver.</li>
806 <li><strong>password</strong> - Database password to be passed to our
807 JDBC driver.</li>
808 <li><strong>url</strong> - Connection URL to be passed to our JDBC driver.
809 (For backwards compatibility, the property <code>driverName</code>
810 is also recognized.)</li>
811 <li><strong>initialSize</strong> - The initial number of connections
812 that will be created in the pool during pool initialization. Default: 0</li>
813 <li><strong>maxActive</strong> - The maximum number of connections
814 that can be allocated from this pool at the same time. Default: 8</li>
815 <li><strong>minIdle</strong> - The minimum number of connections that
816 will sit idle in this pool at the same time. Default: 0</li>
817 <li><strong>maxIdle</strong> - The maximum number of connections that
818 can sit idle in this pool at the same time. Default: 8</li>
819 <li><strong>maxWait</strong> - The maximum number of milliseconds that the
820 pool will wait (when there are no available connections) for a
821 connection to be returned before throwing an exception. Default: -1 (infinite)</li>
822 </ul>
823 <p>Some additional properties handle connection validation:</p>
824 <ul>
825 <li><strong>validationQuery</strong> - SQL query that can be used by the
826 pool to validate connections before they are returned to the
827 application. If specified, this query MUST be an SQL SELECT
828 statement that returns at least one row.</li>
829 <li><strong>validationQueryTimeout</strong> - Timeout in seconds
830 for the validation query to return. Default: -1 (infinite)</li>
831 <li><strong>testOnBorrow</strong> - true or false: whether a connection
832 should be validated using the validation query each time it is
833 borrowed from the pool. Default: true</li>
834 <li><strong>testOnReturn</strong> - true or false: whether a connection
835 should be validated using the validation query each time it is
836 returned to the pool. Default: false</li>
837 </ul>
838 <p>The optional evictor thread is responsible for shrinking the pool
刘洪青6266f992017-05-15 21:21:03 +0800839 by removing any connections which are idle for a long time. The evictor
Hongqing Liufd5ee812014-05-10 16:32:51 +0800840 does not respect <code>minIdle</code>. Note that you do not need to
841 activate the evictor thread if you only want the pool to shrink according
842 to the configured <code>maxIdle</code> property.</p>
843 <p>The evictor is disabled by default and can be configured using
844 the following properties:</p>
845 <ul>
846 <li><strong>timeBetweenEvictionRunsMillis</strong> - The number of
847 milliseconds between consecutive runs of the evictor.
848 Default: -1 (disabled)</li>
849 <li><strong>numTestsPerEvictionRun</strong> - The number of connections
刘洪青6266f992017-05-15 21:21:03 +0800850 that will be checked for idleness by the evictor during each
Hongqing Liufd5ee812014-05-10 16:32:51 +0800851 run of the evictor. Default: 3</li>
852 <li><strong>minEvictableIdleTimeMillis</strong> - The idle time in
853 milliseconds after which a connection can be removed from the pool
854 by the evictor. Default: 30*60*1000 (30 minutes)</li>
855 <li><strong>testWhileIdle</strong> - true or false: whether a connection
856 should be validated by the evictor thread using the validation query
857 while sitting idle in the pool. Default: false</li>
858 </ul>
859 <p>Another optional feature is the removal of abandoned connections.
860 A connection is called abandoned if the application does not return it
861 to the pool for a long time. The pool can close such connections
862 automatically and remove them from the pool. This is a workaround
863 for applications leaking connections.</p>
864 <p>The abandoning feature is disabled by default and can be configured
865 using the following properties:</p>
866 <ul>
867 <li><strong>removeAbandoned</strong> - true or false: whether to
868 remove abandoned connections from the pool. Default: false</li>
869 <li><strong>removeAbandonedTimeout</strong> - The number of
870 seconds after which a borrowed connection is assumed to be abandoned.
871 Default: 300</li>
872 <li><strong>logAbandoned</strong> - true or false: whether to log
873 stack traces for application code which abandoned a statement
874 or connection. This adds serious overhead. Default: false</li>
875 </ul>
876 <p>Finally there are various properties that allow further fine tuning
877 of the pool behaviour:</p>
878 <ul>
879 <li><strong>defaultAutoCommit</strong> - true or false: default
880 auto-commit state of the connections created by this pool.
881 Default: true</li>
882 <li><strong>defaultReadOnly</strong> - true or false: default
883 read-only state of the connections created by this pool.
884 Default: false</li>
885 <li><strong>defaultTransactionIsolation</strong> - This sets the
886 default transaction isolation level. Can be one of
887 <code>NONE</code>, <code>READ_COMMITTED</code>,
888 <code>READ_UNCOMMITTED</code>, <code>REPEATABLE_READ</code>,
889 <code>SERIALIZABLE</code>. Default: no default set</li>
890 <li><strong>poolPreparedStatements</strong> - true or false: whether to
891 pool PreparedStatements and CallableStatements. Default: false</li>
892 <li><strong>maxOpenPreparedStatements</strong> - The maximum number of open
893 statements that can be allocated from the statement pool at the same time.
894 Default: -1 (unlimited)</li>
895 <li><strong>defaultCatalog</strong> - The name of the default catalog.
896 Default: not set</li>
897 <li><strong>connectionInitSqls</strong> - A list of SQL statements
898 run once after a Connection is created. Separate multiple statements
899 by semicolons (<code>;</code>). Default: no statement</li>
900 <li><strong>connectionProperties</strong> - A list of driver specific
901 properties passed to the driver for creating connections. Each
902 property is given as <code>name=value</code>, multiple properties
903 are separated by semicolons (<code>;</code>). Default: no properties</li>
904 <li><strong>accessToUnderlyingConnectionAllowed</strong> - true or false: whether
905 accessing the underlying connections is allowed. Default: false</li>
906 </ul>
907 <p>For more details, please refer to the commons-dbcp documentation.</p>
908
909 </blockquote></td></tr></table>
910
911</blockquote></td></tr></table><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="Adding Custom Resource Factories"><!--()--></a><a name="Adding_Custom_Resource_Factories"><strong>Adding Custom Resource Factories</strong></a></font></td></tr><tr><td><blockquote>
912
913 <p>If none of the standard resource factories meet your needs, you can write
刘洪青6266f992017-05-15 21:21:03 +0800914 your own factory and integrate it into Tomcat, and then configure the use
Hongqing Liufd5ee812014-05-10 16:32:51 +0800915 of this factory in the
916 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
917 the web application. In the example below, we will create a factory that only
918 knows how to create <code>com.mycompany.MyBean</code> beans from the
刘洪青6266f992017-05-15 21:21:03 +0800919 <a href="#Generic_JavaBean_Resources">Generic JavaBean Resources</a> example
Hongqing Liufd5ee812014-05-10 16:32:51 +0800920 above.</p>
921
刘洪青6266f992017-05-15 21:21:03 +0800922 <h4>1. Write A Resource Factory Class</h4>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800923
924 <p>You must write a class that implements the JNDI service provider
刘洪青6266f992017-05-15 21:21:03 +0800925 <code>javax.naming.spi.ObjectFactory</code> interface. Every time your
Hongqing Liufd5ee812014-05-10 16:32:51 +0800926 web application calls <code>lookup()</code> on a context entry that is
刘洪青6266f992017-05-15 21:21:03 +0800927 bound to this factory (assuming that the factory is configured with
928 <code>singleton="false"</code>), the
929 <code>getObjectInstance()</code> method is called, with the following
930 arguments:</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800931 <ul>
932 <li><strong>Object obj</strong> - The (possibly null) object containing
933 location or reference information that can be used in creating an object.
934 For Tomcat, this will always be an object of type
935 <code>javax.naming.Reference</code>, which contains the class name of
936 this factory class, as well as the configuration properties (from the
937 <a href="config/context.html"><code>&lt;Context&gt;</code></a> for the
938 web application) to use in creating objects to be returned.</li>
939 <li><strong>Name name</strong> - The name to which this factory is bound
940 relative to <code>nameCtx</code>, or <code>null</code> if no name
941 is specified.</li>
942 <li><strong>Context nameCtx</strong> - The context relative to which the
943 <code>name</code> parameter is specified, or <code>null</code> if
944 <code>name</code> is relative to the default initial context.</li>
945 <li><strong>Hashtable environment</strong> - The (possibly null)
946 environment that is used in creating this object. This is generally
947 ignored in Tomcat object factories.</li>
948 </ul>
949
950 <p>To create a resource factory that knows how to produce <code>MyBean</code>
951 instances, you might create a class like this:</p>
952
刘洪青6266f992017-05-15 21:21:03 +0800953<div class="codeBox"><pre><code>package com.mycompany;
Hongqing Liufd5ee812014-05-10 16:32:51 +0800954
955import java.util.Enumeration;
956import java.util.Hashtable;
957import javax.naming.Context;
958import javax.naming.Name;
959import javax.naming.NamingException;
960import javax.naming.RefAddr;
961import javax.naming.Reference;
962import javax.naming.spi.ObjectFactory;
963
964public class MyBeanFactory implements ObjectFactory {
965
966 public Object getObjectInstance(Object obj,
刘洪青6266f992017-05-15 21:21:03 +0800967 Name name2, Context nameCtx, Hashtable environment)
Hongqing Liufd5ee812014-05-10 16:32:51 +0800968 throws NamingException {
969
970 // Acquire an instance of our specified bean class
971 MyBean bean = new MyBean();
972
973 // Customize the bean properties from our attributes
974 Reference ref = (Reference) obj;
975 Enumeration addrs = ref.getAll();
976 while (addrs.hasMoreElements()) {
977 RefAddr addr = (RefAddr) addrs.nextElement();
978 String name = addr.getType();
979 String value = (String) addr.getContent();
980 if (name.equals("foo")) {
981 bean.setFoo(value);
982 } else if (name.equals("bar")) {
983 try {
984 bean.setBar(Integer.parseInt(value));
985 } catch (NumberFormatException e) {
986 throw new NamingException("Invalid 'bar' value " + value);
987 }
988 }
989 }
990
991 // Return the customized instance
992 return (bean);
993
994 }
995
刘洪青6266f992017-05-15 21:21:03 +0800996}</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +0800997
998 <p>In this example, we are unconditionally creating a new instance of
999 the <code>com.mycompany.MyBean</code> class, and populating its properties
1000 based on the parameters included in the <code>&lt;ResourceParams&gt;</code>
1001 element that configures this factory (see below). You should note that any
1002 parameter named <code>factory</code> should be skipped - that parameter is
1003 used to specify the name of the factory class itself (in this case,
1004 <code>com.mycompany.MyBeanFactory</code>) rather than a property of the
1005 bean being configured.</p>
1006
1007 <p>For more information about <code>ObjectFactory</code>, see the
刘洪青6266f992017-05-15 21:21:03 +08001008 <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/index.html">
1009 JNDI Service Provider Interface (SPI) Specification</a>.</p>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001010
1011 <p>You will need to compile this class against a class path that includes
1012 all of the JAR files in the <code>$CATALINA_HOME/lib</code> directory. When you are through,
1013 place the factory class (and the corresponding bean class) unpacked under
1014 <code>$CATALINA_HOME/lib</code>, or in a JAR file inside
1015 <code>$CATALINA_HOME/lib</code>. In this way, the required class
1016 files are visible to both Catalina internal resources and your web
1017 application.</p>
1018
刘洪青6266f992017-05-15 21:21:03 +08001019 <h4>2. Declare Your Resource Requirements</h4>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001020
1021 <p>Next, modify your web application deployment descriptor
1022 (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under which
1023 you will request new instances of this bean. The simplest approach is
1024 to use a <code>&lt;resource-env-ref&gt;</code> element, like this:</p>
1025
刘洪青6266f992017-05-15 21:21:03 +08001026<div class="codeBox"><pre><code>&lt;resource-env-ref&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +08001027 &lt;description&gt;
1028 Object factory for MyBean instances.
1029 &lt;/description&gt;
1030 &lt;resource-env-ref-name&gt;
1031 bean/MyBeanFactory
1032 &lt;/resource-env-ref-name&gt;
1033 &lt;resource-env-ref-type&gt;
1034 com.mycompany.MyBean
1035 &lt;/resource-env-ref-type&gt;
刘洪青6266f992017-05-15 21:21:03 +08001036&lt;/resource-env-ref&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001037
1038 <p><strong>WARNING</strong> - Be sure you respect the element ordering
1039 that is required by the DTD for web application deployment descriptors!
1040 See the
1041 <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
1042 Specification</a> for details.</p>
1043
刘洪青6266f992017-05-15 21:21:03 +08001044 <h4>3. Code Your Application's Use Of This Resource</h4>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001045
1046 <p>A typical use of this resource environment reference might look
1047 like this:</p>
1048
刘洪青6266f992017-05-15 21:21:03 +08001049<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
Hongqing Liufd5ee812014-05-10 16:32:51 +08001050Context envCtx = (Context) initCtx.lookup("java:comp/env");
1051MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
1052
1053writer.println("foo = " + bean.getFoo() + ", bar = " +
刘洪青6266f992017-05-15 21:21:03 +08001054 bean.getBar());</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001055
刘洪青6266f992017-05-15 21:21:03 +08001056 <h4>4. Configure Tomcat's Resource Factory</h4>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001057
1058 <p>To configure Tomcat's resource factory, add an elements like this to the
1059 <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
1060 this web application.</p>
1061
刘洪青6266f992017-05-15 21:21:03 +08001062<div class="codeBox"><pre><code>&lt;Context ...&gt;
Hongqing Liufd5ee812014-05-10 16:32:51 +08001063 ...
1064 &lt;Resource name="bean/MyBeanFactory" auth="Container"
1065 type="com.mycompany.MyBean"
1066 factory="com.mycompany.MyBeanFactory"
刘洪青6266f992017-05-15 21:21:03 +08001067 singleton="false"
Hongqing Liufd5ee812014-05-10 16:32:51 +08001068 bar="23"/&gt;
1069 ...
刘洪青6266f992017-05-15 21:21:03 +08001070&lt;/Context&gt;</code></pre></div>
Hongqing Liufd5ee812014-05-10 16:32:51 +08001071
1072 <p>Note that the resource name (here, <code>bean/MyBeanFactory</code>
1073 must match the value specified in the web application deployment
1074 descriptor. We are also initializing the value of the <code>bar</code>
1075 property, which will cause <code>setBar(23)</code> to be called before
1076 the new bean is returned. Because we are not initializing the
1077 <code>foo</code> property (although we could have), the bean will
1078 contain whatever default value is set up by its constructor.</p>
1079
1080 <p>You will also note that, from the application developer's perspective,
1081 the declaration of the resource environment reference, and the programming
1082 used to request new instances, is identical to the approach used for the
1083 <em>Generic JavaBean Resources</em> example. This illustrates one of the
1084 advantages of using JNDI resources to encapsulate functionality - you can
1085 change the underlying implementation without necessarily having to
1086 modify applications using the resources, as long as you maintain
1087 compatible APIs.</p>
1088
刘洪青6266f992017-05-15 21:21:03 +08001089</blockquote></td></tr></table></td></tr><tr class="noPrint"><td width="20%" valign="top" nowrap class="noPrint"></td><td width="80%" valign="top" align="left"><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="#525D76"><font color="#ffffff" face="arial,helvetica.sanserif"><a name="comments_section" id="comments_section"><strong>Comments</strong></a></font></td></tr><tr><td><blockquote><p class="notice"><strong>Notice: </strong>This comments section collects your suggestions
1090 on improving documentation for Apache Tomcat.<br><br>
1091 If you have trouble and need help, read
1092 <a href="http://tomcat.apache.org/findhelp.html">Find Help</a> page
1093 and ask your question on the tomcat-users
1094 <a href="http://tomcat.apache.org/lists.html">mailing list</a>.
1095 Do not ask such questions here. This is not a Q&amp;A section.<br><br>
1096 The Apache Comments System is explained <a href="./comments.html">here</a>.
1097 Comments may be removed by our moderators if they are either
1098 implemented or considered invalid/off-topic.</p><script type="text/javascript"><!--//--><![CDATA[//><!--
1099 var comments_shortname = 'tomcat';
1100 var comments_identifier = 'http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html';
1101 (function(w, d) {
1102 if (w.location.hostname.toLowerCase() == "tomcat.apache.org") {
1103 d.write('<div id="comments_thread"><\/div>');
1104 var s = d.createElement('script');
1105 s.type = 'text/javascript';
1106 s.async = true;
1107 s.src = 'https://comments.apache.org/show_comments.lua?site=' + comments_shortname + '&page=' + comments_identifier;
1108 (d.getElementsByTagName('head')[0] || d.getElementsByTagName('body')[0]).appendChild(s);
1109 }
1110 else {
1111 d.write('<div id="comments_thread"><strong>Comments are disabled for this page at the moment.<\/strong><\/div>');
1112 }
1113 })(window, document);
1114 //--><!]]></script></blockquote></td></tr></table></td></tr><!--FOOTER SEPARATOR--><tr><td colspan="2"><hr noshade size="1"></td></tr><!--PAGE FOOTER--><tr><td colspan="2"><div align="center"><font color="#525D76" size="-1"><em>
1115 Copyright &copy; 1999-2017, Apache Software Foundation
Hongqing Liufd5ee812014-05-10 16:32:51 +08001116 </em></font></div></td></tr></table></body></html>