달력

42024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

context root path

 

Servlet

절대경로

 

getServletContext().getRealPath("/")); // 웹서버의 Document Root

ex) getServletContext().getRealPath("/WEB-INF/web.xml")); 

 

또는 

 

config.getServletContext().getRealPath("/");

 

또는

 

getServletConfig().getServletContext().getRealPath("/");

 

또는

 

request.getSession().getServletContext().getRealPath("/");

 


 

JAVA

 

절대경로

 

this.getClass().getResource("").getPath(); // 현재 자신의 절대 경로

 

this.getClass().getResource("/").getPath(); // classes 폴더의 최상위 경로

 

this.getClass().getResource("/com/test/config/config.properties").getPath(); // classes 폴더에서부터 시작하여 해당파일까지의 절대 경로

 

this.getClass().getProtectionDomain().getCodeSource().getLocation(); // 자신의 파일명(*.class)이 포함된 절대경로

 

 

 

System.getProperty("user.home"); // 사용자 홈 디렉토리

 

System.getProperty("user.dir");  // 이클립스에서 실행시 이클립스 워크스페이스 (해당 프로젝트명 전까지)

 


 

ClassLoader 사용법

 

ClassLoader classLoader = (Thread.currentThread()).getContextClassLoader();

 

if(classLoader==null) classLoader = ClassLoader.getSystemClassLoader();

 

URL url = classLoader.getResource("struts.properties");

 

System.out.println(url.getPath());

 

WEB-INF/classes 에 있는 리소스만 참조합니다.

 

WEB-INF 와 같이 바로 아래에 있는 있는 리소스는 참조하지 못합니다.

 

getSystemClassLoader는 java application에서 사용되는 방법이고

 

(Thread.currentThread()).getContextClassLoader() 는 web에서 사용되는 방법입니다.

 

현재 클래스가 상속되는(부모) 클래스라면 클래스명.class.getResource 로 해야 합니다.

 

getClass()는 실행되는 현재 자신(자식클래스가 될 수 있습니다.)을 가리키기 때문입다.

 

WEB의 절대경로와는 다릅니다.

 

new File("").getAbsolutePath() : 절대경로

 

new File("").getCanonicalPath() : 상대경로

Posted by 한설림
|