File: jndi-resources-howto.xml

package info (click to toggle)
tomcat6 6.0.45%2Bdfsg-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 20,960 kB
  • ctags: 27,814
  • sloc: java: 179,379; xml: 42,067; jsp: 1,948; sh: 1,268; makefile: 101
file content (975 lines) | stat: -rw-r--r-- 41,775 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!DOCTYPE document [
  <!ENTITY project SYSTEM "project.xml">
]>
<document url="jndi-resources-howto.html">

    &project;

    <properties>
      <author email="craigmcc@apache.org">Craig R. McClanahan</author>
      <author email="yoavs@apache.org">Yoav Shapira</author>
      <title>JNDI Resources HOW-TO</title>
    </properties>

<body>

<section name="Table of Contents">
<toc/>
</section>

<section name="Introduction">

<p>Tomcat 6 provides a JNDI <strong>InitialContext</strong> implementation
instance for each web application running under it, in a manner that is 
compatible with those provided by a 
<a href="http://java.sun.com/j2ee">Java2 Enterprise Edition</a> application 
server. The J2EE standard provides a standard set of elements in the
<code>/WEB-INF/web.xml</code> file to reference/define resources.</p>

<p>See the following Specifications for more information about programming APIs
for JNDI, and for the features supported by Java2 Enterprise Edition (J2EE)
servers, which Tomcat emulates for the services that it provides:</p>
<ul>
<li><a href="http://java.sun.com/products/jndi">Java Naming and Directory
    Interface</a> (included in JDK 1.4 onwards)</li>
<li><a href="http://java.sun.com/j2ee/download.html">J2EE Platform
    Specification</a> (in particular, see Chapter 5 on <em>Naming</em>)</li>
</ul>

</section>

<section name="web.xml configuration" >

<p>The following elements may be used in the web application deployment
descriptor (<code>/WEB-INF/web.xml</code>) of your web application to define
resources:</p>
<ul>
<li><code><strong>&lt;env-entry&gt;</strong></code> - Environment entry, a
    single-value parameter that can be used to configure how the application
    will operate.</li>
<li><code><strong>&lt;resource-ref&gt;</strong></code> - Resource reference,
    which is typically to an object factory for resources such as a JDBC
    <code>DataSource</code>, a JavaMail <code>Session</code>, or custom
    object factories configured into Tomcat 6.</li>
<li><code><strong>&lt;resource-env-ref&gt;</strong></code> - Resource
    environment reference, a new variation of <code>resource-ref</code>
    added in Servlet 2.4 that is simpler to configure for resources
    that do not require authentication information.</li>
</ul>

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

<section name="context.xml configuration">

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

<p>Tomcat specific resource configuration is performed using the following
elements in the <a href="config/context.html"><code>&lt;Context&gt;</code></a>
element:</p>

<ul>
<li><a href="config/context.html#Environment Entries">&lt;Environment&gt;</a> -
    Configure names and values for scalar environment entries that will be
    exposed to the web application through the JNDI
    <code>InitialContext</code> (equivalent to the inclusion of an
    <code>&lt;env-entry&gt;</code> element in the web application
    deployment descriptor).</li>
<li><a href="config/context.html#Resource Definitions">&lt;Resource&gt;</a> -
    Configure the name and data type of a resource made available to the
    application (equivalent to the inclusion of a
    <code>&lt;resource-ref&gt;</code> element in the web application
    deployment descriptor).</li>
<li><a href="config/context.html#Resource Links">&lt;ResourceLink&gt;</a> -
    Add a link to a resource defined in the global JNDI context. Use resource 
    links to give a web application access to a resource defined in 
    the <a href="config/globalresources.html">&lt;GlobalNamingResources&gt;</a>
    child element of the <a href="config/server.html">&lt;Server&gt;</a>
    element.</li>
<li><a href="config/context.html#Transaction">&lt;Transaction&gt;</a> -
    Add a resource factory for instantiating the UserTransaction object 
    instance that is available at <code>java:comp/UserTransaction</code>.</li>

</ul>

