I use tomcat and I want to get an environment variable in my java code.
To set an environment variable, I use this bash command :
export TOMCAT_OPTS=-Dmy.var=foo
After it I start tomcat
./startup.sh (in bin folder of tomcat)
In my java code, I try to get this variable :
System.getEnv("my.var")
But it returns NULL.
How can I do that ?
I precise that if I use maven to launch tomcat and use eclipse environment tab, the variable is found ! But I need to launch tomcat like above in production mode.
EDIT: when using export MY_VAR directly it runs in local but not on my server...
getenv(String name) method gets the value of the specified environment variable. An environment variable is a system-dependent external named value. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).
The getenv() function returns a pointer to the string containing the value for the specified varname in the current environment. If getenv() cannot find the environment string, NULL is returned, and errno is set to indicate the error.
System.getEnv
returns environment variables like PATH or, in your example, TOMCAT_OPTS).
When you invoke Java with -Dfoo=bar
, you don't set an environment variable : you pass a system property. Use System.getProperty
to get the value of foo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With