Tomcat中的ResourceLink元素不起作用

时间:2013-03-16 09:00:07

标签: java java-ee tomcat7 jndi

我正在使用apache-tomcat-7.0.35。我在server.xml中定义了一个环境变量,如下所示

<GlobalNamingResources>

        <Environment name="sam" 
                 value="D:\AppServers\apache-tomcat-7.0.35\conf\sample.xml"
                 type="java.lang.String" override="true"/>

  </GlobalNamingResources>

我在context.xml

中使用了我的上下文元素中的ResourceLink元素
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Practice_1" docBase="/Practice_1"
    crossContext="true" reloadable="true" debug="1">
<ResourceLink name="sam" global="sam" type="java.lang.String"/>

</Context>

当我尝试使用

在代码中获取此值时
 Context initCtx = new InitialContext();
        String configPath = (String)initCtx.lookup("sam");

投掷javax.naming.NameNotFoundException.javax.naming.NameNotFoundException: Name [sam] is not bound in this Context. Unable to find [sam].

我该如何纠正这个?

2 个答案:

答案 0 :(得分:1)

如果我没有错,你不需要修改server.xml。

修改后的context.xml

<Resource auth="Container"            java.naming.factory.initial="org.jnp.interfaces.NamingContextFactory" 
factory="de.example.CXIResourceLocator"
name="bean/CXIResourceLocator"
type="de.example.Bean"/>

的web.xml

<resource-env-ref>
    <description>
        Connection pooling.
    </description>
    <resource-env-ref-name>bean/CXIResourceLocator</resource-env-ref-name>
    <resource-env-ref-type>
        de.example.Bean
    </resource-env-ref-type>
</resource-env-ref>

bean/CXIResourceLocator should match in both context and web xmls.

由于我不知道你这样做的目的,我无法帮助你。 : - (

请点击此链接了解更多详情。 Apache给出了非常好的例子。

希望这有帮助。 http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html

答案 1 :(得分:1)

tomcat jndi有默认名称空间“java:comp / env”。

将您的代码修改为

Context initCtx = new InitialContext();
String configPath = (String)initCtx.lookup("java:comp/env/sam");

Context initCtx = new InitialContext();
Context rootCtx = (Context) initCtx.lookup("java:comp/env");
String configPath = (String)rootCtx.lookup("sam");