3
Licensed to the Apache Software Foundation (ASF) under one or more
4
contributor license agreements. See the NOTICE file distributed with
5
this work for additional information regarding copyright ownership.
6
The ASF licenses this file to You under the Apache License, Version 2.0
7
(the "License"); you may not use this file except in compliance with
8
the License. You may obtain a copy of the License at
10
http://www.apache.org/licenses/LICENSE-2.0
12
Unless required by applicable law or agreed to in writing, software
13
distributed under the License is distributed on an "AS IS" BASIS,
14
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
See the License for the specific language governing permissions and
16
limitations under the License.
19
<!ENTITY project SYSTEM "project.xml">
21
<document url="jndi-resources-howto.html">
26
<author email="craigmcc@apache.org">Craig R. McClanahan</author>
27
<author email="yoavs@apache.org">Yoav Shapira</author>
28
<title>JNDI Resources HOW-TO</title>
34
<section name="Introduction">
36
<p>Tomcat 6 provides a JNDI <strong>InitialContext</strong> implementation
37
instance for each web application running under it, in a manner that is
38
compatible with those provided by a
39
<a href="http://java.sun.com/j2ee">Java2 Enterprise Edition</a> application
40
server. The J2EE standard provides a standard set of elements in the
41
<code>/WEB-INF/web.xml</code> file to reference/define resources.</p>
43
<p>See the following Specifications for more information about programming APIs
44
for JNDI, and for the features supported by Java2 Enterprise Edition (J2EE)
45
servers, which Tomcat emulates for the services that it provides:</p>
47
<li><a href="http://java.sun.com/products/jndi">Java Naming and Directory
48
Interface</a> (included in JDK 1.4 onwards)</li>
49
<li><a href="http://java.sun.com/j2ee/download.html">J2EE Platform
50
Specification</a> (in particular, see Chapter 5 on <em>Naming</em>)</li>
55
<section name="web.xml configuration" >
57
<p>The following elements may be used in the web application deployment
58
descriptor (<code>/WEB-INF/web.xml</code>) of your web application to define
61
<li><code><strong><env-entry></strong></code> - Environment entry, a
62
single-value parameter that can be used to configure how the application
64
<li><code><strong><resource-ref></strong></code> - Resource reference,
65
which is typically to an object factory for resources such as a JDBC
66
<code>DataSource</code>, a JavaMail <code>Session</code>, or custom
67
object factories configured into Tomcat 6.</li>
68
<li><code><strong><resource-env-ref></strong></code> - Resource
69
environment reference, a new variation of <code>resource-ref</code>
70
added in Servlet 2.4 that is simpler to configure for resources
71
that do not require authentication information.</li>
74
<p>Providing that Tomcat is able to identify an appropriate resource factory to
75
use to create the resource and that no further configuration information is
76
required, Tomcat will use the information in <code>/WEB-INF/web.xml</code> to
77
create the resource.</p>
80
<section name="context.xml configuration">
82
<p>If Tomcat is unable to identify the appropriate resource factory and/or
83
additional configuration information is required, additional Tomcat specific
84
configuration must be specified before Tomcat can create the resource.
85
Tomcat specific resource configuration is entered in
86
the <a href="config/context.html"><code><Context></code></a> elements that
87
can be specified in either <code>$CATALINA_BASE/conf/server.xml</code> or,
88
preferably, the per-web-application context XML file
89
(<code>META-INF/context.xml</code>).</p>
91
<p>Tomcat specific resource configuration is performed using the following
92
elements in the <a href="config/context.html"><code><Context></code></a>
96
<li><a href="config/context.html#Environment Entries"><Environment></a> -
97
Configure names and values for scalar environment entries that will be
98
exposed to the web application through the JNDI
99
<code>InitialContext</code> (equivalent to the inclusion of an
100
<code><env-entry></code> element in the web application
101
deployment descriptor).</li>
102
<li><a href="config/context.html#Resource Definitions"><Resource></a> -
103
Configure the name and data type of a resource made available to the
104
application (equivalent to the inclusion of a
105
<code><resource-ref></code> element in the web application
106
deployment descriptor).</li>
107
<li><a href="config/context.html#Resource Links"><ResourceLink></a> -
108
Add a link to a resource defined in the global JNDI context. Use resource
109
links to give a web application access to a resource defined in
110
the<a href="config/globalresources.html"><GlobalNamingResources></a>
111
child element of the <a href="config/server.html"><Server></a>
113
<li><a href="config/context.html#Transaction"><Transaction></a> -
114
Add a resource factory for instantiating the UserTransaction object
115
instance that is available at <code>java:comp/UserTransaction</code>.</li>
119
<p>Any number of these elements may be nested inside a
120
<a href="config/context.html"><code><Context></code></a> element and will
121
be associated only with that particular web application.</p>
123
<p>If a resource has been defined in a
124
<a href="config/context.html"><code><Context></code></a> element it is not
125
necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
126
However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
127
to document the resource requirements for the web application.</p>
129
<p>Where the same resource name has been defined for a
130
<code><env-entry></code> element included in the web application
131
deployment descriptor (<code>/WEB-INF/web.xml</code>) and in an
132
<code><Environment></code> element as part of the
133
<a href="config/context.html"><code><Context></code></a> element for the
134
web application, the values in the deployment descriptor will take precedence
135
<strong>only</strong> if allowed by the corresponding
136
<code><Environment></code> element (by setting the <code>override</code>
137
attribute to "true").</p>
141
<section name="Global configuration">
143
<p>Tomcat 6 maintains a separate namespace of global resources for the
144
entire server. These are configured in the
145
<a href="config/globalresources.html">
146
<code><strong><GlobalNameingResources></strong></code></a> element of
147
<code>$CATALINA_BASE/conf/server.xml</code>. You may expose these resources to
148
web applications by using a
149
<a href="config/context.html#Resource Links"><ResourceLink></a> to
150
include it in the per-web-application context.</p>
152
<p>If a resource has been defined using a
153
<a href="config/context.html#Resource Links"><ResourceLink></a>, it is not
154
necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
155
However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
156
to document the resource requirements for the web application.</p>
160
<section name="Using resources">
162
<p>The <code>InitialContext</code> is configured as a web application is
163
initially deployed, and is made available to web application components (for
164
read-only access). All configured entries and resources are placed in
165
the <code>java:comp/env</code> portion of the JNDI namespace, so a typical
166
access to a resource - in this case, to a JDBC <code>DataSource</code> -
167
would look something like this:</p>
170
// Obtain our environment naming context
171
Context initCtx = new InitialContext();
172
Context envCtx = (Context) initCtx.lookup("java:comp/env");
174
// Look up our data source
175
DataSource ds = (DataSource)
176
envCtx.lookup("jdbc/EmployeeDB");
178
// Allocate and use a connection from the pool
179
Connection conn = ds.getConnection();
180
... use this connection to access the database ...
186
<section name="Tomcat Standard Resource Factories">
188
<p>Tomcat 6 includes a series of standard resource factories that can
189
provide services to your web applications, but give you configuration
191
<a href="config/context.html"><code><Context></code></a> element)
192
without modifying the web application or the deployment descriptor. Each
193
subsection below details the configuration and usage of the standard resource
196
<p>See <a href="#Adding Custom Resource Factories">Adding Custom
197
Resource Factories</a> for information about how to create, install,
198
configure, and use your own custom resource factory classes with
201
<p><em>NOTE</em> - Of the standard resource factories, only the
202
"JDBC Data Source" and "User Transaction" factories are mandated to
203
be available on other platforms, and then they are required only if
204
the platform implements the Java2 Enterprise Edition (J2EE) specs.
205
All other standard resource factories, plus custom resource factories
206
that you write yourself, are specific to Tomcat and cannot be assumed
207
to be available on other containers.</p>
209
<subsection name="Generic JavaBean Resources">
211
<h3>0. Introduction</h3>
213
<p>This resource factory can be used to create objects of <em>any</em>
214
Java class that conforms to standard JavaBeans naming conventions (i.e.
215
it has a zero-arguments constructor, and has property setters that
216
conform to the setFoo() naming pattern. The resource factory will
217
create a new instance of the appropriate bean class every time a
218
<code>lookup()</code> for this entry is made.</p>
220
<p>The steps required to use this facility are described below.</p>
222
<h3>1. Create Your JavaBean Class</h3>
224
<p>Create the JavaBean class which will be instantiated each time
225
that the resource factory is looked up. For this example, assume
226
you create a class <code>com.mycompany.MyBean</code>, which looks
230
package com.mycompany;
232
public class MyBean {
234
private String foo = "Default Foo";
236
public String getFoo() {
240
public void setFoo(String foo) {
246
public int getBar() {
250
public void setBar(int bar) {
258
<h3>2. Declare Your Resource Requirements</h3>
260
<p>Next, modify your web application deployment descriptor
261
(<code>/WEB-INF/web.xml</code>) to declare the JNDI name under which
262
you will request new instances of this bean. The simplest approach is
263
to use a <code><resource-env-ref></code> element, like this:</p>
266
<resource-env-ref>
268
Object factory for MyBean instances.
270
<resource-env-ref-name>
272
</resource-env-ref-name>
273
<resource-env-ref-type>
275
</resource-env-ref-type>
276
</resource-env-ref>
279
<p><strong>WARNING</strong> - Be sure you respect the element ordering
280
that is required by the DTD for web application deployment descriptors!
282
<a href="http://java.sun.com/products/servlet/download.html">Servlet
283
Specification</a> for details.</p>
285
<h3>3. Code Your Application's Use Of This Resource</h3>
287
<p>A typical use of this resource environment reference might look
291
Context initCtx = new InitialContext();
292
Context envCtx = (Context) initCtx.lookup("java:comp/env");
293
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
295
writer.println("foo = " + bean.getFoo() + ", bar = " +
299
<h3>4. Configure Tomcat's Resource Factory</h3>
301
<p>To configure Tomcat's resource factory, add an element like this to the
302
<a href="config/context.html"><code><Context></code></a> element for
303
this web application.</p>
308
<Resource name="bean/MyBeanFactory" auth="Container"
309
type="com.mycompany.MyBean"
310
factory="org.apache.naming.factory.BeanFactory"
316
<p>Note that the resource name (here, <code>bean/MyBeanFactory</code>
317
must match the value specified in the web application deployment
318
descriptor. We are also initializing the value of the <code>bar</code>
319
property, which will cause <code>setBar(23)</code> to be called before
320
the new bean is returned. Because we are not initializing the
321
<code>foo</code> property (although we could have), the bean will
322
contain whatever default value is set up by its constructor.</p>
327
<subsection name="UserDatabase Resources">
329
<h3>0. Introduction</h3>
331
<p>UserDatabase resources are typically configured as global resources for
332
use by a UserDatabase realm. Tomcat includes a UserDatabaseFactoory that
333
creates UserDatabase resources backed by an XML file - usually
334
<code>tomcat-users.xml</code></p>
336
<p>The steps required to set up a global UserDatabase resource are described
339
<h3>1. Create/edit the XML file</h3>
341
<p>The XMl file is typically located at
342
<code>$CATALINA_BASE/conf/tomcat-users.xml</code> however, you are free to
343
locate the file anywhere on the file system. It is recommended that the XML
344
files are placed in <code>$CATALINA_BASE/conf</code>. A typical XML would
348
<?xml version='1.0' encoding='utf-8'?>
350
<role rolename="tomcat"/>
351
<role rolename="role1"/>
352
<user username="tomcat" password="tomcat" roles="tomcat"/>
353
<user username="both" password="tomcat" roles="tomcat,role1"/>
354
<user username="role1" password="tomcat" roles="role1"/>
355
</tomcat-users>
358
<h3>2. Declare Your Resource</h3>
360
<p>Next, modify <code>$CATALINA_BASE/conf/server.xml</code> to create the
361
UserDatabase resource based on your XMl file. It should look something like
365
<Resource name="UserDatabase"
367
type="org.apache.catalina.UserDatabase"
368
description="User database that can be updated and saved"
369
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
370
pathname="conf/tomcat-users.xml"
371
readonly="false" />
374
<p>The <code>pathname</code> attribute can be absolute or relative. If
375
relative, it is relative to <code>$CATALINA_BASE</code>.</p>
377
<p>The <code>readonly</code> attribute is optional and defaults to
378
<code>false</code> if not supplied. If the XML is writeable then it will be
379
written to when Tomcat starts. <strong>WARNING:</strong> When the file is
380
written it will inherit the default file permissions for the user Tomcat
381
is running as. Ensure that these are appropriate to maintain the security
382
of your installation.</p>
384
<h3>3. Configure the Realm</h3>
386
<p>Configure a UserDatabase Realm to use this resource as described in the
387
<a href="config/realm.html">Realm configuration documentation</a>.</p>
392
<subsection name="JavaMail Sessions">
394
<h3>0. Introduction</h3>
396
<p>In many web applications, sending electronic mail messages is a
397
required part of the system's functionality. The
398
<a href="http://java.sun.com/products/javamail">Java Mail</a> API
399
makes this process relatively straightforward, but requires many
400
configuration details that the client application must be aware of
401
(including the name of the SMTP host to be used for message sending).</p>
403
<p>Tomcat 6 includes a standard resource factory that will create
404
<code>javax.mail.Session</code> session instances for you, already
405
configured to connect to an SMTP server.
406
In this way, the application is totally insulated from changes in the
407
email server configuration environment - it simply asks for, and receives,
408
a preconfigured session whenever needed.</p>
410
<p>The steps required for this are outlined below.</p>
412
<h3>1. Declare Your Resource Requirements</h3>
414
<p>The first thing you should do is modify the web application deployment
415
descriptor (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
416
which you will look up preconfigured sessions. By convention, all such
417
names should resolve to the <code>mail</code> subcontext (relative to the
418
standard <code>java:comp/env</code> naming context that is the root of
419
all provided resource factories. A typical <code>web.xml</code> entry
420
might look like this:</p>
424
Resource reference to a factory for javax.mail.Session
425
instances that may be used for sending electronic mail
426
messages, preconfigured to connect to the appropriate
431
</res-ref-name>
438
</resource-ref>
441
<p><strong>WARNING</strong> - Be sure you respect the element ordering
442
that is required by the DTD for web application deployment descriptors!
444
<a href="http://java.sun.com/products/servlet/download.html">Servlet
445
Specification</a> for details.</p>
447
<h3>2. Code Your Application's Use Of This Resource</h3>
449
<p>A typical use of this resource reference might look like this:</p>
451
Context initCtx = new InitialContext();
452
Context envCtx = (Context) initCtx.lookup("java:comp/env");
453
Session session = (Session) envCtx.lookup("mail/Session");
455
Message message = new MimeMessage(session);
456
message.setFrom(new InternetAddress(request.getParameter("from"));
457
InternetAddress to[] = new InternetAddress[1];
458
to[0] = new InternetAddress(request.getParameter("to"));
459
message.setRecipients(Message.RecipientType.TO, to);
460
message.setSubject(request.getParameter("subject"));
461
message.setContent(request.getParameter("content"), "text/plain");
462
Transport.send(message);
465
<p>Note that the application uses the same resource reference name
466
that was declared in the web application deployment descriptor. This
467
is matched up against the resource factory that is configured in the
468
<a href="config/context.html"><code><Context></code></a> element
469
for the web application as described below.</p>
471
<h3>3. Configure Tomcat's Resource Factory</h3>
473
<p>To configure Tomcat's resource factory, add an elements like this to the
474
<a href="config/context.html"><code><Context></code></a> element for
475
this web application.</p>
480
<Resource name="mail/Session" auth="Container"
481
type="javax.mail.Session"
482
mail.smtp.host="localhost"/>
487
<p>Note that the resource name (here, <code>mail/Session</code>) must
488
match the value specified in the web application deployment descriptor.
489
Customize the value of the <code>mail.smtp.host</code> parameter to
490
point at the server that provides SMTP service for your network.</p>
492
<h3>4. Install the JavaMail libraries</h3>
494
<p><a href="http://java.sun.com/products/javamail/downloads/index.html" target="_blank">
495
Download the JavaMail API</a>. The JavaMail API requires the Java Activation
496
Framework (JAF) API as well. The Java Activation Framework can be downloaded
497
from <a href="http://java.sun.com/products/javabeans/glasgow/jaf.html">Sun's site</a>.
500
<p>This download includes 2 vital libraries for the configuration;
501
activation.jar and mail.jar. Unpackage both distributions and place
502
them into $CATALINA_HOME/lib so that they are available to
503
Tomcat during the initialization of the mail Session Resource.
504
<strong>Note:</strong> placing these jars in both $CATALINA_HOME/lib and a
505
web application's lib folder will cause an error, so ensure you have
506
them in the $CATALINA_HOME/lib location only.
509
<h3>Example Application</h3>
511
<p>The <code>/examples</code> application included with Tomcat contains
512
an example of utilizing this resource factory. It is accessed via the
513
"JSP Examples" link. The source code for the servlet that actually
514
sends the mail message is in
515
<code>/WEB-INF/classes/SendMailServlet.java</code>.</p>
517
<p><strong>WARNING</strong> - The default configuration assumes that there
518
is an SMTP server listing on port 25 on <code>localhost</code>. If this is
519
not the case, edit the
520
<a href="config/context.html"><code><Context></code></a> element for
521
this web application and modify the parameter value for the
522
<code>mail.smtp.host</code> parameter to be the host name of an SMTP server
527
<subsection name="JDBC Data Sources">
529
<h3>0. Introduction</h3>
531
<p>Many web applications need to access a database via a JDBC driver,
532
to support the functionality required by that application. The J2EE
533
Platform Specification requires J2EE Application Servers to make
534
available a <em>DataSource</em> implementation (that is, a connection
535
pool for JDBC connections) for this purpose. Tomcat 6 offers exactly
536
the same support, so that database-based applications you develop on
537
Tomcat using this service will run unchanged on any J2EE server.</p>
539
<p>For information about JDBC, you should consult the following:</p>
541
<li><a href="http://java.sun.com/products/jdbc/">http://java.sun.com/products/jdbc/</a> -
542
Home page for information about Java Database Connectivity.</li>
543
<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> -
544
The JDBC 2.1 API Specification.</li>
545
<li><a href="http://java.sun.com/products/jdbc/jdbc20.stdext.pdf">http://java.sun.com/products/jdbc/jdbc20.stdext.pdf</a> -
546
The JDBC 2.0 Standard Extension API (including the
547
<code>javax.sql.DataSource</code> API). This package is now known
548
as the "JDBC Optional Package".</li>
549
<li><a href="http://java.sun.com/j2ee/download.html">http://java.sun.com/j2ee/download.html</a> -
550
The J2EE Platform Specification (covers the JDBC facilities that
551
all J2EE platforms must provide to applications).</li>
554
<p><strong>NOTE</strong> - The default data source support in Tomcat
555
is based on the <strong>DBCP</strong> connection pool from the
556
<a href="http://commons.apache.org/">Commons</a>
557
project. However, it is possible to use any other connection pool
558
that implements <code>javax.sql.DataSource</code>, by writing your
559
own custom resource factory, as described
560
<a href="#Adding Custom Resource Factories">below</a>.</p>
562
<h3>1. Install Your JDBC Driver</h3>
564
<p>Use of the <em>JDBC Data Sources</em> JNDI Resource Factory requires
565
that you make an appropriate JDBC driver available to both Tomcat internal
566
classes and to your web application. This is most easily accomplished by
567
installing the driver's JAR file(s) into the
568
<code>$CATALINA_HOME/lib</code> directory, which makes the driver
569
available both to the resource factory and to your application.</p>
571
<h3>2. Declare Your Resource Requirements</h3>
573
<p>Next, modify the web application deployment descriptor
574
(<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
575
which you will look up preconfigured data source. By convention, all such
576
names should resolve to the <code>jdbc</code> subcontext (relative to the
577
standard <code>java:comp/env</code> naming context that is the root of
578
all provided resource factories. A typical <code>web.xml</code> entry
579
might look like this:</p>
583
Resource reference to a factory for java.sql.Connection
584
instances that may be used for talking to a particular
585
database that is configured in the <Context>
586
configurartion for the web application.
590
</res-ref-name>
597
</resource-ref>
600
<p><strong>WARNING</strong> - Be sure you respect the element ordering
601
that is required by the DTD for web application deployment descriptors!
603
<a href="http://java.sun.com/products/servlet/download.html">Servlet
604
Specification</a> for details.</p>
606
<h3>3. Code Your Application's Use Of This Resource</h3>
608
<p>A typical use of this resource reference might look like this:</p>
610
Context initCtx = new InitialContext();
611
Context envCtx = (Context) initCtx.lookup("java:comp/env");
612
DataSource ds = (DataSource)
613
envCtx.lookup("jdbc/EmployeeDB");
615
Connection conn = ds.getConnection();
616
... use this connection to access the database ...
620
<p>Note that the application uses the same resource reference name that was
621
declared in the web application deployment descriptor. This is matched up
622
against the resource factory that is configured in the
623
<a href="config/context.html"><code><Context></code></a> element for
624
the web application as described below.</p>
626
<h3>4. Configure Tomcat's Resource Factory</h3>
628
<p>To configure Tomcat's resource factory, add an element like this to the
629
<a href="config/context.html"><code><Context></code></a> element for
630
the web application.</p>
635
<Resource name="jdbc/EmployeeDB"
637
type="javax.sql.DataSource"
638
username="dbusername"
639
password="dbpassword"
640
driverClassName="org.hsql.jdbcDriver"
641
url="jdbc:HypersonicSQL:database"
648
<p>Note that the resource name (here, <code>jdbc/EmployeeDB</code>) must
649
match the value specified in the web application deployment descriptor.</p>
651
<p>This example assumes that you are using the HypersonicSQL database
652
JDBC driver. Customize the <code>driverClassName</code> and
653
<code>driverName</code> parameters to match your actual database's
654
JDBC driver and connection URL.</p>
656
<p>The configuration properties for Tomcat's standard data source
658
(<code>org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory</code>) are
661
<li><strong>driverClassName</strong> - Fully qualified Java class name
662
of the JDBC driver to be used.</li>
663
<li><strong>maxActive</strong> - The maximum number of active instances
664
that can be allocated from this pool at the same time.</li>
665
<li><strong>maxIdle</strong> - The maximum number of connections that
666
can sit idle in this pool at the same time.</li>
667
<li><strong>maxWait</strong> - The maximum number of milliseconds that the
668
pool will wait (when there are no available connections) for a
669
connection to be returned before throwing an exception.</li>
670
<li><strong>password</strong> - Database password to be passed to our
672
<li><strong>url</strong> - Connection URL to be passed to our JDBC driver.
673
(For backwards compatibility, the property <code>driverName</code>
674
is also recognized.)</li>
675
<li><strong>username</strong> - Database username to be passed to our
677
<li><strong>validationQuery</strong> - SQL query that can be used by the
678
pool to validate connections before they are returned to the
679
application. If specified, this query MUST be an SQL SELECT
680
statement that returns at least one row.</li>
682
<p>For more details, please refer to the commons-dbcp documentation.</p>
689
<section name="Adding Custom Resource Factories">
691
<p>If none of the standard resource factories meet your needs, you can write
692
your own factory and integrate it into Tomcat 6, and then configure the use
693
of this factory in the
694
<a href="config/context.html"><code><Context></code></a> element for
695
the web application. In the example below, we will create a factory that only
696
knows how to create <code>com.mycompany.MyBean</code> beans from the
697
<a href="#Generic JavaBean Resources">Generic JavaBean Resources</a> example
700
<h3>1. Write A Resource Factory Class</h3>
702
<p>You must write a class that implements the JNDI service provider
703
<code>javax.naming.spi.ObjectFactory</code> inteface. Every time your
704
web application calls <code>lookup()</code> on a context entry that is
705
bound to this factory, the <code>getObjectInstance()</code> method is
706
called, with the following arguments:</p>
708
<li><strong>Object obj</strong> - The (possibly null) object containing
709
location or reference information that can be used in creating an object.
710
For Tomcat, this will always be an object of type
711
<code>javax.naming.Reference</code>, which contains the class name of
712
this factory class, as well as the configuration properties (from the
713
<a href="config/context.html"><code><Context></code></a> for the
714
web application) to use in creating objects to be returned.</li>
715
<li><strong>Name name</strong> - The name to which this factory is bound
716
relative to <code>nameCtx</code>, or <code>null</code> if no name
718
<li><strong>Context nameCtx</strong> - The context relative to which the
719
<code>name</code> parameter is specified, or <code>null</code> if
720
<code>name</code> is relative to the default initial context.</li>
721
<li><strong>Hashtable environment</strong> - The (possibly null)
722
environment that is used in creating this object. This is generally
723
ignored in Tomcat object factories.</li>
726
<p>To create a resource factory that knows how to produce <code>MyBean</code>
727
instances, you might create a class like this:</p>
730
package com.mycompany;
732
import java.util.Enumeration;
733
import java.util.Hashtable;
734
import javax.naming.Context;
735
import javax.naming.Name;
736
import javax.naming.NamingException;
737
import javax.naming.RefAddr;
738
import javax.naming.Reference;
739
import javax.naming.spi.ObjectFactory;
741
public class MyBeanFactory implements ObjectFactory {
743
public Object getObjectInstance(Object obj,
744
Name name, Context nameCtx, Hashtable environment)
745
throws NamingException {
747
// Acquire an instance of our specified bean class
748
MyBean bean = new MyBean();
750
// Customize the bean properties from our attributes
751
Reference ref = (Reference) obj;
752
Enumeration addrs = ref.getAll();
753
while (addrs.hasMoreElements()) {
754
RefAddr addr = (RefAddr) addrs.nextElement();
755
String name = addr.getType();
756
String value = (String) addr.getContent();
757
if (name.equals("foo")) {
759
} else if (name.equals("bar")) {
761
bean.setBar(Integer.parseInt(value));
762
} catch (NumberFormatException e) {
763
throw new NamingException("Invalid 'bar' value " + value);
768
// Return the customized instance
776
<p>In this example, we are unconditionally creating a new instance of
777
the <code>com.mycompany.MyBean</code> class, and populating its properties
778
based on the parameters included in the <code><ResourceParams></code>
779
element that configures this factory (see below). You should note that any
780
parameter named <code>factory</code> should be skipped - that parameter is
781
used to specify the name of the factory class itself (in this case,
782
<code>com.mycompany.MyBeanFactory</code>) rather than a property of the
783
bean being configured.</p>
785
<p>For more information about <code>ObjectFactory</code>, see the
786
<a href="http://java.sun.com/products/jndi/docs.html">JNDI 1.2 Service
787
Provider Interface (SPI) Specification</a>.</p>
789
<p>You will need to compile this class against a class path that includes
790
all of the JAR files in the <code>$CATALINA_HOME/lib</code> directory. When you are through,
791
place the factory class (and the corresponding bean class) unpacked under
792
<code>$CATALINA_HOME/lib</code>, or in a JAR file inside
793
<code>$CATALINA_HOME/lib</code>. In this way, the required class
794
files are visible to both Catalina internal resources and your web
797
<h3>2. Declare Your Resource Requirements</h3>
799
<p>Next, modify your web application deployment descriptor
800
(<code>/WEB-INF/web.xml</code>) to declare the JNDI name under which
801
you will request new instances of this bean. The simplest approach is
802
to use a <code><resource-env-ref></code> element, like this:</p>
805
<resource-env-ref>
807
Object factory for MyBean instances.
809
<resource-env-ref-name>
811
</resource-env-ref-name>
812
<resource-env-ref-type>
814
</resource-env-ref-type>
815
<resource-env-ref>
818
<p><strong>WARNING</strong> - Be sure you respect the element ordering
819
that is required by the DTD for web application deployment descriptors!
821
<a href="http://java.sun.com/products/servlet/download.html">Servlet
822
Specification</a> for details.</p>
824
<h3>3. Code Your Application's Use Of This Resource</h3>
826
<p>A typical use of this resource environment reference might look
830
Context initCtx = new InitialContext();
831
Context envCtx = (Context) initCtx.lookup("java:comp/env");
832
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
834
writer.println("foo = " + bean.getFoo() + ", bar = " +
838
<h3>4. Configure Tomcat's Resource Factory</h3>
840
<p>To configure Tomcat's resource factory, add an elements like this to the
841
<a href="config/context.html"><code><Context></code></a> element for
842
this web application.</p>
847
<Resource name="bean/MyBeanFactory" auth="Container"
848
type="com.mycompany.MyBean"
849
factory="com.mycompany.MyBeanFactory"
855
<p>Note that the resource name (here, <code>bean/MyBeanFactory</code>
856
must match the value specified in the web application deployment
857
descriptor. We are also initializing the value of the <code>bar</code>
858
property, which will cause <code>setBar(23)</code> to be called before
859
the new bean is returned. Because we are not initializing the
860
<code>foo</code> property (although we could have), the bean will
861
contain whatever default value is set up by its constructor.</p>
863
<p>You will also note that, from the application developer's perspective,
864
the declaration of the resource environment reference, and the programming
865
used to request new instances, is identical to the approach used for the
866
<em>Generic JavaBean Resources</em> example. This illustrates one of the
867
advantages of using JNDI resources to encapsulate functionality - you can
868
change the underlying implementation without necessarily having to
869
modify applications using the resources, as long as you maintain