이미지, 자바스크립트, CSS 그리고 HTML 파일과 같은 정적인 리소스를 처리하는 핸들러 등록하는 방법
디폴트(Default) 서블릿
스프링 MVC 리소스 핸들러 맵핑 등록
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello index</h1>
</body>
</html>
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloStatic() throws Exception {
this.mockMvc.perform(get("/index.html"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("Hello index")));
}
}
리소스 핸들러 설정
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello Mobile</h1>
</body>
</html>
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/mobile/**")
.addResourceLocations("classpath:/mobile/")
.setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES));
}
}
java도 classpath 루트가 되고 resources도 classpath 루트가 된다. classpath 접두어를 붙이지 않으면 src/main/webapp에서 리소스를 찾게 된다.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloStatic() throws Exception {
this.mockMvc.perform(get("/index.html"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("Hello index")));
}
@Test
public void mobilehelloStatic() 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));
}
참고