JNDI Resources How-To

Tomcat Home
The Apache Software Foundation
Apache Tomcat 8
Version 8.5.54, Apr 3 2020
Links

Docs Home
FAQ
User Comments

User Guide

1) Introduction
2) Setup
3) First webapp
4) Deployer
5) Manager
6) Host Manager
7) Realms and AAA
8) Security Manager
9) JNDI Resources
10) JDBC DataSources
11) Classloading
12) JSPs
13) SSL/TLS
14) SSI
15) CGI
16) Proxy Support
17) MBeans Descriptors
18) Default Servlet
19) Clustering
20) Load Balancer
21) Connectors
22) Monitoring and Management
23) Logging
24) APR/Native
25) Virtual Hosting
26) Advanced IO
27) Additional Components
28) Mavenized
29) Security Considerations
30) Windows Service
31) Windows Authentication
32) Tomcat's JDBC Pool
33) WebSocket
34) Rewrite

Reference

Release Notes
Configuration
Tomcat Javadocs
Servlet 4.0 Javadocs
JSP 2.3 Javadocs
EL 3.0 Javadocs
WebSocket 1.1 Javadocs
JASPIC 1.1 Javadocs
Common Annotations 1.2 Javadocs
JK 1.2 Documentation

Apache Tomcat Development

Building
Changelog
Status
Developers
Architecture
Functional Specs.
Tribes

JNDI Resources How-To
Table of Contents

Introduction
web.xml configuration
context.xml configuration
Global configuration
Using resources
Tomcat Standard Resource Factories
    Generic JavaBean Resources
    UserDatabase Resources
    JavaMail Sessions
    JDBC Data Sources
Adding Custom Resource Factories

Introduction

Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.xml file to reference/define resources.

See the following Specifications for more information about programming APIs for JNDI, and for the features supported by Java Enterprise Edition (Java EE) servers, which Tomcat emulates for the services that it provides:

Java Naming and Directory Interface (included in JDK 1.4 onwards)
Java EE Platform Specification (in particular, see Chapter 5 on Naming)

web.xml configuration

The following elements may be used in the web application deployment descriptor (/WEB-INF/web.xml) of your web application to define resources:

<env-entry> - Environment entry, a single-value parameter that can be used to configure how the application will operate.
<resource-ref> - Resource reference, which is typically to an object factory for resources such as a JDBC DataSource, a JavaMail Session, or custom object factories configured into Tomcat.
<resource-env-ref> - Resource environment reference, a new variation of resource-ref added in Servlet 2.4 that is simpler to configure for resources that do not require authentication information.

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

Tomcat provides a number of Tomcat specific options for JNDI resources that cannot be specified in web.xml. These include closeMethod that enables faster cleaning-up of JNDI resources when a web application stops and singleton that controls whether or not a new instance of the resource is created for every JNDI lookup. To use these configuration options the resource must be specified in a web application’s element or in the element of $CATALINA_BASE/conf/server.xml.
context.xml configuration

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 elements that can be specified in either $CATALINA_BASE/conf/server.xml or, preferably, the per-web-application context XML file (META-INF/context.xml).

Tomcat specific resource configuration is performed using the following elements in the element:

<Environment> - Configure names and values for scalar environment entries that will be exposed to the web application through the JNDI InitialContext (equivalent to the inclusion of an <env-entry> element in the web application deployment descriptor).
<Resource> - Configure the name and data type of a resource made available to the application (equivalent to the inclusion of a <resource-ref> element in the web application deployment descriptor).
<ResourceLink> - Add a link to a resource defined in the global JNDI context. Use resource links to give a web application access to a resource defined in the <GlobalNamingResources> child element of the <Server> element.
<Transaction> - Add a resource factory for instantiating the UserTransaction object instance that is available at java:comp/UserTransaction.

Any number of these elements may be nested inside a element and will be associated only with that particular web application.

If a resource has been defined in a element it is not necessary for that resource to be defined in /WEB-INF/web.xml. However, it is recommended to keep the entry in /WEB-INF/web.xml to document the resource requirements for the web application.

Where the same resource name has been defined for a element included in the web application deployment descriptor (/WEB-INF/web.xml) and in an element as part of the element for the web application, the values in the deployment descriptor will take precedence only if allowed by the corresponding element (by setting the override attribute to “true”).
Global configuration

Tomcat maintains a separate namespace of global resources for the entire server. These are configured in the element of $CATALINA_BASE/conf/server.xml. You may expose these resources to web applications by using a to include it in the per-web-application context.

If a resource has been defined using a , it is not necessary for that resource to be defined in /WEB-INF/web.xml. However, it is recommended to keep the entry in /WEB-INF/web.xml to document the resource requirements for the web application.
Using resources

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

// 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();

Tomcat Standard Resource Factories

Tomcat includes a series of standard resource factories that can provide services to your web applications, but give you configuration flexibility (via the element) without modifying the web application or the deployment descriptor. Each subsection below details the configuration and usage of the standard resource factories.

