본문 바로가기

Tomcat/Properties file

Tomcat Properties example

Tomcat 사용시 Properties 파일 운용 예

 

Test Environment:

Tomcat 7, Windows 7


Tomcat 을 사용할 때 Properties 파일을 사용할 때가 있는데 다음과 같이 대략 3가지 방법을 생각할 수 있다.


application.properties

editorPath=C:/Program Files/Notepad++/notepad++.exe

stRootDir=D:/test


1. properties 파일을 Tomcat의 디폴트 클래스패스(WEB-INF/classes, WEB-INF/lib)에 두는 경우, 파일명만 지정하면 된다

Properties prop = new Properties();

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties")

prop.load(is);

prop.getProperty("editorPath");


2. properties 파일을 웹폴더(WebContent) 에 두는 경우, 웹폴더를 루트로 삼아 그 하위경로(WEB-INF 등)를 지정해주면 된다

Properties prop = new Properties();

InputStream is = getServletContext().getResourceAsStream("/WEB-INF/application.properties")

prop.load(is);

prop.getProperty("editorPath");


3. properties 파일을 톰캣이 인식하지 못하는 톰캣 외부에 두는 경우, 절대경로를 사용한다

Properties prop = new Properties();

InputStream is = new FileInputStream("/absolute/path/to/application.properties");

prop.load(is);

prop.getProperty("editorPath");


실제 사용 예(application.properties 파일을 WEB-INF/classes/안에 두는 경우)

private static String rootDir;// = "D:/test";

private static String editorPath;

static {

InputStream is;

try {

Properties prop = new Properties();

is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");

prop.load(is);

editorPath = prop.getProperty("editorPath");

rootDir = prop.getProperty("stRootDir");

is.close();

} catch (Exception e) {

e.printStackTrace();

}

}