Environment: Java (Java EE), Tomcat container
At work the vast majority of our apps run in a Glassfish-container and (as typical) we have a lot of properties externalized from our apps and injected into our Glassfish-environment via the use of an app.properties file where Glassfish then exposes them to our app by making a standard system call something like this:
System.getProperty( "myProp" );
We have one particular app, however, than was deployed on a Tomcat-container (and due to the large bureaucracy here, that’s not going to change anytime soon); the original author also didn’t invest the time to research how to do a similar property-externalization using Tomcat as what is done with Glassfish. The result is that there are several things in this app where you have to comment-out some lines of code when you deploy it to our test-server and comment-out different lines of code when you deploy it to our production-server. A real pain, and potential-cause of trouble.
So I’m trying to fix that.
From my research it seems that the way to do this in Tomcat is via Tomcat’s server.xml file, something like this:
<Environment name="myProp" type="java.lang.String" value="This is my value"/>
Then, from what I’ve read here, accessing ‘myProp’ should be the same thing as accessing an in the <env-entry>web.xml, so image I have an entry like this:
<env-entry>
<env-entry-name>myOtherProp</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>This is my other value</env-entry-value>
</env-entry>
Then I have implemented the following code in my Spring#handleRequestInternal():
Context ctx = new InitialContext();
String myProp = "<not found>";
try {
myProp = (String) ctx.lookup( "java:comp/env/myProp" ); // from Tomcat's server.xml
} catch( Exception e ) { ... }
String myOtherProp = "<not found>";
try {
myOtherProp = (String) ctx.lookup( "java:comp/env/myOtherProp" ); // from web.xml
} catch( Exception e ) { ... }
Yet when I log ‘myProp’ and ‘myOtherProp’, the one from my web.xml returns the correct value while the one from Tomcat’s server.xml is not found (caught by the try/catch).
What gives?
How do I set an environment-variable outside of my app via the Tomcat-container and retrieve it from within my app?
Instead of putting this in server.xml it belongs in the Context.xml file for the servlet containter you’re configuring. See the tomcat Context configuration webpage. For more details.