TOMCAT_OPTS, environment variable and System.getEnv()
我使用tomcat,我想在我的java代码中获取一个环境变量。
要设置环境变量,我使用以下bash命令:
1 | export TOMCAT_OPTS=-Dmy.var=foo |
之后,我开始tomcat
1 | ./startup.sh (in bin folder of tomcat) |
在我的Java代码中,我尝试获取此变量:
1 |
但是它返回NULL。
我怎样才能做到这一点 ?
我精确地指出,如果我使用maven启动tomcat并使用eclipse环境选项卡,则会找到该变量! 但是我需要在生产模式下像上面一样启动tomcat。
编辑:直接使用导出MY_VAR时,它在本地运行,但不在我的服务器上运行...
使用
我终于在CATALINA_HOME中找到了一个名为tomcat6.conf的配置文件。
我将export my.var = foo添加到文件的末尾,System.getenv(" my.var")现在返回值...
恶梦...
如果您使用的是tomcat7和unbuntu os,则可以编辑/ etc / default / tomcat7文件,
只需添加yourvar = yourvalue行即可。
如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # Run Tomcat as this user ID. Not setting this or leaving it blank will use the # default of tomcat7. TOMCAT7_USER=tomcat7 # Run Tomcat as this group ID. Not setting this or leaving it blank will use # the default of tomcat7. TOMCAT7_GROUP=tomcat7 IM4JAVA_TOOLPATH=/usr/local/bin/ # The home directory of the Java development kit (JDK). You need at least # JDK version 1.5. If JAVA_HOME is not set, some common directories for # OpenJDK, the Sun JDK, and various J2SE 1.5 versions are tried. #JAVA_HOME=/usr/lib/jvm/openjdk-6-jdk # You may pass JVM startup parameters to Java here. If unset, the default # options will be: -Djava.awt.headless=true -Xmx128m -XX:+UseConcMarkSweepGC # # Use"-XX:+UseConcMarkSweepGC" to enable the CMS garbage collector (improved # response time). If you use that option and you run Tomcat on a machine with # exactly one CPU chip that contains one or two cores, you should also add # the"-XX:+CMSIncrementalMode" option. JAVA_OPTS="-Djava.awt.headless=true -Xmx2048m -XX:+UseConcMarkSweepGC" |
在仅通过解压缩安装的Tomcat8中,有一个名为" catalina.properties"的文件
您可以通过添加以下内容在此文件中引入环境变量
1 | my.special.variable=some_value |
对于Tomcat7 + Ubuntu:
组:
添加行
注意:变量名称不能包含点。
读:
我相信有一个tomcat的配置文件,默认情况下位于
1 | MY_VAR=somevalue |
那应该对您的Java应用程序可用。
我知道这是一个古老的问题,但也许对其他人有用:)
如果要在tomcat中设置环境变量以通过getEnv进入,请使用setenv。
即在tomcat / bin中,您具有(或应创建)
1 2 | my.var=FOO OTHERVAR=BOO |
在
您是否在Eclipse IDE上使用Tomcat?然后,您只需要执行以下步骤:
现在,您已经向我解释了您正在使用基于yum的安装(这表明是Red Hat发行版的派生产品),如果您将Tomcat作为守护程序运行,那么您需要设置" export TOMCAT_OPTS = ..."命令在/ etc / profile中(用于全局范围),或将其添加到启动Tomcat实例的用户的家的?/ .profile或?/ .bashrc文件中。