[SpringBoot][WebMVC] 정적 리소스 지원

2022. 11. 9. 12:09JAVA/Spring

1. 정적 리소스 맵핑 “/**”

  • 기본 리소스 위치
    • classpath:/static
    • classpath:/public
    • classpath:/resources/
    • classpath:/META-INF/resources
    • 예) “/hello.html” ⇒ /static/hello.html
    • spring.mvc.static-path-pattern: 맵핑 설정 변경 가능
    • spring.mvc.static-locations: 리소스 찾을 위치 변경 가능 (비권장)
  • Last-Modified 헤더를 보고 304 응답을 보냄
    • 정적 리소스가 수정되면 200 응답을 보냄
    • 정적 리소스가 수정되지 않은 상태에서 다시 자원을 요청시 304 응답을 보냄
    • 304 응답을 보내면서 정적 리소스를 다시 보내지는 않음(빨리짐을 의미함)
  • ResourceHttpRequestHandler가 처리함
    • WebMvcConfigurer의 addResourceHandlers로 커스터마이징 할 수 있음 (권장)
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
	registry.addResourceHandler("/m/**")
				.addResourceLocations("classpath:/m/")
				.setCachePeriod(20);
}

 

 

 

2. 실습, 정적 리소스 생성

정적 리소스는 서버쪽에서 이미 만들어놓은 자원을 그대로 이용하는 것을 말합니다. 예를 들어 “/hello.html” 요청이 들어오면 /static 디렉토리에서 hello.html 파일을 탐색하여 보내는 것입니다.

1. /static/hello.html 생성

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello world</h1>
</body>
</html>

 

2. 스프링부트 애플리케이션 실행하고 브라우저 주소창에 “http://localhost:8080/hello.html” 요청하여 실행결과 확인

3. 개발자도구에서 hello.html의 응답 상태를 확인

  • status=304이므로 hello.html 자원은 요청시 수정되지 않았다는 것을 의미합니다.

 

4. hello.html을 수정하고 다시 서버에 hello.html 요청

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello world modified</h1>
</body>
</html>

 

5. 정적 리소스를 수정한 상태에서 다시 클라이언트가 수정한 정적 리소스를 요청하고 응답 상태를 확인합니다.

  • 정적 리소스가 수정되었기 때문에 200을 응답합니다.
  • If-Modified-Since : 해당 시간으로부터 정적 리소스가 수정된 것이 있으면 새로 응답하게 됩니다.

 

3. 실습, 정적 리소스 맵핑 설정 변경

1. application.yml 파일에 다음과 같이 spring.mvc.static-path-pattern의 값을 설정하여 정적 리소스 맵핑 설정을 변경합니다.

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

 

2. 이전 예제의 정적 리소스인 hello.html을 요청하기 위해서는 “http://localhost:8080/hello.html”이 아닌 “http://localhost:8080/static/hello.html”을 요청해야 합니다.

 

 

4. 실습, WebMvcConfigurer의 addResourceHandlers로 원하는 리소스 디렉토리를 추가

장점

  • 기존 스프링부트가 제공하는 리소스 핸들러 유지
  • 사용자가 원하는 리소스 핸들러 추가 가능함

 

1. WebMvcConfigurer 인터페이스의 addResourceHandlers 메서드를 재정의하여 리소스 핸들러와 리소스 위치를 추가합니다.

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/m/**")
                .addResourceLocations("classpath:/m/")
                .setCachePeriod(20);

    }
}
  • 클라이언트에서 “/m/”으로 시작하는 요청이 오면 resources 디렉토리에서 “/m/”위치에서 해당하는 리소스가 있는지 탐색합니다.
  • 리소스 위치 추가시 반드시 “/”으로 끝나야 합니다. (classpath:/m/)

2. 브라우저에서 “http://localhost:8080/m/hello.html”을 요청하여 실행 결과를 확인합니다.

References

source code : https://github.com/yonghwankim-dev/springboot_study/tree/main/springboot_webmvc
[인프런] 스프링 부트 개념과 활용