---
title: "Jetty中使用JNDI设置环境变量"
author: "wintersun"
date: "2014-12-22T14:55:48Z"
tags: []
categories: ["开源软件"]
slug: "jetty-jndi"
draft: false
lastmod: "2014-12-22T14:55:48Z"
id: 2169219
url: "https://search.iteye.com/blog/2169219"
---

【目的】

Production使用WebSphere作为App Server，但主包方开发团队在Dev环境使用Tomcat binding to Eclipse，我更倾向于使用Mave Jetty Plugin——项目本身就是使用Maven进行依赖管理的！

 

【问题】

主包方开发团队要求在Tomcat的Server.xml中定义Naming Resource，用于访问WS-资源，如下：

```
 * - server.xml
 *  Add the following inside XML Tag <GlobalNamingResources> :
	<Environment name="wsPathPhq" override="false" type="java.lang.String" value="http://localhost:8080/cis2_ws/"/>
	<Environment name="wsPathNtn" override="false" type="java.lang.String" value="http://localhost:8080/cis2_ws/"/>
	<Environment name="defaultSite" override="false" type="java.lang.String" value="PHQ"/> <!-- PHQ or NTN -->
	<Environment name="uiOffShorePath" override="false" type="java.lang.String" value="http://localhost:8080/cis2_ui/"/>
	<Environment name="uiOffShoreName" override="false" type="java.lang.String" value="NTN"/>
```

然后在代码中使用javax.naming.InitialContext.lookup(String)进行查找。 但Jetty如何支持？

 

【解决方案】

在Jetty.xml中，加入如下部分：

```
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
	<New class="org.eclipse.jetty.plus.jndi.EnvEntry">
		<Arg></Arg>
		<Arg>wsPathPhq</Arg>
		<Arg type="java.lang.String">http://localhost:8080/cis2_ws/</Arg>
		<Arg type="boolean">true</Arg>
	</New>
...
```

 

【参考文档】https://wiki.eclipse.org/Jetty/Feature/JNDI

## Binding Objects into Jetty JNDI

You can bind four types of object into Jetty JNDI:

- An ordinary POJO instance.
- A [java.naming.Reference](http://java.sun.com/j2se/1.5.0/docs/api/javax/naming/Reference.html) instance.
- An object instance that implements the [java.naming.Referenceable](http://java.sun.com/j2se/1.5.0/docs/api/javax/naming/Referenceable.html) interface.
- A link between a name as referenced in `web.xml` and as referenced in the environment.

The binding for all of these object types follows the same pattern:

```
<New class=type of naming entry>
  <Arg>scope</Arg>
  <Arg>name to bind as</Arg>
  <Arg>the object to bind</Arg>
</New>
```

#### Defining Naming Entries

The `type of naming entry` can be:

- `"org.eclipse.jetty.plus.jndi.EnvEntry"` for &lt;env-entry&gt;s.
- `"org.eclipse.jetty.plus.jndi.Resource"` for all other type of resources.
- `"org.eclipse.jetty.plus.jndi.Transaction"` for a JTA manager. For detailed information, see the [Configuring XA Transactions](https://wiki.eclipse.org/Jetty/Feature/JNDI#Configuring_XA_Transactions) section.
- `"org.eclipse.jetty.plus.jndi.Link"` for link between a `web.xml` resource name and a NamingEntry. For more information, see the [Configuring Links](https://wiki.eclipse.org/Jetty/Feature/JNDI#Configuring_Links) section.

You can define naming entries in three places:

1. `jetty.xml`
2. `WEB-INF/jetty-env.xml`
3. context xml file