<p>Any number of these elements may be nested inside a
<a href="config/context.html"><code>&lt;Context&gt;</code></a> element and will
be associated only with that particular web application.</p>

<p>If a resource has been defined in a
<a href="config/context.html"><code>&lt;Context&gt;</code></a> element it is not
necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
to document the resource requirements for the web application.</p>

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

</section>

<section name="Global configuration">

<p>Tomcat 6 maintains a separate namespace of global resources for the 
entire server.  These are configured in the 
<a href="config/globalresources.html">
<code><strong>&lt;GlobalNamingResources&gt;</strong></code></a> element of 
<code>$CATALINA_BASE/conf/server.xml</code>. You may expose these resources to 
web applications by using a 
<a href="config/context.html#Resource Links">&lt;ResourceLink&gt;</a> to
include it in the per-web-application context.</p>

<p>If a resource has been defined using a 
<a href="config/context.html#Resource Links">&lt;ResourceLink&gt;</a>, it is not
necessary for that resource to be defined in <code>/WEB-INF/web.xml</code>.
However, it is recommended to keep the entry in <code>/WEB-INF/web.xml</code>
to document the resource requirements for the web application.</p>

</section>

<section name="Using resources">

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

<source>
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source
DataSource ds = (DataSource)
  envCtx.lookup("jdbc/EmployeeDB");

// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
</source>

</section>

<section name="Tomcat Standard Resource Factories">

  <p>Tomcat 6 includes a series of standard resource factories that can
  provide services to your web applications, but give you configuration
  flexibility (via the
  <a href="config/context.html"><code>&lt;Context&gt;</code></a> element)
  without modifying the web application or the deployment descriptor. Each
  subsection below details the configuration and usage of the standard resource
  factories.</p>

  <p>See <a href="#Adding Custom Resource Factories">Adding Custom
  Resource Factories</a> for information about how to create, install,
  configure, and use your own custom resource factory classes with
  Tomcat 6.</p>

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

  <subsection name="Generic JavaBean Resources">

    <h3>0.  Introduction</h3>

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

    <p>The steps required to use this facility are described below.</p>

    <h3>1.  Create Your JavaBean Class</h3>

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

<source>
package com.mycompany;

public class MyBean {

  private String foo = "Default Foo";

  public String getFoo() {
    return (this.foo);
  }

  public void setFoo(String foo) {
    this.foo = foo;
  }

  private int bar = 0;

  public int getBar() {
    return (this.bar);
  }

  public void setBar(int bar) {
    this.bar = bar;
  }


}
</source>

  <h3>2.  Declare Your Resource Requirements</h3>

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

<source>
&lt;resource-env-ref&gt;
  &lt;description&gt;
    Object factory for MyBean instances.
  &lt;/description&gt;
  &lt;resource-env-ref-name&gt;
    bean/MyBeanFactory
  &lt;/resource-env-ref-name&gt;
  &lt;resource-env-ref-type&gt;
    com.mycompany.MyBean
  &lt;/resource-env-ref-type&gt;
&lt;/resource-env-ref&gt;
</source>

    <p><strong>WARNING</strong> - Be sure you respect the element ordering
    that is required by the DTD for web application deployment descriptors!
    See the
    <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
    Specification</a> for details.</p>

  <h3>3.  Code Your Application's Use Of This Resource</h3>

  <p>A typical use of this resource environment reference might look
  like this:</p>

<source>
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
               bean.getBar());
</source>

    <h3>4.  Configure Tomcat's Resource Factory</h3>

    <p>To configure Tomcat's resource factory, add an element like this to the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
    this web application.</p>

<source>
&lt;Context ...&gt;
  ...
  &lt;Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="org.apache.naming.factory.BeanFactory"
            bar="23"/&gt;
  ...
&lt;/Context&gt;
</source>

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

  </subsection>


  <subsection name="UserDatabase Resources">

    <h3>0.  Introduction</h3>

    <p>UserDatabase resources are typically configured as global resources for
    use by a UserDatabase realm. Tomcat includes a UserDatabaseFactoory that
    creates UserDatabase resources backed by an XML file - usually
    <code>tomcat-users.xml</code></p>

    <p>The steps required to set up a global UserDatabase resource are described
    below.</p>

    <h3>1. Create/edit the XML file</h3>

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

