HTTP 요청 매핑하기 : 미디어 타입 매핑
특정한 데이터를 담고 있는 요청만 처리하는 핸들러
@RequestMapping(consumes=MediaType.APPLIATION_JSON_UTF8_VALUE)
- Content-Type 헤더를 통해 필터링 한다.
- 매치되지 않는 경우에는
415 Unsupported Media Type
으로 응답한다.
특정한 타입의 응답을 만드는 핸들러
@RequetMapping(produces="application/json")
- Accept 헤더로 필터링 (하지만 살짝 오묘함 왜냐하면 요청측에서 Accept 헤더를 따로 명시하지 않는 경우에 모든 타입에 대해 수용한다는 의미이기 때문에 필터링 되지 않음)
- 매치 되지 않는 경우에
406 Not Acceptable
응답
팁
-
문자열을 직접 입력하는 대신 MediaType을 사용하면 상수를 통해 IDE의 자동완성을 사용해 오타를 줄일 수 있다.
-
클래스에 선언한
@RequestMapping
에 사용한 것과 이어져 조합이 되지 않고 메소드에 사용한@RequestMapping
의 설정을 덮어쓴다. -
Not(
!
)연산자를 사용해서 특정 미디어 타입이 아닌 경우로 매핑할 수도 있다.Expressions can be negated by using the “!” operator, as in “!text/plain”, which matches all requests with a Content-Type other than “text/plain”.
예제 코드
@Controller
public class SampleController {
@ResponseBody
@RequestMapping(
value = "/hello",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String hello() {
return "hello";
}
}
테스트 코드
헤더를 조작하기 위해 get메소드 뒤에 사용한 메소드에 주의 깊게 살펴보자.
@ExtendWith(SpringExtension.class)
@WebMvcTest
class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void helloTest() throws Exception {
mockMvc.perform(get("/hello")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_PLAIN))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("hello"))
.andExpect(handler().handlerType(SampleController.class))
.andExpect(handler().methodName("hello"));
}
}
댓글남기기