-
Resource HandlerSPRING/스프링 MVC 2021. 6. 16. 15:23
이미지, 자바스크립트, CSS 그리고 HTML 파일과 같은 정적인 리소스를 처리하는 핸들러 등록하는 방법
리소스 핸들러 설정
- 어떤 요청 패턴을 지원할 것인가
- 어디서 리소스를 찾을 것인가
- 캐싱
- ResourceResolver: 요청에 해당하는 리소스를 찾는 전략
Ex:) 캐싱, 인코딩(gzip, brotli), WebJar
- ResourceTransformer: 응답으로 보낼 리소스를 수정하는 전략
Ex:) 캐싱, CSS 링크, HTML5 AppCache
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // TODO Auto-generated method stub // addResourceHandler : mobile/ url로 들어오는 요청 // addResourceLocations : classpath 기준 mobile 경로 위치 // 캐싱을 10분간 실행 registry.addResourceHandler("/mobile/**") .addResourceLocations("classpath:/mobile/") .setCacheControl(CacheControl.maxAge(10,TimeUnit.MINUTES)); } }
크롬 개발자도구의 Network탭을 보면 상태코드가 304 응답이 나오게 된다.
10분간 Last-Modified 값이 변경되지 않는다.
이렇게 캐싱하는 경우에는 리소스 응답 전체를 다시 받지 않기 때문에, 속도가 더 빠르고 트래픽도 조금 쓰게 된다.
테스트 코드
@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class SampleControllerTest { @Autowired MockMvc mockMvc; @Test public void mobileStatic() throws Exception { this.mockMvc.perform(get("/mobile/index.html")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(Matchers.containsString("hello mobile"))) .andExpect(header().exists(HttpHeaders.CACHE_CONTROL)); } }
'SPRING > 스프링 MVC' 카테고리의 다른 글
HTTP 메시지 컨버터 : JSON (0) 2021.06.18 HTTP 메시지 컨버터 : 개요 (0) 2021.06.18 HandlerInterceptor (서블릿 필터 비교) (0) 2021.06.15 Formatter 추가하기 (0) 2021.06.14 스프링 부트에서 JSP 사용하기 (0) 2021.06.13