See Adding Custom Resource Factories for information about how to create, install, configure, and use your own custom resource factory classes with Tomcat.

NOTE - Of the standard resource factories, only the “JDBC Data Source” and “User Transaction” factories are mandated to be available on other platforms, and then they are required only if the platform implements the Java Enterprise Edition (Java EE) specs. All other standard resource factories, plus custom resource factories that you write yourself, are specific to Tomcat and cannot be assumed to be available on other containers.
Generic JavaBean Resources
0. Introduction

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

The steps required to use this facility are described below.

  1. Create Your JavaBean Class

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

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;
}

}

  1. Declare Your Resource Requirements

Next, modify your web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will request new instances of this bean. The simplest approach is to use a element, like this:

Object factory for MyBean instances. bean/MyBeanFactory com.mycompany.MyBean

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.
3. Code Your Application’s Use Of This Resource

A typical use of this resource environment reference might look like this:

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());

  1. Configure Tomcat’s Resource Factory

To configure Tomcat’s resource factory, add an element like this to the element for this web application.

<Context …>



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

Some beans have properties with types that cannot automatically be converted from a string value. Setting such properties using the Tomcat BeanFactory will fail with a NamingException. In cases were those beans provide methods to set the properties from a string value, the Tomcat BeanFactory can be configured to use these methods. The configuration is done with the forceString attribute.

Assume our bean looks like this:

package com.mycompany;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class MyBean2 {

private InetAddress local = null;

public InetAddress getLocal() {
return local;
}

public void setLocal(InetAddress ip) {
local = ip;
}

public void setLocal(String localHost) {
try {
local = InetAddress.getByName(localHost);
} catch (UnknownHostException ex) {
}
}

private InetAddress remote = null;

public InetAddress getRemote() {
return remote;
}

public void setRemote(InetAddress ip) {
remote = ip;
}

public void host(String remoteHost) {
try {
remote = InetAddress.getByName(remoteHost);
} catch (UnknownHostException ex) {
}
}

}

The bean has two properties, both are of type InetAddress. The first property local has an additional setter taking a string argument. By default the Tomcat BeanFactory would try to use the automatically detected setter with the same argument type as the property type and then throw a NamingException, because it is not prepared to convert the given string attribute value to InetAddress. We can tell the Tomcat BeanFactory to use the other setter like that:

<Context …>



The bean property remote can also be set from a string, but one has to use the non-standard method name host. To set local and remote use the following configuration:

<Context …>



Multiple property descriptions can be combined in forceString by concatenation with comma as a separator. Each property description consists of either only the property name in which case the BeanFactory calls the setter method. Or it consist of name=method in which case the property named name is set by calling method method. For properties of types String or of primitive type or of their associated primitive wrapper classes using forceString is not needed. The correct setter will be automatically detected and argument conversion will be applied.
UserDatabase Resources
0. Introduction

UserDatabase resources are typically configured as global resources for use by a UserDatabase realm. Tomcat includes a UserDatabaseFactory that creates UserDatabase resources backed by an XML file - usually tomcat-users.xml

The steps required to set up a global UserDatabase resource are described below.

  1. Create/edit the XML file

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

<?xml version="1.0" encoding="UTF-8"?>
  1. Declare Your Resource

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

The pathname attribute can be a URL, an absolute path or a relative path. If relative, it is relative to $CATALINA_BASE.

The readonly attribute is optional and defaults to true if not supplied. If the XML is writeable then it will be written to when Tomcat starts. WARNING: When the file is written it will inherit the default file permissions for the user Tomcat is running as. Ensure that these are appropriate to maintain the security of your installation.

If referenced in a Realm, the MemoryUserDatabse will, by default, monitor pathname for changes and reload the file if a change in the last modified time is observed. This can be disabled by setting the watchSource attribute to false.
3. Configure the Realm

Configure a UserDatabase Realm to use this resource as described in the Realm configuration documentation.
JavaMail Sessions
0. Introduction

In many web applications, sending electronic mail messages is a required part of the system’s functionality. The Java Mail API makes this process relatively straightforward, but requires many configuration details that the client application must be aware of (including the name of the SMTP host to be used for message sending).

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

The steps required for this are outlined below.

  1. Declare Your Resource Requirements

The first thing you should do is modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured sessions. By convention, all such names should resolve to the mail subcontext (relative to the standard java:comp/env naming context that is the root of all provided resource factories. A typical web.xml entry might look like this:

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. mail/Session javax.mail.Session Container

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.
2. Code Your Application’s Use Of This Resource

A typical use of this resource reference might look like this:

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);

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 element for the web application as described below.
3. Configure Tomcat’s Resource Factory

To configure Tomcat’s resource factory, add an elements like this to the element for this web application.

<Context …>

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

Additional resource attributes and values will be converted to properties and values and passed to javax.mail.Session.getInstance(java.util.Properties

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值