Setting User Environment Variables for tomcat on Windows
Asked Answered
B

1

8

I am running tomcat 8 on Windows Server 2012.

I have a web app that needs an user environment variable to be set in order to run.

I can start tomcat and retrieve the variable successfully like this:

set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_65
set CATALINA_HOME=C:\TOOLS\apache-tomcat-8.0.30

set CATALINA_BASE=C:\Users\ULUser\tomcat\myapp
set MY_VAR=%CATALINA_BASE%
set PATH=%CATALINA_ROOT%\bin;%PATH%
set CATALINA_OPTS="-Djava.security.properties=%CATALINA_BASE%\conf\java.security.properties"

%CATALINA_HOME%\bin\catalina.bat run

But when I run as a windows service I cannot retrieve the MY_VAR variable using System.getenv("MY_VAR");

Googling has not helped because all the pages show how to set the Java and Tomcat variables, but not how to set user variables.

I cannot set it for the entire machine because I have several instances of tomcat and each one needs a different environment variable.

I would prefer a method that involves setting the variable in the tomcat configuration rather that with windows configuration.

My alternative is to use context.xml file in tomcat and retrieve the value with logic that retrieves context settings.

Bemuse answered 7/11, 2016 at 2:13 Comment(0)
S
10

From an admin command prompt do the following command:

tomcat8 //US//YourServiceName ++Environment varname=value

You can set more than one variable by separating them with a semicolon (;) or a hash (#). The documentation is quite clear, but it's just difficult to believe anything's happened, because there's no visual indication anywhere, meaning if you run:

tomcat8w //ES//YourServiceName 

to get the GUI config tool you will not see the environment variable anywhere, but if you run the service it will pick it up. It's like hidden magic. Don't know why they haven't included it somewhere in the config panel.

Sink answered 6/12, 2016 at 11:45 Comment(2)
Just because I stumbled on this, a small addition to your answer: the parameters are maintained in the windows registry under (at least in a x64 Server operating system) WOW6432Node/Apache Software Foundation/Procrun 2.0/Tomcat8/Parameters, there is a key called Environment that holds the environment variables Tomcat uses when started as a service. There are also a few subkeys that hold additional information like the base directory, jvm directory etc.Schlegel
@DirkTrilsbeek The registry entry is actually not a key but a value named Environment of type REG_MULTI_SZ in the Parameters key.Underlinen

© 2022 - 2024 — McMap. All rights reserved.