title: Accessing a system-property from a Tomcat-container using Java
body: <p>Environment: Java (Java EE), Tomcat container</p>
  
  <p>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:</p>
  
  <pre><code>System.getProperty( "myProp" );
  </code></pre>
  
  <p>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.</p>
  
  <p>So I'm trying to fix that.
  From my research it seems that the way to do this in Tomcat is via Tomcat's <code>server.xml</code> file, something like this:</p>
  
  <pre><code> &lt;Environment name="myProp" type="java.lang.String" value="This is my value"/&gt;
  </code></pre>
  
  <p>Then, from what I've read <a href="http://tomcat.apache.org/tomcat-4.1-doc/config/globalresources.html" rel="nofollow">here</a>, accessing 'myProp' should be the same thing as accessing an <code><code>&lt;env-entry</code>></code> in the <code>web.xml</code>, so image I have an entry like this:</p>
  
  <pre><code> &lt;env-entry&gt;
          &lt;env-entry-name&gt;myOtherProp&lt;/env-entry-name&gt;
          &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
          &lt;env-entry-value&gt;This is my other value&lt;/env-entry-value&gt;
    &lt;/env-entry&gt;
  </code></pre>
  
  <p>Then I have implemented the following code in my <code>Spring#handleRequestInternal()</code>:</p>
  
  <pre><code>Context ctx = new InitialContext();
  
  String myProp = "&lt;not found&gt;";
  try {
        myProp = (String) ctx.lookup( "java:comp/env/myProp" );  // from Tomcat's server.xml
  } catch( Exception e ) { ... }
  
  String myOtherProp = "&lt;not found&gt;";
  try {
        myOtherProp = (String) ctx.lookup( "java:comp/env/myOtherProp" ); // from web.xml
  } catch( Exception e ) { ... }
  </code></pre>
  
  <p>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).</p>
  
  <p>What gives?
  How do I set an environment-variable outside of my app via the Tomcat-container and retrieve it from within my app?</p>