Programing

시작시 Tomcat 구성에서 시스템 속성을 어떻게 지정할 수 있습니까?

lottogame 2020. 10. 25. 11:29
반응형

시작시 Tomcat 구성에서 시스템 속성을 어떻게 지정할 수 있습니까?


-D 매개 변수와 함께 인수 (예 : " -Dmy.prop = value ") 를 전달하여 Tomcat에 시스템 특성을 지정할 수 있음을 이해합니다 .

context.xml 파일이나 다른 바람둥이 구성 파일에 속성 값을 지정하여이 작업을 수행하는 더 깨끗한 방법이 있는지 궁금합니다. 첫째, 내 속성을 추적하는 것이 더 쉽고 두 번째로 여러 컨텍스트가 실행 중이며 -D 매개 변수를 통해 컨텍스트 별 속성을 지정하는 방법을 모르기 때문에 이렇게하고 싶습니다.

Tomcat 버전 5.5를 사용하고 있습니다.


(업데이트 :이 답변을 삭제할 수 있다면 수락되었으므로 할 수 없지만 더 나은 지침을 제공하기 위해 설명을 업데이트하고 원래 답변에서 설명한 잘못된 관행을 사람들이 사용하지 못하도록 막습니다).

컨텍스트 또는 환경 매개 변수 (예 : context.xml)를 통해 이러한 매개 변수를 지정할 수 있습니다. 이 페이지의 "컨텍스트 매개 변수"및 "환경 항목"섹션을 참조하십시오.

http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

@netjeff가 지적했듯이 이러한 값은 시스템 매개 변수가 아닌 Context.lookup (String) 메서드를 통해 사용할 수 있습니다.

이러한 값을 지정하는 또 다른 방법은 배포중인 웹 애플리케이션의 web.xml 파일 내에 변수를 정의하는 것입니다 (아래 참조). @Roberto Lo Giacco가 지적했듯이 배포 된 아티팩트가 환경에 따라 달라서는 안되므로 일반적으로 이는 좋지 않은 방법으로 간주됩니다. 그러나 실제로 수행하려는 경우 구성 스 니펫은 다음과 같습니다.

<env-entry>
    <env-entry-name>SMTP_PASSWORD</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>abc123ftw</env-entry-value>
</env-entry>

<env-entry>System.getProperty () 만 사용할 때 사용 을 제안한 cliff.meyers 의 원래 답변은 도움이되지 않습니다.

Tomcat 6.0 문서에 따르면 <env-entry>JNDI 용 입니다. 즉,에 영향을 미치지 않습니다 System.getProperty().

<env-entry>에서 cliff.meyers 의 예를 들어, 다음 코드

System.getProperty("SMTP_PASSWORD");

"abc123ftw"값이 아닌 null을 반환합니다.

Tomcat 6 문서에 따르면 사용 <env-entry>하려면 다음과 같은 코드를 작성해야합니다 <env-entry>.

// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source
String s = (String)envCtx.lookup("SMTP_PASSWORD");

주의 사항 : 위의 예를 실제로 시도하지 않았습니다. 그러나 나는 노력 <env-entry>은 System.getProperty ()와 함께하고 있음을 확실히 일을하지 않습니다.


일반적으로 웹앱을 구성하기 위해 시스템 속성에 의존해서는 안됩니다. 컨테이너 (예 : Tomcat)를 구성하는 데 사용할 수 있지만 tomcat 내부에서 실행되는 애플리케이션에는 사용할 수 없습니다.

cliff.meyers는 웹 애플리케이션에 사용해야하는 방식을 이미 언급했습니다. 이것이 표준 방식이며 context.xml 또는 server.xml을 통해 구성 가능하다는 질문에도 적합합니다.

즉, Tomcat에서 시스템 속성이나 기타 jvm 옵션 (예 : 최대 메모리 설정)이 실제로 필요하면 "bin / setenv.sh"또는 "bin / setenv.bat"라는 파일을 만들어야합니다. 이러한 파일은 다운로드 한 표준 아카이브에 존재하지 않지만 존재하는 경우 시작하는 동안 콘텐츠가 실행됩니다 (startup.sh/startup.bat를 통해 tomcat을 시작하는 경우). 이것은 표준 바람둥이 설정에서 자신의 설정을 분리하는 좋은 방법이며 업데이트를 훨씬 쉽게 만듭니다. startup.sh 또는 catalina.sh를 조정할 필요가 없습니다.

(Windows 서비스로 tomcat을 실행하는 경우 일반적으로 tomcat5w.exe, tomcat6w.exe 등을 사용하여 서비스에 대한 레지스트리 설정을 구성합니다.)

편집 : 또한 또 다른 가능성은 JNDI 리소스 로 이동하는 것입니다 .


ServletContextListener가 시스템 속성을 설정하도록 할 수도 있습니다.

import java.util.Enumeration;
import javax.servlet.*;

public class SystemPropertiesHelper implements
        javax.servlet.ServletContextListener {
    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        Enumeration<String> params = context.getInitParameterNames();

        while (params.hasMoreElements()) {
          String param = (String) params.nextElement();
          String value = 
            context.getInitParameter(param);
          if (param.startsWith("customPrefix.")) {
              System.setProperty(param, value);
          }
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
    }
}

And then put this into your web.xml (should be possible for context.xml too)

<context-param>
        <param-name>customPrefix.property</param-name>
        <param-value>value</param-value>
        <param-type>java.lang.String</param-type>
</context-param>

<listener>
    <listener-class>servletUtils.SystemPropertiesHelper</listener-class>    
</listener>

It worked for me.


An alternative to setting the system property on tomcat configuration is to use CATALINA_OPTS environment variable


This question is addressed in the Apache wiki.

Question: "Can I set Java system properties differently for each webapp?"

Answer: No. If you can edit Tomcat's startup scripts (or better create a setenv.sh file), you can add "-D" options to Java. But there is no way in Java to have different values of system properties for different classes in the same JVM. There are some other methods available, like using ServletContext.getContextPath() to get the context name of your web application and locate some resources accordingly, or to define elements in WEB-INF/web.xml file of your web application and then set the values for them in Tomcat context file (META-INF/context.xml). See http://tomcat.apache.org/tomcat-7.0-doc/config/context.html .

http://wiki.apache.org/tomcat/HowTo#Can_I_set_Java_system_properties_differently_for_each_webapp.3F


You could add necessary properties to catalina.properties file in <tomcat installation directory>/conf directory.

Reference: https://tomcat.apache.org/tomcat-8.0-doc/config/index.html

All system properties are available including those set using the -D syntax, those automatically made available by the JVM and those configured in the $CATALINA_BASE/conf/catalina.properties file.


If you want to define an environment variable in your context base on documentation you shod define them as below

<Context ...>
  ...
  <Environment name="maxExemptions" value="10"
         type="java.lang.Integer" override="false"/>
  ...
</Context>

Also use them as below:

((Context)new InitialContext().lookup("java:comp/env")).lookup("maxExemptions")

You should get 10 as output.

참고URL : https://stackoverflow.com/questions/372686/how-can-i-specify-system-properties-in-tomcat-configuration-on-startup

반응형