티스토리 뷰

Dev/Spring

Spring Web Static Resources

Alxndr 2020. 11. 11. 23:13

Spring Web static resources

오늘은 Spring Web에서 지원해주는

정적 리소스 경로 맵핑에 대해 공유해보겠습니다.

정적 리소스는 동적으로 만들어지지 않는 리소스 ex) 사진, javascript 등을 말합니다.

기본 리소스 위치

  • classpath:/static
  • classpath:/public
  • classpath:/resources
  • classpath:/META-INF/resources

html 생성

프로젝트 resources → static → hello.html

  • hello.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Hello World</title>
      </head>
      <body>
      Hello Static Resource 오호호
      </body>
      </html>

서버 실행 후 브라우저에서 확인해보겠습니다.


개발자 도구 (F12)를 열어서 Network 탭을 열어둔 후 다시 새로고침을 해보면

응답 코드가 200이 아닌 304로 내려온다.

이유는 브라우저가 가지고 있는 마지막 수정시간과 서버에서의 수정시간을 비교해서

변경내역이 없는 경우 304로 캐시 된 데이터를 내리게 된다.

ResourceHttpReqeustHandler가 처리합니다.

custom 경로

위와 같이 설정을 하게 되면 아까와 같이

http://localhost:8080/hello.html 이 아닌

http://localhost:8080/static/hello.html로 요청해야 정상적으로 나오게 됩니다.

굳이 변경할 필요가 있을까 싶지만... 알아만 두겠습니다.

spring.mvc.static-location : 리소스 찾을 위치 변경

하지만 위에 이미 지정되어있는 경로들도 못쓰게 되어서 아래의 방법을 추천합니다.

  • WebConfig.java

      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
      import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
      @Configuration
      public class WebConfig implements WebMvcConfigurer {
    
          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
              registry.addResourceHandler("/alxndr/**")
                      .addResourceLocations("classpath:/alxndr/")
                      .setCachePeriod(20);
      // 캐싱 전략을 따로 해줘야함.
          }
      }

위 코드와 같이 기존 경로들도 유지하면서 원하는 경로를 추가해줄 수 있습니다.

감사합니다.

 

Github

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함