Search code examples
javaapachetomcatstripes

How can I read Apache Httpd Env variables from a Java application running in TomCat?


I have a couple of Java applications running in TomCat containers behind Apache Httpd. In Apache Httdp you can set Env variables with SetEnv FOO bar, if you have mod_env installed. How can I read those variables in my Java applications running inside TomCat? The Java applications are mostly build with Stripes, if that helps.


Solution

  • Because Tomcat is started outside of Apache it does not have access to the Apache environment. This means you need some way of passing environment variables from Apache to Tomcat.

    If you are connecting Apache and Tomcat using mod_jk, you can use the JkEnvVar directive to pass specific variables to Tomcat. From the mod_jk documentation:

    The directive JkEnvVar allows you to forward environment variables from Apache server to Tomcat engine. You can add a default value as a second parameter to the directive. If the default value is not given explicitly, the variable will only be send, if it is set during runtime. The variables can be retrieved on the Tomcat side as request attributes via request.getAttribute(attributeName). Note that the variables send via JkEnvVar will not be listed in request.getAttributeNames().

    If you are using the HTTP proxy (mod_proxy) instead of mod_jk, you can pass environment variables as request headers using mod_headers, something like:

    RequestHeader set X-MYVAR %{MYVAR}e
    

    ...and then in Tomcat you would have to extract the X-MYVAR header.