Subversion Repositories Integrator Subversion

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
771 blopes 1
<!DOCTYPE html SYSTEM "about:legacy-compat">
2
<html lang="en"><head><META http-equiv="Content-Type" content="text/html; charset=UTF-8"><link href="./images/docs-stylesheet.css" rel="stylesheet" type="text/css"><title>Apache Tomcat 9 (9.0.112) - JNDI Resources How-To</title></head><body><div id="wrapper"><header><div id="header"><div><div><div class="logo noPrint"><a href="https://tomcat.apache.org/"><img alt="Tomcat Home" src="./images/tomcat.png"></a></div><div style="height: 1px;"></div><div class="asfLogo noPrint"><a href="https://www.apache.org/" target="_blank"><img src="./images/asf-logo.svg" alt="The Apache Software Foundation" style="width: 266px; height: 83px;"></a></div><h1>Apache Tomcat 9</h1><div class="versionInfo">
3
            Version 9.0.112,
4
            <time datetime="2025-11-06">Nov 6 2025</time></div><div style="height: 1px;"></div><div style="clear: left;"></div></div></div></div></header><div id="middle"><div><div id="mainLeft" class="noprint"><div><nav><div><h2>Links</h2><ul><li><a href="index.html">Docs Home</a></li><li><a href="https://cwiki.apache.org/confluence/display/TOMCAT/FAQ">FAQ</a></li></ul></div><div><h2>User Guide</h2><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="host-manager-howto.html">6) Host Manager</a></li><li><a href="realm-howto.html">7) Realms and AAA</a></li><li><a href="security-manager-howto.html">8) Security Manager</a></li><li><a href="jndi-resources-howto.html">9) JNDI Resources</a></li><li><a href="jndi-datasource-examples-howto.html">10) JDBC DataSources</a></li><li><a href="class-loader-howto.html">11) Classloading</a></li><li><a href="jasper-howto.html">12) JSPs</a></li><li><a href="ssl-howto.html">13) SSL/TLS</a></li><li><a href="ssi-howto.html">14) SSI</a></li><li><a href="cgi-howto.html">15) CGI</a></li><li><a href="proxy-howto.html">16) Proxy Support</a></li><li><a href="mbeans-descriptors-howto.html">17) MBeans Descriptors</a></li><li><a href="default-servlet.html">18) Default Servlet</a></li><li><a href="cluster-howto.html">19) Clustering</a></li><li><a href="balancer-howto.html">20) Load Balancer</a></li><li><a href="connectors.html">21) Connectors</a></li><li><a href="monitoring.html">22) Monitoring and Management</a></li><li><a href="logging.html">23) Logging</a></li><li><a href="apr.html">24) APR/Native</a></li><li><a href="virtual-hosting-howto.html">25) Virtual Hosting</a></li><li><a href="aio.html">26) Advanced IO</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><li><a href="rewrite.html">33) Rewrite</a></li><li><a href="cdi.html">34) CDI 2 and JAX-RS</a></li><li><a href="graal.html">35) AOT/GraalVM Support</a></li></ul></div><div><h2>Reference</h2><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 4.0 Javadocs</a></li><li><a href="jspapi/index.html">JSP 2.3 Javadocs</a></li><li><a href="elapi/index.html">EL 3.0 Javadocs</a></li><li><a href="websocketapi/index.html">WebSocket 1.1 Javadocs</a></li><li><a href="jaspicapi/index.html">JASPIC 1.1 Javadocs</a></li><li><a href="annotationapi/index.html">Common Annotations 1.3 Javadocs</a></li><li><a href="https://tomcat.apache.org/connectors-doc/">JK 1.2 Documentation</a></li></ul></div><div><h2>Apache Tomcat Development</h2><ul><li><a href="building.html">Building</a></li><li><a href="changelog.html">Changelog</a></li><li><a href="https://cwiki.apache.org/confluence/display/TOMCAT/Tomcat+Versions">Status</a></li><li><a href="developers.html">Developers</a></li><li><a href="architecture/index.html">Architecture</a></li><li><a href="tribes/introduction.html">Tribes</a></li></ul></div></nav></div></div><div id="mainRight"><div id="content"><h2>JNDI Resources How-To</h2><h3 id="Table_of_Contents">Table of Contents</h3><div class="text">
5
<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="#Memory_UserDatabase_Resources">Memory UserDatabase Resources</a></li><li><a href="#DataSource_UserDatabase_Resources">DataSource 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>
6
</div><h3 id="Introduction">Introduction</h3><div class="text">
7
 
8
<p>Tomcat provides a JNDI <strong>InitialContext</strong> implementation
9
instance for each web application running under it, in a manner that is
10
compatible with those provided by a
11
<a href="http://www.oracle.com/technetwork/java/javaee/overview/index.html">
12
Java Enterprise Edition</a> application server. The Java EE standard provides
13
a standard set of elements in the <code>/WEB-INF/web.xml</code> file to
14
reference/define resources.</p>
15
 
16
<p>See the following Specifications for more information about programming APIs
17
for JNDI, and for the features supported by Java Enterprise Edition (Java EE)
18
servers, which Tomcat emulates for the services that it provides:</p>
19
<ul>
20
<li><a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/index.html">
21
    Java Naming and Directory Interface</a> (included in JDK 1.4 onwards)</li>
22
<li><a href="http://www.oracle.com/technetwork/java/javaee/documentation/index.html">
23
    Java EE Platform Specification</a> (in particular, see Chapter 5 on <em>Naming</em>)</li>
24
</ul>
25
 
26
</div><h3 id="web.xml_configuration">web.xml configuration</h3><div class="text">
27
 
28
<p>The following elements may be used in the web application deployment
29
descriptor (<code>/WEB-INF/web.xml</code>) of your web application to define
30
resources:</p>
31
<ul>
32
<li><code><strong>&lt;env-entry&gt;</strong></code> - Environment entry, a
33
    single-value parameter that can be used to configure how the application
34
    will operate.</li>
35
<li><code><strong>&lt;resource-ref&gt;</strong></code> - Resource reference,
36
    which is typically to an object factory for resources such as a JDBC
37
    <code>DataSource</code>, a JavaMail <code>Session</code>, or custom
38
    object factories configured into Tomcat.</li>
39
<li><code><strong>&lt;resource-env-ref&gt;</strong></code> - Resource
40
    environment reference, a new variation of <code>resource-ref</code>
41
    added in Servlet 2.4 that is simpler to configure for resources
42
    that do not require authentication information.</li>
43
</ul>
44
 
45
<p>Providing that Tomcat is able to identify an appropriate resource factory to
46
use to create the resource and that no further configuration information is
47
required, Tomcat will use the information in <code>/WEB-INF/web.xml</code> to
48
create the resource.</p>
49
 
50
<p>Tomcat provides a number of Tomcat specific options for JNDI resources that
51
cannot be specified in web.xml. These include <code>closeMethod</code> that
52
enables faster cleaning-up of JNDI resources when a web application stops and
53
<code>singleton</code> that controls whether or not a new instance of the
54
resource is created for every JNDI lookup. To use these configuration options
55
the resource must be specified in a web application's
56
<a href="config/context.html"><code>&lt;Context&gt;</code></a> element or in the
57
<a href="config/globalresources.html">
58
<code><strong>&lt;GlobalNamingResources&gt;</strong></code></a> element of
59
<code>$CATALINA_BASE/conf/server.xml</code>.</p>
60
 
