Java中JNDI的简单字符串值

Java中JNDI的简单字符串值

本文介绍了Java中JNDI的简单字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在tomcat的配置中设置简单的字符串值然后在java应用程序中读取?

How can i set simple string value in configuration of tomcat and then read in java application?

context.xml

context.xml

<ResourceLink name="global/test" global="testing" type="java.lang.String" />

server.xml

server.xml

<Enviroment name="testing" value="myUser" type="java.lang.String"/>

应用程序中的web.xml

web.xml in application

<resource-env-ref>
    <resource-env-ref-name>global/test</resource-env-ref-name>
    <resource-env-ref-type>java.lang.String</resource-env-ref-type>
</resource-env-ref>
public String getValue(){
    return new JndiDataSourceLookup().getDataSource("global/test").toString();
}

当我运行tomcat时,我看到这些错误......

When i Run tomcat, i see these errors...

org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'global/test'; nested exception is javax.naming.NameNotFoundException: Name [global/test] is not bound in this Context. Unable to find [global].
javax.naming.NameNotFoundException: Name [global/test] is not bound in this Context. Unable to find [global].


推荐答案

在你的web.xml使用中,

In your web.xml use,

<env-entry>
<description>Sample env entry</description>
<env-entry-name>isConnected</env-entry-name>
<env-entry-type>java.lang.Boolean</env-entry-type><!--order matters -->
<env-entry-value>true</env-entry-value>
</env-entry>

在代码中,

try {
 Context initCxt =  new InitialContext();
 Boolean isConn =  (Boolean)initCxt.lookup("java:comp/env/isConnected");
 System.out.println(isConn.toString());
 // one could use relative names into the sub-context
 Context envContext = (Context) initCxt.lookup("java:comp/env");
 Boolean isConn2 = (Boolean)envContext.lookup("isConnected");
 System.out.println(isConn2.toString());
} catch (NamingException e) {
 e.printStackTrace();
}

看看这里,以便更好地理解InitialContext和JNDI。

Have a look here Naming service tutorial to get a good understanding of InitialContext and JNDI.

这篇关于Java中JNDI的简单字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:21