Tomcat JNDI lookup problem
I was trying read a property value in Tomcat. My plan was to access the value using System.getProperty("LOGPATH")
where LOGPATH
is the name of my property. However I did not find a way to set a System property value in Tomcat.
Is there any way we can set a System property in Tomcat?
As I did not get any documentation on setting the System property I thought of accessing the value using JNDI. So I added the following entry
<Environment name="LOGPATH" type="java.lang.String" value="c:/temp" />
after
<GlobalNamingResources>
in server.xml
file.
The code I used for looking up the JNDI is
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env/");
String path = (String) envCtx.lookup("LOGPATH");
When I executed the above code, I got the following error message.
javax.servlet.ServletException: Name LOGPATH is not bound in this Context
org.apache.jasper.runtime.PageContextImpl.doHandlePage开发者_运维百科Exception(PageContextImpl.java:825)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
Then I added an entry in my web.xml
<resource-env-ref>
<resource-env-ref-name>LOGPATH</resource-env-ref-name>
<resource-env-ref-type>java.lang.String</resource-env-ref-type>
</resource-env-ref>
Now the error message is changed to
javax.naming.NamingException: Cannot create resource instance
org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:99)
What am I doing wrong now? Thank you for the help.
You also need a resource link in your web app's context. The context is generally placed in META-INF/context.xml and will look something like this:
<Context>
<Resource name="LOGPATH" global="LOGPATH" type="java.lang.String" />
</Context>
This "grants" the web app the rights to see the particular Environment
value.
As for setting system properties, just add a line to tomcat/conf/catalina.properties like so:
LOGPATH=C:/temp
Just note that system properties are available to all web apps where as JNDI entries are controlled per web app.
Make it an init-param in your web.xml, and access it via the ServetContext.
I coded my environment string in a context file under conf/Catalina/localhost and named the same as my webapp. Then I used Spring's JndiObjectFactoryBean to retrieve it. Hope this is of some help.
精彩评论