61
</div><h3 id="context.xml_configuration">context.xml configuration</h3><div class="text">
62
 
63
<p>If Tomcat is unable to identify the appropriate resource factory and/or
64
additional configuration information is required, additional Tomcat specific
65
configuration must be specified before Tomcat can create the resource.
66
Tomcat specific resource configuration is entered in
67
the <a href="config/context.html"><code>&lt;Context&gt;</code></a> elements that
68
can be specified in either <code>$CATALINA_BASE/conf/server.xml</code> or,
69
preferably, the per-web-application context XML file
70
(<code>META-INF/context.xml</code>).</p>
71
 
72
<p>Tomcat specific resource configuration is performed using the following
73
elements in the <a href="config/context.html"><code>&lt;Context&gt;</code></a>
74
element:</p>
75
 
76
<ul>
77
<li><a href="config/context.html#Environment_Entries">&lt;Environment&gt;</a> -
78
    Configure names and values for scalar environment entries that will be
79
    exposed to the web application through the JNDI
80
    <code>InitialContext</code> (equivalent to the inclusion of an
81
    <code>&lt;env-entry&gt;</code> element in the web application
82
    deployment descriptor).</li>
83
<li><a href="config/context.html#Resource_Definitions">&lt;Resource&gt;</a> -
84
    Configure the name and data type of a resource made available to the
85
    application (equivalent to the inclusion of a
86
    <code>&lt;resource-ref&gt;</code> element in the web application
87
    deployment descriptor).</li>
88
<li><a href="config/context.html#Resource_Links">&lt;ResourceLink&gt;</a> -
89
    Add a link to a resource defined in the global JNDI context. Use resource
90
    links to give a web application access to a resource defined in
91
    the <a href="config/globalresources.html">&lt;GlobalNamingResources&gt;</a>
92
    child element of the <a href="config/server.html">&lt;Server&gt;</a>
93
    element.</li>
94
<li><a href="config/context.html#Transaction">&lt;Transaction&gt;</a> -
95
    Add a resource factory for instantiating the UserTransaction object
96
    instance that is available at <code>java:comp/UserTransaction</code>.</li>
97
 
98
</ul>
99
 
100
<p>Any number of these elements may be nested inside a
101
<a href="config/context.html"><code>&lt;Context&gt;</code></a> element and will
102
be associated only with that particular web application.</p>
103
 
104
<p>If a resource has been defined in a
105
<a href="config/context.html"><code>&lt;Context&gt;</code></a> element it is not
106
necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
107
However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
108
to document the resource requirements for the web application.</p>
109
 
110
<p>Where the same resource name has been defined for a
111
<code>&lt;env-entry&gt;</code> element included in the web application
112
deployment descriptor (<code>/WEB-INF/web.xml</code>) and in an
113
<code>&lt;Environment&gt;</code> element as part of the
114
<a href="config/context.html"><code>&lt;Context&gt;</code></a> element for the
115
web application, the values in the deployment descriptor will take precedence
116
<strong>only</strong> if allowed by the corresponding
117
<code>&lt;Environment&gt;</code> element (by setting the <code>override</code>
118
attribute to "true").</p>
119
 
120
</div><h3 id="Global_configuration">Global configuration</h3><div class="text">
121
 
122
<p>Tomcat maintains a separate namespace of global resources for the
123
entire server.  These are configured in the
124
<a href="config/globalresources.html">
125
<code><strong>&lt;GlobalNamingResources&gt;</strong></code></a> element of
126
<code>$CATALINA_BASE/conf/server.xml</code>. You may expose these resources to
127
web applications by using a
128
<a href="config/context.html#Resource_Links">&lt;ResourceLink&gt;</a> to
129
include it in the per-web-application context.</p>
130
 
131
<p>If a resource has been defined using a
132
<a href="config/context.html#Resource_Links">&lt;ResourceLink&gt;</a>, it is not
133
necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
134
However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
135
to document the resource requirements for the web application.</p>
136
 
137
</div><h3 id="Using_resources">Using resources</h3><div class="text">
138
 
139
<p>The <code>InitialContext</code> is configured as a web application is
140
initially deployed, and is made available to web application components (for
141
read-only access).  All configured entries and resources are placed in
142
the <code>java:comp/env</code> portion of the JNDI namespace, so a typical
143
access to a resource - in this case, to a JDBC <code>DataSource</code> -
144
would look something like this:</p>
145
 
146
<div class="codeBox"><pre><code>// Obtain our environment naming context
147
Context initCtx = new InitialContext();
148
Context envCtx = (Context) initCtx.lookup("java:comp/env");
149
 
150
// Look up our data source
151
DataSource ds = (DataSource)
152
  envCtx.lookup("jdbc/EmployeeDB");
153
 
154
// Allocate and use a connection from the pool
155
Connection conn = ds.getConnection();
156
... use this connection to access the database ...
157
conn.close();</code></pre></div>
158
 
159
</div><h3 id="Tomcat_Standard_Resource_Factories">Tomcat Standard Resource Factories</h3><div class="text">
160
 
161
  <p>Tomcat includes a series of standard resource factories that can
162
  provide services to your web applications, but give you configuration
163
  flexibility (via the
164
  <a href="config/context.html"><code>&lt;Context&gt;</code></a> element)
165
  without modifying the web application or the deployment descriptor. Each
166
  subsection below details the configuration and usage of the standard resource
167
  factories.</p>
168
 
169
  <p>See <a href="#Adding_Custom_Resource_Factories">Adding Custom
170
  Resource Factories</a> for information about how to create, install,
171
  configure, and use your own custom resource factory classes with
172
  Tomcat.</p>
173
 
174
  <p><em>NOTE</em> - Of the standard resource factories, only the
175
  "JDBC Data Source" and "User Transaction" factories are mandated to
176
  be available on other platforms, and then they are required only if
177
  the platform implements the Java Enterprise Edition (Java EE) specs.
178
  All other standard resource factories, plus custom resource factories
179
  that you write yourself, are specific to Tomcat and cannot be assumed
180
  to be available on other containers.</p>
181
 
182
  <div class="subsection"><h4 id="Generic_JavaBean_Resources">Generic JavaBean Resources</h4><div class="text">
183
 
184
    <h5>0.  Introduction</h5>
185
 
186
    <p>This resource factory can be used to create objects of <em>any</em>
