ecsimsw

Spring 에서 정적 리소스를 다루는 네가지 방법 본문

Spring 에서 정적 리소스를 다루는 네가지 방법

JinHwan Kim 2020. 9. 13. 23:12

1. Static Resource 사용하기

스프링 부트에서는 /resources/static의 파일을 url 요청으로 접근할 수 있다. resources/static/file/hello.html을 접근한다면 

 

/localhost:8080/file/hello.html

 

기본 리소스 맵핑은 "/**"이지만, spring.mvc.static-path-pattern을 설정해서, url에 접근 경로를 지정할 수 있다. static path pattern은 application.yml에서 설정한다.

 

spring.mvc.static-path-pattern: /static/**

 

위의 예시처럼 /static/**으로 설정한다면, 이후로는 정적 리소를 localhost:port/static/ 아래에서 접근하는 것이다. resources/static/file/hello.html을 접근한다면 설정 이후에는 다음으로 경로를 지정하는 것으로 정적 리소스에 접근할 수 있다.

 

/localhost:8080/static/file/hello.html

 

2. ResourceLoader 객체 사용

ResourceLoader.getResource()으로 리소스를 찾을 수 있다. 

 

ResourceLoader는 빈으로 등록되어 있어 @Autowired로 자동 주입 받을 수 있고,  또는 Application Context가 상속하고 있기 때문에 Application Context나, ServeltContext으로도 getResource()를 사용할 수 있다.

 

Resource resource = resourceLoader.getResource("classpath:file/hello.html"); 

resource.exists();
resource.getFile();
resource.getURI();

 

3.  resources 상대 경로 얻기 / ServletContext.getRealPath()

현재 서비스가 되고 있는 서블릿의 상대 경로를 가져온다. 파일이 업로드되는 위치가 어떤 절대 경로가 아닌, 프로젝트에 상대적인 경로를 얻고 싶은 경우,

 

예를 들면  "C:\Users\ecsimsw\files\imgFiles"라는 절대적인 경로가 아닌, "/src/webapp/files/imgFiles"처럼 프로젝트에 상대적인 경로에 파일을 업로드 하고자 하는 경우 사용할 수 있다.

 

ServletContext.getRealPath()로, /webapp의 경로를 구할 수 있다.

 

String resourceSrc = request.getServletContext().getRealPath("/mainBoardImg");

 

위 예시라면 resourceSrc는 "/src/main/webapp/mainBoardImg"의 해당 물리 경로를 반환 받게 된다.

 

  ** webapp 폴더를 만들어 놓아야 경로가 반환된다. 

  

4. project/src/main 경로

project/src/main의 물리 경로를 얻고자 할 수 도 있을 것이다.

 

URL r = this.getClass().getResource("");

String path = r.getPath();

 

경로 예시

 

Comments