<source>
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;tomcat-users&gt;
  &lt;role rolename="tomcat"/&gt;
  &lt;role rolename="role1"/&gt;
  &lt;user username="tomcat" password="tomcat" roles="tomcat"/&gt;
  &lt;user username="both" password="tomcat" roles="tomcat,role1"/&gt;
  &lt;user username="role1" password="tomcat" roles="role1"/&gt;
&lt;/tomcat-users&gt;
</source>

    <h3>2.  Declare Your Resource</h3>

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

<source>
&lt;Resource name="UserDatabase"
          auth="Container"
          type="org.apache.catalina.UserDatabase"
          description="User database that can be updated and saved"
          factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
          pathname="conf/tomcat-users.xml"
          readonly="false" /&gt;
</source>

    <p>The <code>pathname</code> attribute can be absolute or relative. If
    relative, it is relative to <code>$CATALINA_BASE</code>.</p>
    
    <p>The <code>readonly</code> attribute is optional and defaults to
    <code>true</code> if not supplied. If the XML is writeable then it will be
    written to when Tomcat starts. <strong>WARNING:</strong> When the file is
    written it will inherit the default file permissions for the user Tomcat
    is running as. Ensure that these are appropriate to maintain the security
    of your installation.</p>

    <h3>3.  Configure the Realm</h3>

    <p>Configure a UserDatabase Realm to use this resource as described in the
    <a href="config/realm.html">Realm configuration documentation</a>.</p>

  </subsection>


  <subsection name="JavaMail Sessions">

    <h3>0.  Introduction</h3>

    <p>In many web applications, sending electronic mail messages is a
    required part of the system's functionality.  The
    <a href="http://java.sun.com/products/javamail">Java Mail</a> API
    makes this process relatively straightforward, but requires many
    configuration details that the client application must be aware of
    (including the name of the SMTP host to be used for message sending).</p>

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

    <p>The steps required for this are outlined below.</p>

    <h3>1.  Declare Your Resource Requirements</h3>

    <p>The first thing you should do is modify the web application deployment
    descriptor (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
    which you will look up preconfigured sessions.  By convention, all such
    names should resolve to the <code>mail</code> subcontext (relative to the
    standard <code>java:comp/env</code> naming context that is the root of
    all provided resource factories.  A typical <code>web.xml</code> entry
    might look like this:</p>
<source>
&lt;resource-ref&gt;
  &lt;description&gt;
    Resource reference to a factory for javax.mail.Session
    instances that may be used for sending electronic mail
    messages, preconfigured to connect to the appropriate
    SMTP server.
  &lt;/description&gt;
  &lt;res-ref-name&gt;
    mail/Session
  &lt;/res-ref-name&gt;
  &lt;res-type&gt;
    javax.mail.Session
  &lt;/res-type&gt;
  &lt;res-auth&gt;
    Container
  &lt;/res-auth&gt;
&lt;/resource-ref&gt;
</source>

    <p><strong>WARNING</strong> - Be sure you respect the element ordering
    that is required by the DTD for web application deployment descriptors!
    See the
    <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
    Specification</a> for details.</p>

    <h3>2.  Code Your Application's Use Of This Resource</h3>

    <p>A typical use of this resource reference might look like this:</p>
<source>
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from")));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);
</source>

    <p>Note that the application uses the same resource reference name
    that was declared in the web application deployment descriptor.  This
    is matched up against the resource factory that is configured in the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element
    for the web application as described below.</p>

    <h3>3.  Configure Tomcat's Resource Factory</h3>

    <p>To configure Tomcat's resource factory, add an elements like this to the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
    this web application.</p>

<source>
&lt;Context ...&gt;
  ...
  &lt;Resource name="mail/Session" auth="Container"
            type="javax.mail.Session"
            mail.smtp.host="localhost"/&gt;
  ...
&lt;/Context&gt;
</source>

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

    <p>Additional resource attributes and values will be converted to properties
    and values and passed to
    <code>javax.mail.Session.getInstance(java.util.Properties)</code> as part of
    the <code>java.util.Properties</code> collection. In addition to the
    properties defined in Annex A of the JavaMail specification, individual
    providers may also support additional properties.</p>
    
    <p>Tomcat's resource factory provides a <code>password</code> property
    which can be configured by adding <code>password="yourpassword"</code>
    to the Resource definition.</p>

    <h3>4.  Install the JavaMail libraries</h3>

    <p><a href="http://www.oracle.com/technetwork/java/index-138643.html">
    Download the JavaMail API</a>.  The JavaMail API requires the Java Activation
    Framework (JAF) API as well.  The Java Activation Framework is included in
    Java SE 6 onwards. Java SE 5 users can download the latest version, 
    <a href="http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html">
    JAF 1.1.1</a>.
    </p>

    <p>Unpackage the distribution(s) and place mail.jar (and activation.jar if
    required) into $CATALINA_HOME/lib so the JAR(s) is(are) available to Tomcat
    during the initialization of the mail Session Resource.
    <strong>Note:</strong> placing jars in both $CATALINA_HOME/lib and a web
    application's lib folder will cause an error, so ensure mail.jar (and
    activation.jar) is(are) placed only the $CATALINA_HOME/lib location.
    </p>

    <h3>Example Application</h3>

    <p>The <code>/examples</code> application included with Tomcat contains
    an example of utilizing this resource factory.  It is accessed via the
    "JSP Examples" link.  The source code for the servlet that actually
    sends the mail message is in
    <code>/WEB-INF/classes/SendMailServlet.java</code>.</p>

    <p><strong>WARNING</strong> - The default configuration assumes that there
    is an SMTP server listing on port 25 on <code>localhost</code>. If this is
    not the case, edit the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
    this web application and modify the parameter value for the
    <code>mail.smtp.host</code> parameter to be the host name of an SMTP server
    on your network.</p>

  </subsection>

  <subsection name="JDBC Data Sources">

    <h3>0.  Introduction</h3>

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

    <p>For information about JDBC, you should consult the following:</p>
    <ul>
    <li><a href="http://java.sun.com/products/jdbc/">http://java.sun.com/products/jdbc/</a> -
        Home page for information about Java Database Connectivity.</li>
    <li><a href="http://docs.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html">http://docs.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame.html</a> -
        The JDBC 2.1 API Specification.</li>
    <li><a href="http://java.sun.com/products/jdbc/jdbc20.stdext.pdf">http://java.sun.com/products/jdbc/jdbc20.stdext.pdf</a> -
        The JDBC 2.0 Standard Extension API (including the
        <code>javax.sql.DataSource</code> API).  This package is now known
        as the "JDBC Optional Package".</li>
    <li><a href="http://java.sun.com/j2ee/download.html">http://java.sun.com/j2ee/download.html</a> -
        The J2EE Platform Specification (covers the JDBC facilities that
        all J2EE platforms must provide to applications).</li>
    </ul>

    <p><strong>NOTE</strong> - The default data source support in Tomcat
    is based on the <strong>DBCP</strong> connection pool from the
    <a href="http://commons.apache.org/">Commons</a>
    project.  However, it is possible to use any other connection pool
    that implements <code>javax.sql.DataSource</code>, by writing your
    own custom resource factory, as described
    <a href="#Adding Custom Resource Factories">below</a>.</p>

    <h3>1.  Install Your JDBC Driver</h3>

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

    <h3>2.  Declare Your Resource Requirements</h3>

    <p>Next, modify the web application deployment descriptor
    (<code>/WEB-INF/web.xml</code>) to declare the JNDI name under
    which you will look up preconfigured data source.  By convention, all such
    names should resolve to the <code>jdbc</code> subcontext (relative to the
    standard <code>java:comp/env</code> naming context that is the root of
    all provided resource factories.  A typical <code>web.xml</code> entry
    might look like this:</p>
<source>
&lt;resource-ref&gt;
  &lt;description&gt;
    Resource reference to a factory for java.sql.Connection
    instances that may be used for talking to a particular
    database that is configured in the &lt;Context&gt;
    configurartion for the web application.
  &lt;/description&gt;
  &lt;res-ref-name&gt;
    jdbc/EmployeeDB
  &lt;/res-ref-name&gt;
  &lt;res-type&gt;
    javax.sql.DataSource
  &lt;/res-type&gt;
  &lt;res-auth&gt;
    Container
  &lt;/res-auth&gt;
&lt;/resource-ref&gt;
</source>

    <p><strong>WARNING</strong> - Be sure you respect the element ordering
    that is required by the DTD for web application deployment descriptors!
    See the
    <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
    Specification</a> for details.</p>

    <h3>3.  Code Your Application's Use Of This Resource</h3>

    <p>A typical use of this resource reference might look like this:</p>
<source>
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
  envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
</source>

    <p>Note that the application uses the same resource reference name that was
    declared in the web application deployment descriptor. This is matched up
    against the resource factory that is configured in the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
    the web application as described below.</p>

    <h3>4.  Configure Tomcat's Resource Factory</h3>

    <p>To configure Tomcat's resource factory, add an element like this to the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
    the web application.</p>

<source>
&lt;Context ...&gt;
  ...
  &lt;Resource name="jdbc/EmployeeDB"
            auth="Container"
            type="javax.sql.DataSource"
            username="dbusername"
            password="dbpassword"
            driverClassName="org.hsql.jdbcDriver"
            url="jdbc:HypersonicSQL:database"
            maxActive="8"
            maxIdle="4"/&gt;
  ...
&lt;/Context&gt;
</source>

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

    <p>This example assumes that you are using the HypersonicSQL database
    JDBC driver.  Customize the <code>driverClassName</code> and
    <code>driverName</code> parameters to match your actual database's
    JDBC driver and connection URL.</p>

    <p>The configuration properties for our default data source
    resource factory
    (<code>org.apache.commons.dbcp.BasicDataSourceFactory</code>) are
    as follows:</p>
    <ul>
    <li><strong>driverClassName</strong> - Fully qualified Java class name
        of the JDBC driver to be used.</li>
    <li><strong>username</strong> - Database username to be passed to our
        JDBC driver.</li>
    <li><strong>password</strong> - Database password to be passed to our
        JDBC driver.</li>
    <li><strong>url</strong> - Connection URL to be passed to our JDBC driver.
        (For backwards compatibility, the property <code>driverName</code>
        is also recognized.)</li>
    <li><strong>initialSize</strong> - The initial number of connections
        that will be created in the pool during pool initialization. Default: 0</li>
    <li><strong>maxActive</strong> - The maximum number of connections
        that can be allocated from this pool at the same time. Default: 8</li>
    <li><strong>minIdle</strong> - The minimum number of connections that
        will sit idle in this pool at the same time. Default: 0</li>
    <li><strong>maxIdle</strong> - The maximum number of connections that
        can sit idle in this pool at the same time. Default: 8</li>
    <li><strong>maxWait</strong> - The maximum number of milliseconds that the
        pool will wait (when there are no available connections) for a
        connection to be returned before throwing an exception. Default: -1 (infinite)</li>
    </ul>
    <p>Some additional properties handle connection validation:</p>
    <ul>
    <li><strong>validationQuery</strong> - SQL query that can be used by the
        pool to validate connections before they are returned to the
        application.  If specified, this query MUST be an SQL SELECT
        statement that returns at least one row.</li>
    <li><strong>validationQueryTimeout</strong> - Timeout in seconds
        for the validation query to return. Default: -1 (infinite)</li>
    <li><strong>testOnBorrow</strong> - true or false: whether a connection
        should be validated using the validation query each time it is
        borrowed from the pool. Default: true</li>
    <li><strong>testOnReturn</strong> - true or false: whether a connection
        should be validated using the validation query each time it is
        returned to the pool. Default: false</li>
    </ul>
    <p>The optional evictor thread is responsible for shrinking the pool
    by removing any conections which are idle for a long time. The evictor
    does not respect <code>minIdle</code>. Note that you do not need to
    activate the evictor thread if you only want the pool to shrink according
    to the configured <code>maxIdle</code> property.</p>
    <p>The evictor is disabled by default and can be configured using
    the following properties:</p>
    <ul>
    <li><strong>timeBetweenEvictionRunsMillis</strong> - The number of
        milliseconds between consecutive runs of the evictor.
        Default: -1 (disabled)</li>
    <li><strong>numTestsPerEvictionRun</strong> - The number of connections
        that will be checked for idleness by the evitor during each
        run of the evictor. Default: 3</li>
    <li><strong>minEvictableIdleTimeMillis</strong> - The idle time in
        milliseconds after which a connection can be removed from the pool
        by the evictor. Default: 30*60*1000 (30 minutes)</li>
    <li><strong>testWhileIdle</strong> - true or false: whether a connection
        should be validated by the evictor thread using the validation query
        while sitting idle in the pool. Default: false</li>
    </ul>
    <p>Another optional feature is the removal of abandoned connections.
    A connection is called abandoned if the application does not return it
    to the pool for a long time. The pool can close such connections
    automatically and remove them from the pool. This is a workaround
    for applications leaking connections.</p>
    <p>The abandoning feature is disabled by default and can be configured
    using the following properties:</p>
    <ul>
    <li><strong>removeAbandoned</strong> - true or false: whether to
        remove abandoned connections from the pool. Default: false</li>
    <li><strong>removeAbandonedTimeout</strong> - The number of
        seconds after which a borrowed connection is assumed to be abandoned.
        Default: 300</li>
    <li><strong>logAbandoned</strong> - true or false: whether to log
        stack traces for application code which abandoned a statement
        or connection. This adds serious overhead. Default: false</li>
    </ul>
    <p>Finally there are various properties that allow further fine tuning
    of the pool behaviour:</p>
    <ul>
    <li><strong>defaultAutoCommit</strong> - true or false: default
        auto-commit state of the connections created by this pool.
        Default: true</li>
    <li><strong>defaultReadOnly</strong> - true or false: default
        read-only state of the connections created by this pool.
        Default: false</li>
    <li><strong>defaultTransactionIsolation</strong> - This sets the
        default transaction isolation level. Can be one of
        <code>NONE</code>, <code>READ_COMMITTED</code>,
        <code>READ_UNCOMMITTED</code>, <code>REPEATABLE_READ</code>,
        <code>SERIALIZABLE</code>. Default: no default set</li>
    <li><strong>poolPreparedStatements</strong> - true or false: whether to
        pool PreparedStatements and CallableStatements. Default: false</li>
    <li><strong>maxOpenPreparedStatements</strong> - The maximum number of open
        statements that can be allocated from the statement pool at the same time.
        Default: -1 (unlimited)</li>
    <li><strong>defaultCatalog</strong> - The name of the default catalog.
        Default: not set</li>
    <li><strong>connectionInitSqls</strong> - A list of SQL statements
        run once after a Connection is created. Separate multiple statements
        by semicolons (<code>;</code>). Default: no statement</li>
    <li><strong>connectionProperties</strong> - A list of driver specific
        properties passed to the driver for creating connections. Each
        property is given as <code>name=value</code>, multiple properties
        are separated by semicolons (<code>;</code>). Default: no properties</li>
    <li><strong>accessToUnderlyingConnectionAllowed</strong> - true or false: whether
        accessing the underlying connections is allowed. Default: false</li>
    </ul>
    <p>For more details, please refer to the commons-dbcp documentation.</p>

  </subsection>

</section>


<section name="Adding Custom Resource Factories">

  <p>If none of the standard resource factories meet your needs, you can write
  your own factory and integrate it into Tomcat 6, and then configure the use
  of this factory in the
  <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
  the web application. In the example below, we will create a factory that only
  knows how to create <code>com.mycompany.MyBean</code> beans from the
  <a href="#Generic JavaBean Resources">Generic JavaBean Resources</a> example
  above.</p>

  <h3>1.  Write A Resource Factory Class</h3>

  <p>You must write a class that implements the JNDI service provider
  <code>javax.naming.spi.ObjectFactory</code> inteface.  Every time your
  web application calls <code>lookup()</code> on a context entry that is
  bound to this factory, the <code>getObjectInstance()</code> method is
  called, with the following arguments:</p>
  <ul>
  <li><strong>Object obj</strong> - The (possibly null) object containing
      location or reference information that can be used in creating an object.
      For Tomcat, this will always be an object of type
      <code>javax.naming.Reference</code>, which contains the class name of
      this factory class, as well as the configuration properties (from the
      <a href="config/context.html"><code>&lt;Context&gt;</code></a> for the
      web application) to use in creating objects to be returned.</li>
  <li><strong>Name name</strong> - The name to which this factory is bound
      relative to <code>nameCtx</code>, or <code>null</code> if no name
      is specified.</li>
  <li><strong>Context nameCtx</strong> - The context relative to which the
      <code>name</code> parameter is specified, or <code>null</code> if
      <code>name</code> is relative to the default initial context.</li>
  <li><strong>Hashtable environment</strong> - The (possibly null)
      environment that is used in creating this object.  This is generally
      ignored in Tomcat object factories.</li>
  </ul>

  <p>To create a resource factory that knows how to produce <code>MyBean</code>
  instances, you might create a class like this:</p>

<source>
package com.mycompany;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {

  public Object getObjectInstance(Object obj,
      Name name2, Context nameCtx, Hashtable environment)
      throws NamingException {

      // Acquire an instance of our specified bean class
      MyBean bean = new MyBean();

      // Customize the bean properties from our attributes
      Reference ref = (Reference) obj;
      Enumeration addrs = ref.getAll();
      while (addrs.hasMoreElements()) {
          RefAddr addr = (RefAddr) addrs.nextElement();
          String name = addr.getType();
          String value = (String) addr.getContent();
          if (name.equals("foo")) {
              bean.setFoo(value);
          } else if (name.equals("bar")) {
              try {
                  bean.setBar(Integer.parseInt(value));
              } catch (NumberFormatException e) {
                  throw new NamingException("Invalid 'bar' value " + value);
              }
          }
      }

      // Return the customized instance
      return (bean);

  }

}
</source>

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

  <p>For more information about <code>ObjectFactory</code>, see the
  <a href="http://java.sun.com/products/jndi/docs.html">JNDI 1.2 Service
  Provider Interface (SPI) Specification</a>.</p>

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

  <h3>2.  Declare Your Resource Requirements</h3>

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

<source>
&lt;resource-env-ref&gt;
  &lt;description&gt;
    Object factory for MyBean instances.
  &lt;/description&gt;
  &lt;resource-env-ref-name&gt;
    bean/MyBeanFactory
  &lt;/resource-env-ref-name&gt;
  &lt;resource-env-ref-type&gt;
    com.mycompany.MyBean
  &lt;/resource-env-ref-type&gt;
&lt;/resource-env-ref&gt;
</source>

    <p><strong>WARNING</strong> - Be sure you respect the element ordering
    that is required by the DTD for web application deployment descriptors!
    See the
    <a href="http://wiki.apache.org/tomcat/Specifications">Servlet
    Specification</a> for details.</p>

  <h3>3.  Code Your Application's Use Of This Resource</h3>

  <p>A typical use of this resource environment reference might look
  like this:</p>

<source>
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
               bean.getBar());
</source>

    <h3>4.  Configure Tomcat's Resource Factory</h3>

    <p>To configure Tomcat's resource factory, add an elements like this to the
    <a href="config/context.html"><code>&lt;Context&gt;</code></a> element for
    this web application.</p>

<source>
&lt;Context ...&gt;
  ...
  &lt;Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="com.mycompany.MyBeanFactory"
            bar="23"/&gt;
  ...
&lt;/Context&gt;
</source>

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

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

</section>

</body>

</document>