187
    Java class that conforms to standard JavaBeans naming conventions (i.e.
188
    it has a zero-arguments constructor, and has property setters that
189
    conform to the setFoo() naming pattern.  The resource factory will
190
    only create a new instance of the appropriate bean class every time a
191
    <code>lookup()</code> for this entry is made if the <code>singleton</code>
192
    attribute of the factory is set to <code>false</code>.</p>
193
 
194
    <p>The steps required to use this facility are described below.</p>
195
 
196
    <h5>1.  Create Your JavaBean Class</h5>
197
 
198
    <p>Create the JavaBean class which will be instantiated each time
199
    that the resource factory is looked up.  For this example, assume
200
    you create a class <code>com.mycompany.MyBean</code>, which looks
201
    like this:</p>
202
 
203
<div class="codeBox"><pre><code>package com.mycompany;
204
 
205
public class MyBean {
206
 
207
  private String foo = "Default Foo";
208
 
209
  public String getFoo() {
210
    return (this.foo);
211
  }
212
 
213
  public void setFoo(String foo) {
214
    this.foo = foo;
215
  }
216
 
217
  private int bar = 0;
218
 
219
  public int getBar() {
220
    return (this.bar);
221
  }
222
 
223
  public void setBar(int bar) {
224
    this.bar = bar;
225
  }
226
 
227
 
228
}</code></pre></div>
229
 
230
  <h5>2.  Declare Your Resource Requirements</h5>
231
 
232
  <p>Next, modify your web application deployment descriptor
233
  (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under which
234
  you will request new instances of this bean.  The simplest approach is
235
  to use a <code>&lt;resource-env-ref&gt;</code> element, like this:</p>
236
 
237
<div class="codeBox"><pre><code>&lt;resource-env-ref&gt;
238
  &lt;description&gt;
239
    Object factory for MyBean instances.
240
  &lt;/description&gt;
241
  &lt;resource-env-ref-name&gt;
242
    bean/MyBeanFactory
243
  &lt;/resource-env-ref-name&gt;
244
  &lt;resource-env-ref-type&gt;
245
    com.mycompany.MyBean
246
  &lt;/resource-env-ref-type&gt;
247
&lt;/resource-env-ref&gt;</code></pre></div>
248
 
249
    <p><strong>WARNING</strong> - Be sure you respect the element ordering
250
    that is required by the DTD for web application deployment descriptors!
251
    See the
252
    <a href="https://cwiki.apache.org/confluence/display/TOMCAT/Specifications">Servlet
253
    Specification</a> for details.</p>
254
 
255
  <h5>3.  Code Your Application's Use Of This Resource</h5>
256
 
257
  <p>A typical use of this resource environment reference might look
258
  like this:</p>
259
 
260
<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
261
Context envCtx = (Context) initCtx.lookup("java:comp/env");
262
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
263
 
264
writer.println("foo = " + bean.getFoo() + ", bar = " +
265
               bean.getBar());</code></pre></div>
266
 
267
    <h5>4.  Configure Tomcat's Resource Factory</h5>
268
 
269
    <p>To configure Tomcat's resource factory, add an element like this to the
270
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
271
    this web application.</p>
272
 
273
<div class="codeBox"><pre><code>&lt;Context ...&gt;
274
  ...
275
  &lt;Resource name="bean/MyBeanFactory" auth="Container"
276
            type="com.mycompany.MyBean"
277
            factory="org.apache.naming.factory.BeanFactory"
278
            bar="23"/&gt;
279
  ...
280
&lt;/Context&gt;</code></pre></div>
281
 
282
    <p>Note that the resource name (here, <code>bean/MyBeanFactory</code>
283
    must match the value specified in the web application deployment
284
    descriptor.  We are also initializing the value of the <code>bar</code>
285
    property, which will cause <code>setBar(23)</code> to be called before
286
    the new bean is returned.  Because we are not initializing the
287
    <code>foo</code> property (although we could have), the bean will
288
    contain whatever default value is set up by its constructor.</p>
289
 
290
    <p>If the bean property is of type <code>String</code>, the BeanFactory
291
    will call the property setter using the provided property value. If the
292
    bean property type is a primitive or a primitive wrapper, the
293
    BeanFactory will convert the value to the appropriate primitive or
294
    primitive wrapper and then use that value when calling the setter. Some
295
    beans have properties with types that cannot automatically be converted
296
    from <code>String</code>. If the bean provides an alternative setter with
297
    the same name that does take a <code>String</code>, the BeanFactory will
298
    attempt to use that setter. If the BeanFactory cannot use the value or
299
    perform an appropriate conversion, setting the property will fail with a
300
    NamingException.</p>
301
 
302
    <p>The <code>forceString</code> property available in earlier Tomcat
303
    releases has been removed as a security hardening measure.</p>
304
 
305
  </div></div>
306
 
307
 
308
  <div class="subsection"><h4 id="Memory_UserDatabase_Resources">Memory UserDatabase Resources</h4><div class="text">
309
 
310
    <h5>0.  Introduction</h5>
311
 
312
    <p>UserDatabase resources are typically configured as global resources for
313
    use by a UserDatabase realm. Tomcat includes a UserDatabaseFactory that
314
    creates UserDatabase resources backed by an XML file - usually
315
    <code>tomcat-users.xml</code>.</p>
316
 
317
    <p>The steps required to set up a global UserDatabase resource are described
318
    below.</p>
319
 
320
    <h5>1. Create/edit the XML file</h5>
321
 
322
    <p>The XML file is typically located at
323
    <code>$CATALINA_BASE/conf/tomcat-users.xml</code> however, you are free to
324
    locate the file anywhere on the file system. It is recommended that the XML
325
    files are placed in <code>$CATALINA_BASE/conf</code>. A typical XML would
326
    look like:</p>
327
 
328
<div class="codeBox"><pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
329
&lt;tomcat-users&gt;
330
  &lt;role rolename="tomcat"/&gt;
331
  &lt;role rolename="role1"/&gt;
332
  &lt;user username="tomcat" password="tomcat" roles="tomcat"/&gt;
333
  &lt;user username="both" password="tomcat" roles="tomcat,role1"/&gt;
334
  &lt;user username="role1" password="tomcat" roles="role1"/&gt;
335
&lt;/tomcat-users&gt;</code></pre></div>
336
 
337
    <h5>2.  Declare Your Resource</h5>
338
 
339
    <p>Next, modify <code>$CATALINA_BASE/conf/server.xml</code> to create the
340
    UserDatabase resource based on your XML file. It should look something like
341
    this:</p>
342
 
343
<div class="codeBox"><pre><code>&lt;Resource name="UserDatabase"
344
          auth="Container"
345
          type="org.apache.catalina.UserDatabase"
346
          description="User database that can be updated and saved"
347
          factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
348
          pathname="conf/tomcat-users.xml"
349
          readonly="false" /&gt;</code></pre></div>
350
 
351
    <p>The <code>pathname</code> attribute can be a URL, an absolute path or a
352
    relative path. If relative, it is relative to <code>$CATALINA_BASE</code>.
353
    </p>
354
 
355
    <p>The <code>readonly</code> attribute is optional and defaults to
356
    <code>true</code> if not supplied. If the XML is writable then it will be
357
    written to when Tomcat starts. <strong>WARNING:</strong> When the file is
358
    written it will inherit the default file permissions for the user Tomcat
359
    is running as. Ensure that these are appropriate to maintain the security
360
    of your installation.</p>
361
 
362
    <p>If referenced in a Realm, the UserDatabase will, by default, monitor
363
    <code>pathname</code> for changes and reload the file if a change in the
364
    last modified time is observed. This can be disabled by setting the
365
    <code>watchSource</code> attribute to <code>false</code>.
366
    </p>
367
 
368
    <h5>3.  Configure the Realm</h5>
369
 
370
    <p>Configure a UserDatabase Realm to use this resource as described in the
371
    <a href="config/realm.html">Realm configuration documentation</a>.</p>
372
 
373
  </div></div>
374
 
375
 
376
  <div class="subsection"><h4 id="DataSource_UserDatabase_Resources">DataSource UserDatabase Resources</h4><div class="text">
377
 
378
    <h5>0.  Introduction</h5>
379
 
380
    <p>Tomcat also include a <code>UserDatabase</code> that uses a
381
    <code>DataSource</code> resource as the backend. The backend resource
382
    must be declared in the same JNDI context as the user database that will use
383
    it.</p>
384
 
385
    <p>The steps required to set up a global UserDatabase resource are described
386
    below.</p>
387
 
388
    <h5>1. Database schema</h5>
389
 
390
    <p>The database schema for the user database is flexible. It can be the same
391
    as the schema used for the <code>DataSourceRealm</code>, with only a table
392
    for users (user name, password), and another one listing the roles
393
    associated with each user. To support the full <code>UserDatabase</code>
394
    features, it must include additional tables for groups, and is
395
    compatible with referential integrity between users, groups and roles.</p>
396
 
397
    <p>The full featured schema with groups and referential integrity
398
    could be:</p>
399
 
400
<div class="codeBox"><pre><code>create table users (
401
  user_name         varchar(32) not null primary key,
402
  user_pass         varchar(64) not null,
403
  user_fullname     varchar(128)
404
  -- Add more attributes as needed
405
);
406
 
407
create table roles (
408
  role_name         varchar(32) not null primary key,
409
  role_description  varchar(128)
410
);
411
 
412
create table groups (
413
  group_name        varchar(32) not null primary key,
414
  group_description varchar(128)
415
);
416
 
417
create table user_roles (
418
  user_name         varchar(32) references users(user_name),
419
  role_name         varchar(32) references roles(role_name),
420
  primary key (user_name, role_name)
421
);
422
 
423
create table user_groups (
424
  user_name         varchar(32) references users(user_name),
425
  group_name        varchar(32) references groups(group_name),
426
  primary key (user_name, group_name)
427
);
428
 
429
create table group_roles (
430
  group_name        varchar(32) references groups(group_name),
431
  role_name         varchar(32) references roles(role_name),
432
  primary key (group_name, role_name)
433
);
434
</code></pre></div>
435
 
436
    <p>The minimal schema without the ability to use groups will be
437
    (it is the same as for the <code>DataSourceRealm</code>):</p>
438
 
439
<div class="codeBox"><pre><code>create table users (
440
  user_name         varchar(32) not null primary key,
441
  user_pass         varchar(64) not null,
442
  -- Add more attributes as needed
443
);
444
 
445
create table user_roles (
446
  user_name         varchar(32),
447
  role_name         varchar(32),
448
  primary key (user_name, role_name)
449
);
450
</code></pre></div>
451
 
452
    <h5>2.  Declare Your Resource</h5>
453
 
454
    <p>Next, modify <code>$CATALINA_BASE/conf/server.xml</code> to create the
455
    UserDatabase resource based on your <code>DataSource</code> and its schema.
456
    It should look something like this:</p>
457
 
458
<div class="codeBox"><pre><code>&lt;Resource name="UserDatabase" auth="Container"
459
              type="org.apache.catalina.UserDatabase"
460
              description="User database that can be updated and saved"
461
              factory="org.apache.catalina.users.DataSourceUserDatabaseFactory"
462
              dataSourceName="jdbc/authority" readonly="false"
463
              userTable="users" userNameCol="user_name" userCredCol="user_pass"
464
              userRoleTable="user_roles" roleNameCol="role_name"
465
              roleTable="roles" groupTable="groups" userGroupTable="user_groups"
466
              groupRoleTable="group_roles" groupNameCol="group_name" /&gt;</code></pre></div>
467
 
468
    <p>The <code>dataSourceName</code> attribute is the JNDI name of the
469
    <code>DataSource</code> that will be the backend for the
470
    <code>UserDatabase</code>. It must be declared in the same JNDI
471
    <code>Context</code> as the <code>UserDatabase</code>. Please refer to the
472
    <a href="#JDBC_Data_Sources"><code>DataSource</code> resources</a>
473
    documentation for further instructions.</p>
474
 
475
    <p>The <code>readonly</code> attribute is optional and defaults to
476
    <code>true</code> if not supplied. If the database is writable then changes
477
    made through the Tomcat management to the <code>UserDatabase</code> can
478
    be persisted to the database using the <code>save</code> operation.</p>
479
 
480
    <p>Alternately, changes can also be made directly to the backend database.
481
    </p>
482
 
483
    <h5>3.  Resource configuration</h5>
484
 
485
    <table class="defaultTable"><tr><th style="width: 15%;">
486
          Attribute
487
        </th><th style="width: 85%;">
488
          Description
489
        </th></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_dataSourceName"><td><strong><code class="attributeName">dataSourceName</code></strong></td><td>
490
        <p>The name of the JNDI JDBC DataSource for this UserDatabase.</p>
491
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_groupNameCol"><td><code class="attributeName">groupNameCol</code></td><td>
492
        <p>Name of the column, in the "groups", "group roles" and "user groups"
493
        tables, that contains the group's name.</p>
494
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_groupRoleTable"><td><code class="attributeName">groupRoleTable</code></td><td>
495
        <p>Name of the "group roles" table, which must contain columns
496
        named by the <code>groupNameCol</code> and <code>roleNameCol</code>
497
        attributes.</p>
498
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_groupTable"><td><code class="attributeName">groupTable</code></td><td>
499
        <p>Name of the "groups" table, which must contain columns named
500
        by the <code>groupNameCol</code> attribute.</p>
501
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_readonly"><td><code class="attributeName">readonly</code></td><td>
502
        <p>If this is set to <code>true</code>, then changes to the
503
        <code>UserDatabase</code> can be persisted to the
504
        <code>DataSource</code> by using the <code>save</code> method.
505
        The default value is <code>true</code>.</p>
506
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_roleAndGroupDescriptionCol"><td><code class="attributeName">roleAndGroupDescriptionCol</code></td><td>
507
        <p>Name of the column, in the "roles" and "groups" tables, that contains
508
        the description for the roles and groups.</p>
509
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_roleNameCol"><td><code class="attributeName">roleNameCol</code></td><td>
510
        <p>Name of the column, in the "roles", "user roles" and "group roles"
511
        tables, which contains a role name assigned to the corresponding
512
        user.</p>
513
        <p>This attribute is <strong>required</strong> in majority of
514
        configurations. See <strong>allRolesMode</strong> attribute of the
515
        associated realm for a rare case when it can be omitted.</p>
516
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_roleTable"><td><code class="attributeName">roleTable</code></td><td>
517
        <p>Name of the "roles" table, which must contain columns named
518
        by the <code>roleNameCol</code> attribute.</p>
519
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_userCredCol"><td><strong><code class="attributeName">userCredCol</code></strong></td><td>
520
        <p>Name of the column, in the "users" table, which contains
521
        the user's credentials (i.e. password).  If a
522
        <code>CredentialHandler</code> is specified, this component
523
        will assume that the passwords have been encoded with the
524
        specified algorithm.  Otherwise, they will be assumed to be
525
        in clear text.</p>
526
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_userGroupTable"><td><code class="attributeName">userGroupTable</code></td><td>
527
        <p>Name of the "user groups" table, which must contain columns
528
        named by the <code>userNameCol</code> and <code>groupNameCol</code>
529
        attributes.</p>
530
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_userNameCol"><td><strong><code class="attributeName">userNameCol</code></strong></td><td>
531
        <p>Name of the column, in the "users", "user groups" and "user roles"
532
        tables, that contains the user's username.</p>
533
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_userFullNameCol"><td><code class="attributeName">userFullNameCol</code></td><td>
534
        <p>Name of the column, in the "users" table, that contains the user's
535
        full name.</p>
536
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_userRoleTable"><td><code class="attributeName">userRoleTable</code></td><td>
537
        <p>Name of the "user roles" table, which must contain columns
538
        named by the <code>userNameCol</code> and <code>roleNameCol</code>
539
        attributes.</p>
540
        <p>This attribute is <strong>required</strong> in majority of
541
        configurations. See <strong>allRolesMode</strong> attribute of the
542
        associated realm for a rare case when it can be omitted.</p>
543
      </td></tr><tr id="Tomcat Standard Resource Factories_DataSource UserDatabase Resources_userTable"><td><strong><code class="attributeName">userTable</code></strong></td><td>
544
        <p>Name of the "users" table, which must contain columns named
545
        by the <code>userNameCol</code> and <code>userCredCol</code>
546
        attributes.</p>
547
      </td></tr></table>
548
 
549
    <h5>4.  Configure the Realm</h5>
550
 
551
    <p>Configure a UserDatabase Realm to use this resource as described in the
552
    <a href="config/realm.html">Realm configuration documentation</a>.</p>
553
 
554
  </div></div>
555
 
556
  <div class="subsection"><h4 id="JavaMail_Sessions">JavaMail Sessions</h4><div class="text">
557
 
558
    <h5>0.  Introduction</h5>
559
 
560
    <p>In many web applications, sending electronic mail messages is a
561
    required part of the system's functionality.  The
562
    <a href="http://www.oracle.com/technetwork/java/javamail/index.html">Java Mail</a> API
563
    makes this process relatively straightforward, but requires many
564
    configuration details that the client application must be aware of
565
    (including the name of the SMTP host to be used for message sending).</p>
566
 
567
    <p>Tomcat includes a standard resource factory that will create
568
    <code>javax.mail.Session</code> session instances for you, already
569
    configured to connect to an SMTP server.
570
    In this way, the application is totally insulated from changes in the
571
    email server configuration environment - it simply asks for, and receives,
572
    a preconfigured session whenever needed.</p>
573
 
574
    <p>The steps required for this are outlined below.</p>
575
 
576
    <h5>1.  Declare Your Resource Requirements</h5>
577
 
578
    <p>The first thing you should do is modify the web application deployment
579
    descriptor (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
580
    which you will look up preconfigured sessions.  By convention, all such
581
    names should resolve to the <code>mail</code> subcontext (relative to the
582
    standard <code>java:comp/env</code> naming context that is the root of
583
    all provided resource factories.  A typical <code>web.xml</code> entry
584
    might look like this:</p>
585
<div class="codeBox"><pre><code>&lt;resource-ref&gt;
586
  &lt;description&gt;
587
    Resource reference to a factory for javax.mail.Session
588
    instances that may be used for sending electronic mail
589
    messages, preconfigured to connect to the appropriate
590
    SMTP server.
591
  &lt;/description&gt;
592
  &lt;res-ref-name&gt;
593
    mail/Session
594
  &lt;/res-ref-name&gt;
595
  &lt;res-type&gt;
596
    javax.mail.Session
597
  &lt;/res-type&gt;
598
  &lt;res-auth&gt;
599
    Container
600
  &lt;/res-auth&gt;
601
&lt;/resource-ref&gt;</code></pre></div>
602
 
603
    <p><strong>WARNING</strong> - Be sure you respect the element ordering
604
    that is required by the DTD for web application deployment descriptors!
605
    See the
606
    <a href="https://cwiki.apache.org/confluence/display/TOMCAT/Specifications">Servlet
607
    Specification</a> for details.</p>
608
 
609
    <h5>2.  Code Your Application's Use Of This Resource</h5>
610
 
611
    <p>A typical use of this resource reference might look like this:</p>
612
<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
613
Context envCtx = (Context) initCtx.lookup("java:comp/env");
614
Session session = (Session) envCtx.lookup("mail/Session");
615
 
616
Message message = new MimeMessage(session);
617
message.setFrom(new InternetAddress(request.getParameter("from")));
618
InternetAddress to[] = new InternetAddress[1];
619
to[0] = new InternetAddress(request.getParameter("to"));
620
message.setRecipients(Message.RecipientType.TO, to);
621
message.setSubject(request.getParameter("subject"));
622
message.setContent(request.getParameter("content"), "text/plain");
623
Transport.send(message);</code></pre></div>
624
 
625
    <p>Note that the application uses the same resource reference name
626
    that was declared in the web application deployment descriptor.  This
627
    is matched up against the resource factory that is configured in the
628
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element
629
    for the web application as described below.</p>
630
 
631
    <h5>3.  Configure Tomcat's Resource Factory</h5>
632
 
633
    <p>To configure Tomcat's resource factory, add an elements like this to the
634
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
635
    this web application.</p>
636
 
637
<div class="codeBox"><pre><code>&lt;Context ...&gt;
638
  ...
639
  &lt;Resource name="mail/Session" auth="Container"
640
            type="javax.mail.Session"
641
            mail.smtp.host="localhost"/&gt;
642
  ...
643
&lt;/Context&gt;</code></pre></div>
644
 
645
    <p>Note that the resource name (here, <code>mail/Session</code>) must
646
    match the value specified in the web application deployment descriptor.
647
    Customize the value of the <code>mail.smtp.host</code> parameter to
648
    point at the server that provides SMTP service for your network.</p>
649
 
650
    <p>Additional resource attributes and values will be converted to properties
651
    and values and passed to
652
    <code>javax.mail.Session.getInstance(java.util.Properties)</code> as part of
653
    the <code>java.util.Properties</code> collection. In addition to the
654
    properties defined in Annex A of the JavaMail specification, individual
655
    providers may also support additional properties.
656
    </p>
657
 
658
    <p>If the resource is configured with a <code>password</code> attribute and
659
    either a <code>mail.smtp.user</code> or <code>mail.user</code> attribute
660
    then Tomcat's resource factory will configure and add a
661
    <code>javax.mail.Authenticator</code> to the mail session.</p>
662
 
663
    <h5>4.  Install the JavaMail libraries</h5>
664
 
665
    <p><a href="http://javamail.java.net/">
666
    Download the JavaMail API</a>.</p>
667
 
668
    <p>Unpackage the distribution and place mail.jar  into $CATALINA_HOME/lib so
669
    that it is available to Tomcat during the initialization of the mail Session
670
    Resource. <strong>Note:</strong> placing this jar in both $CATALINA_HOME/lib
671
    and a  web application's lib folder will cause an error, so ensure you have
672
    it in the $CATALINA_HOME/lib location only.
673
    </p>
674
 
675
    <h5>5.  Restart Tomcat</h5>
676
 
677
    <p>For the additional JAR to be visible to Tomcat, it is necessary for the
678
    Tomcat instance to be restarted.</p>
679
 
680
  </div></div>
681
 
682
  <div class="subsection"><h4 id="JDBC_Data_Sources">JDBC Data Sources</h4><div class="text">
683
 
684
    <h5>0.  Introduction</h5>
685
 
686
    <p>Many web applications need to access a database via a JDBC driver,
687
    to support the functionality required by that application.  The Java EE
688
    Platform Specification requires Java EE Application Servers to make
689
    available a <em>DataSource</em> implementation (that is, a connection
690
    pool for JDBC connections) for this purpose.  Tomcat offers exactly
691
    the same support, so that database-based applications you develop on
692
    Tomcat using this service will run unchanged on any Java EE server.</p>
693
 
694
    <p>For information about JDBC, you should consult the following:</p>
695
    <ul>
696
    <li><a href="http://www.oracle.com/technetwork/java/javase/jdbc/index.html">
697
        http://www.oracle.com/technetwork/java/javase/jdbc/index.html</a> -
698
        Home page for information about Java Database Connectivity.</li>
699
    <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> -
700
        The JDBC 2.1 API Specification.</li>
701
    <li><a href="http://java.sun.com/products/jdbc/jdbc20.stdext.pdf">http://java.sun.com/products/jdbc/jdbc20.stdext.pdf</a> -
702
        The JDBC 2.0 Standard Extension API (including the
703
        <code>javax.sql.DataSource</code> API).  This package is now known
704
        as the "JDBC Optional Package".</li>
705
    <li><a href="http://www.oracle.com/technetwork/java/javaee/overview/index.htm">
706
        http://www.oracle.com/technetwork/java/javaee/overview/index.htm</a> -
707
        The Java EE Platform Specification (covers the JDBC facilities that
708
        all Java EE platforms must provide to applications).</li>
709
    </ul>
710
 
711
    <p><strong>NOTE</strong> - The default data source support in Tomcat
712
    is based on the <strong>DBCP 2</strong> connection pool from the
713
    <a href="https://commons.apache.org/">Commons</a>
714
    project.  However, it is possible to use any other connection pool
715
    that implements <code>javax.sql.DataSource</code>, by writing your
716
    own custom resource factory, as described
717
    <a href="#Adding_Custom_Resource_Factories">below</a>.</p>
718
 
719
    <h5>1.  Install Your JDBC Driver</h5>
720
 
721
    <p>Use of the <em>JDBC Data Sources</em> JNDI Resource Factory requires
722
    that you make an appropriate JDBC driver available to both Tomcat internal
723
    classes and to your web application.  This is most easily accomplished by
724
    installing the driver's JAR file(s) into the
725
    <code>$CATALINA_HOME/lib</code> directory, which makes the driver
726
    available both to the resource factory and to your application.</p>
727
 
728
    <h5>2.  Declare Your Resource Requirements</h5>
729
 
730
    <p>Next, modify the web application deployment descriptor
731
    (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
732
    which you will look up preconfigured data source.  By convention, all such
733
    names should resolve to the <code>jdbc</code> subcontext (relative to the
734
    standard <code>java:comp/env</code> naming context that is the root of
735
    all provided resource factories.  A typical <code>web.xml</code> entry
736
    might look like this:</p>
737
<div class="codeBox"><pre><code>&lt;resource-ref&gt;
738
  &lt;description&gt;
739
    Resource reference to a factory for java.sql.Connection
740
    instances that may be used for talking to a particular
741
    database that is configured in the &lt;Context&gt;
742
    configuration for the web application.
743
  &lt;/description&gt;
744
  &lt;res-ref-name&gt;
745
    jdbc/EmployeeDB
746
  &lt;/res-ref-name&gt;
747
  &lt;res-type&gt;
748
    javax.sql.DataSource
749
  &lt;/res-type&gt;
750
  &lt;res-auth&gt;
751
    Container
752
  &lt;/res-auth&gt;
753
&lt;/resource-ref&gt;</code></pre></div>
754
 
755
    <p><strong>WARNING</strong> - Be sure you respect the element ordering
756
    that is required by the DTD for web application deployment descriptors!
757
    See the
758
    <a href="https://cwiki.apache.org/confluence/display/TOMCAT/Specifications">Servlet
759
    Specification</a> for details.</p>
760
 
761
    <h5>3.  Code Your Application's Use Of This Resource</h5>
762
 
763
    <p>A typical use of this resource reference might look like this:</p>
764
<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
765
Context envCtx = (Context) initCtx.lookup("java:comp/env");
766
DataSource ds = (DataSource)
767
  envCtx.lookup("jdbc/EmployeeDB");
768
 
769
Connection conn = ds.getConnection();
770
... use this connection to access the database ...
771
conn.close();</code></pre></div>
772
 
773
    <p>Note that the application uses the same resource reference name that was
774
    declared in the web application deployment descriptor. This is matched up
775
    against the resource factory that is configured in the
776
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
777
    the web application as described below.</p>
778
 
779
    <h5>4.  Configure Tomcat's Resource Factory</h5>
780
 
781
    <p>To configure Tomcat's resource factory, add an element like this to the
782
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
783
    the web application.</p>
784
 
785
<div class="codeBox"><pre><code>&lt;Context ...&gt;
786
  ...
787
  &lt;Resource name="jdbc/EmployeeDB"
788
            auth="Container"
789
            type="javax.sql.DataSource"
790
            username="dbusername"
791
            password="dbpassword"
792
            driverClassName="org.hsql.jdbcDriver"
793
            url="jdbc:HypersonicSQL:database"
794
            maxTotal="8"
795
            maxIdle="4"/&gt;
796
  ...
797
&lt;/Context&gt;</code></pre></div>
798
 
799
    <p>Note that the resource name (here, <code>jdbc/EmployeeDB</code>) must
800
    match the value specified in the web application deployment descriptor.</p>
801
 
802
    <p>This example assumes that you are using the HypersonicSQL database
803
    JDBC driver.  Customize the <code>driverClassName</code> and
804
    <code>driverName</code> parameters to match your actual database's
805
    JDBC driver and connection URL.</p>
806
 
807
    <p>The configuration properties for Tomcat's standard data source
808
    resource factory
809
    (<code>org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory</code>) are
810
    as follows:</p>
811
    <ul>
812
    <li><strong>driverClassName</strong> - Fully qualified Java class name
813
        of the JDBC driver to be used.</li>
814
    <li><strong>username</strong> - Database username to be passed to our
815
        JDBC driver.</li>
816
    <li><strong>password</strong> - Database password to be passed to our
817
        JDBC driver.</li>
818
    <li><strong>url</strong> - Connection URL to be passed to our JDBC driver.
819
        (For backwards compatibility, the property <code>driverName</code>
820
        is also recognized.)</li>
821
    <li><strong>initialSize</strong> - The initial number of connections
822
        that will be created in the pool during pool initialization. Default: 0</li>
823
    <li><strong>maxTotal</strong> - The maximum number of connections
824
        that can be allocated from this pool at the same time. Default: 8</li>
825
    <li><strong>minIdle</strong> - The minimum number of connections that
826
        will sit idle in this pool at the same time. Default: 0</li>
827
    <li><strong>maxIdle</strong> - The maximum number of connections that
828
        can sit idle in this pool at the same time. Default: 8</li>
829
    <li><strong>maxWaitMillis</strong> - The maximum number of milliseconds that the
830
        pool will wait (when there are no available connections) for a
831
        connection to be returned before throwing an exception. Default: -1 (infinite)</li>
832
    </ul>
833
    <p>Some additional properties handle connection validation:</p>
834
    <ul>
835
    <li><strong>validationQuery</strong> - SQL query that can be used by the
836
        pool to validate connections before they are returned to the
837
        application.  If specified, this query MUST be an SQL SELECT
838
        statement that returns at least one row.</li>
839
    <li><strong>validationQueryTimeout</strong> - Timeout in seconds
840
        for the validation query to return. Default: -1 (infinite)</li>
841
    <li><strong>testOnBorrow</strong> - true or false: whether a connection
842
        should be validated using the validation query each time it is
843
        borrowed from the pool. Default: true</li>
844
    <li><strong>testOnReturn</strong> - true or false: whether a connection
845
        should be validated using the validation query each time it is
846
        returned to the pool. Default: false</li>
847
    </ul>
848
    <p>The optional evictor thread is responsible for shrinking the pool
849
    by removing any connections which are idle for a long time. The evictor
850
    does not respect <code>minIdle</code>. Note that you do not need to
851
    activate the evictor thread if you only want the pool to shrink according
852
    to the configured <code>maxIdle</code> property.</p>
853
    <p>The evictor is disabled by default and can be configured using
854
    the following properties:</p>
855
    <ul>
856
    <li><strong>timeBetweenEvictionRunsMillis</strong> - The number of
857
        milliseconds between consecutive runs of the evictor.
858
        Default: -1 (disabled)</li>
859
    <li><strong>numTestsPerEvictionRun</strong> - The number of connections
860
        that will be checked for idleness by the evictor during each
861
        run of the evictor. Default: 3</li>
862
    <li><strong>minEvictableIdleTimeMillis</strong> - The idle time in
863
        milliseconds after which a connection can be removed from the pool
864
        by the evictor. Default: 30*60*1000 (30 minutes)</li>
865
    <li><strong>testWhileIdle</strong> - true or false: whether a connection
866
        should be validated by the evictor thread using the validation query
867
        while sitting idle in the pool. Default: false</li>
868
    </ul>
869
    <p>Another optional feature is the removal of abandoned connections.
870
    A connection is called abandoned if the application does not return it
871
    to the pool for a long time. The pool can close such connections
872
    automatically and remove them from the pool. This is a workaround
873
    for applications leaking connections.</p>
874
    <p>The abandoning feature is disabled by default and can be configured
875
    using the following properties:</p>
876
    <ul>
877
    <li><strong>removeAbandonedOnBorrow</strong> - true or false: whether to
878
        remove abandoned connections from the pool when a connection is
879
        borrowed. Default: false</li>
880
    <li><strong>removeAbandonedOnMaintenance</strong> - true or false: whether
881
        to remove abandoned connections from the pool during pool maintenance.
882
        Default: false</li>
883
    <li><strong>removeAbandonedTimeout</strong> - The number of
884
        seconds after which a borrowed connection is assumed to be abandoned.
885
        Default: 300</li>
886
    <li><strong>logAbandoned</strong> - true or false: whether to log
887
        stack traces for application code which abandoned a statement
888
        or connection. This adds serious overhead. Default: false</li>
889
    </ul>
890
    <p>Finally there are various properties that allow further fine tuning
891
    of the pool behaviour:</p>
892
    <ul>
893
    <li><strong>defaultAutoCommit</strong> - true or false: default
894
        auto-commit state of the connections created by this pool.
895
        Default: true</li>
896
    <li><strong>defaultReadOnly</strong> - true or false: default
897
        read-only state of the connections created by this pool.
898
        Default: false</li>
899
    <li><strong>defaultTransactionIsolation</strong> - This sets the
900
        default transaction isolation level. Can be one of
901
        <code>NONE</code>, <code>READ_COMMITTED</code>,
902
        <code>READ_UNCOMMITTED</code>, <code>REPEATABLE_READ</code>,
903
        <code>SERIALIZABLE</code>. Default: no default set</li>
904
    <li><strong>poolPreparedStatements</strong> - true or false: whether to
905
        pool PreparedStatements and CallableStatements. Default: false</li>
906
    <li><strong>maxOpenPreparedStatements</strong> - The maximum number of open
907
        statements that can be allocated from the statement pool at the same time.
908
        Default: -1 (unlimited)</li>
909
    <li><strong>defaultCatalog</strong> - The name of the default catalog.
910
        Default: not set</li>
911
    <li><strong>connectionInitSqls</strong> - A list of SQL statements
912
        run once after a Connection is created. Separate multiple statements
913
        by semicolons (<code>;</code>). Default: no statement</li>
914
    <li><strong>connectionProperties</strong> - A list of driver specific
915
        properties passed to the driver for creating connections. Each
916
        property is given as <code>name=value</code>, multiple properties
917
        are separated by semicolons (<code>;</code>). Default: no properties</li>
918
    <li><strong>accessToUnderlyingConnectionAllowed</strong> - true or false: whether
919
        accessing the underlying connections is allowed. Default: false</li>
920
    </ul>
921
    <p>For more details, please refer to the Commons DBCP 2 documentation.</p>
922
 
923
  </div></div>
924
 
925
</div><h3 id="Adding_Custom_Resource_Factories">Adding Custom Resource Factories</h3><div class="text">
926
 
927
  <p>If none of the standard resource factories meet your needs, you can write
928
  your own factory and integrate it into Tomcat, and then configure the use
929
  of this factory in the
930
  <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
931
  the web application. In the example below, we will create a factory that only
932
  knows how to create <code>com.mycompany.MyBean</code> beans from the
933
  <a href="#Generic_JavaBean_Resources">Generic JavaBean Resources</a> example
934
  above.</p>
935
 
936
  <h4>1.  Write A Resource Factory Class</h4>
937
 
938
  <p>You must write a class that implements the JNDI service provider
939
  <code>javax.naming.spi.ObjectFactory</code> interface.  Every time your
940
  web application calls <code>lookup()</code> on a context entry that is
941
  bound to this factory (assuming that the factory is configured with
942
  <code>singleton="false"</code>), the
943
  <code>getObjectInstance()</code> method is called, with the following
944
  arguments:</p>
945
  <ul>
946
  <li><strong>Object obj</strong> - The (possibly null) object containing
947
      location or reference information that can be used in creating an object.
948
      For Tomcat, this will always be an object of type
949
      <code>javax.naming.Reference</code>, which contains the class name of
950
      this factory class, as well as the configuration properties (from the
951
      <a href="config/context.html"><code>&lt;Context&gt;</code></a> for the
952
      web application) to use in creating objects to be returned.</li>
953
  <li><strong>Name name</strong> - The name to which this factory is bound
954
      relative to <code>nameCtx</code>, or <code>null</code> if no name
955
      is specified.</li>
956
  <li><strong>Context nameCtx</strong> - The context relative to which the
957
      <code>name</code> parameter is specified, or <code>null</code> if
958
      <code>name</code> is relative to the default initial context.</li>
959
  <li><strong>Hashtable environment</strong> - The (possibly null)
960
      environment that is used in creating this object.  This is generally
961
      ignored in Tomcat object factories.</li>
962
  </ul>
963
 
964
  <p>To create a resource factory that knows how to produce <code>MyBean</code>
965
  instances, you might create a class like this:</p>
966
 
967
<div class="codeBox"><pre><code>package com.mycompany;
968
 
969
import java.util.Enumeration;
970
import java.util.Hashtable;
971
import javax.naming.Context;
972
import javax.naming.Name;
973
import javax.naming.NamingException;
974
import javax.naming.RefAddr;
975
import javax.naming.Reference;
976
import javax.naming.spi.ObjectFactory;
977
 
978
public class MyBeanFactory implements ObjectFactory {
979
 
980
  public Object getObjectInstance(Object obj,
981
      Name name2, Context nameCtx, Hashtable environment)
982
      throws NamingException {
983
 
984
      // Acquire an instance of our specified bean class
985
      MyBean bean = new MyBean();
986
 
987
      // Customize the bean properties from our attributes
988
      Reference ref = (Reference) obj;
989
      Enumeration addrs = ref.getAll();
990
      while (addrs.hasMoreElements()) {
991
          RefAddr addr = (RefAddr) addrs.nextElement();
992
          String name = addr.getType();
993
          String value = (String) addr.getContent();
994
          if (name.equals("foo")) {
995
              bean.setFoo(value);
996
          } else if (name.equals("bar")) {
997
              try {
998
                  bean.setBar(Integer.parseInt(value));
999
              } catch (NumberFormatException e) {
1000
                  throw new NamingException("Invalid 'bar' value " + value);
1001
              }
1002
          }
1003
      }
1004
 
1005
      // Return the customized instance
1006
      return (bean);
1007
 
1008
  }
1009
 
1010
}</code></pre></div>
1011
 
1012
  <p>In this example, we are unconditionally creating a new instance of
1013
  the <code>com.mycompany.MyBean</code> class, and populating its properties
1014
  based on the parameters included in the <code>&lt;Resource&gt;</code>
1015
  element that configures this resource (see below).  You should note that any
1016
  parameter named <code>factory</code> should be skipped - that parameter is
1017
  used to specify the name of the factory class itself (in this case,
1018
  <code>com.mycompany.MyBeanFactory</code>) rather than a property of the
1019
  bean being configured.</p>
1020
 
1021
  <p>For more information about <code>ObjectFactory</code>, see the
1022
  <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/index.html">
1023
  JNDI Service Provider Interface (SPI) Specification</a>.</p>
1024
 
1025
  <p>You will need to compile this class against a class path that includes
1026
  all of the JAR files in the <code>$CATALINA_HOME/lib</code> directory.  When you are through,
1027
  place the factory class (and the corresponding bean class) unpacked under
1028
  <code>$CATALINA_HOME/lib</code>, or in a JAR file inside
1029
  <code>$CATALINA_HOME/lib</code>.  In this way, the required class
1030
  files are visible to both Catalina internal resources and your web
1031
  application.</p>
1032
 
1033
  <h4>2.  Declare Your Resource Requirements</h4>
1034
 
1035
  <p>Next, modify your web application deployment descriptor
1036
  (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under which
1037
  you will request new instances of this bean.  The simplest approach is
1038
  to use a <code>&lt;resource-env-ref&gt;</code> element, like this:</p>
1039
 
1040
<div class="codeBox"><pre><code>&lt;resource-env-ref&gt;
1041
  &lt;description&gt;
1042
    Object factory for MyBean instances.
1043
  &lt;/description&gt;
1044
  &lt;resource-env-ref-name&gt;
1045
    bean/MyBeanFactory
1046
  &lt;/resource-env-ref-name&gt;
1047
  &lt;resource-env-ref-type&gt;
1048
    com.mycompany.MyBean
1049
  &lt;/resource-env-ref-type&gt;
1050
&lt;/resource-env-ref&gt;</code></pre></div>
1051
 
1052
    <p><strong>WARNING</strong> - Be sure you respect the element ordering
1053
    that is required by the DTD for web application deployment descriptors!
1054
    See the
1055
    <a href="https://cwiki.apache.org/confluence/display/TOMCAT/Specifications">Servlet
1056
    Specification</a> for details.</p>
1057
 
1058
  <h4>3.  Code Your Application's Use Of This Resource</h4>
1059
 
1060
  <p>A typical use of this resource environment reference might look
1061
  like this:</p>
1062
 
1063
<div class="codeBox"><pre><code>Context initCtx = new InitialContext();
1064
Context envCtx = (Context) initCtx.lookup("java:comp/env");
1065
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
1066
 
1067
writer.println("foo = " + bean.getFoo() + ", bar = " +
1068
               bean.getBar());</code></pre></div>
1069
 
1070
    <h4>4.  Configure Tomcat's Resource Factory</h4>
1071
 
1072
    <p>To configure Tomcat's resource factory, add an elements like this to the
1073
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
1074
    this web application.</p>
1075
 
1076
<div class="codeBox"><pre><code>&lt;Context ...&gt;
1077
  ...
1078
  &lt;Resource name="bean/MyBeanFactory" auth="Container"
1079
            type="com.mycompany.MyBean"
1080
            factory="com.mycompany.MyBeanFactory"
1081
            singleton="false"
1082
            bar="23"/&gt;
1083
  ...
1084
&lt;/Context&gt;</code></pre></div>
1085
 
1086
    <p>Note that the resource name (here, <code>bean/MyBeanFactory</code>
1087
    must match the value specified in the web application deployment
1088
    descriptor.  We are also initializing the value of the <code>bar</code>
1089
    property, which will cause <code>setBar(23)</code> to be called before
1090
    the new bean is returned.  Because we are not initializing the
1091
    <code>foo</code> property (although we could have), the bean will
1092
    contain whatever default value is set up by its constructor.</p>
1093
 
1094
    <p>You will also note that, from the application developer's perspective,
1095
    the declaration of the resource environment reference, and the programming
1096
    used to request new instances, is identical to the approach used for the
1097
    <em>Generic JavaBean Resources</em> example.  This illustrates one of the
1098
    advantages of using JNDI resources to encapsulate functionality - you can
1099
    change the underlying implementation without necessarily having to
1100
    modify applications using the resources, as long as you maintain
1101
    compatible APIs.</p>
1102
 
1103
</div></div></div></div></div><footer><div id="footer">
1104
    Copyright &copy; 1999-2025, The Apache Software Foundation
1105
    <br>
1106
    Apache Tomcat, Tomcat, Apache, the Apache Tomcat logo and the Apache logo
1107
    are either registered trademarks or trademarks of the Apache Software
1108
    Foundation.
1109
    </div></footer></div></body></html>