Spring MVC - HttpMessageConverter, HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler

2021. 4. 8. 23:48카테고리 없음

HttpMessageConverter

  • Http 요청 메시지를 받을 때, @RequestBody나 HttpEntity를 이용해 받거나,
  • Http 응답 메시지를 작성할 때, @ResponseBody나 HttpEntity를 이용해 작성하면 메시지 컨버터라는 놈이 말 그대로 메시지를 변환해준다.
  • 예를 들어, 컨트롤러 메서드에서 DTO로 리턴을 하고, 클라이언트에서 JSON으로 받기를 원할때(Accept) 메시지 컨버터가 알아서 DTO를 JSON으로 변환하여 Http 응답 메시지 바디에 넣어주는 것이다.
  • 그래서 HttpMessageConverter 인터페이스를 확인해보면 스펙에 canRead(), canWrite(), read(), write()가 있는 것을 확인할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
package org.springframework.http.converter;
 
public interface HttpMessageConverter<T> {
 
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
 
    List<MediaType> getSupportedMediaTypes();
 
    T read(Class<extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
}
cs
  • canRead() , canWrite() : 메시지 컨버터가 해당 클래스, 미디어타입을 지원하는지 체크
  • read() , write() : 메시지 컨버터를 통해서 메시지를 읽고 쓰는 기능

 

스프링 부트 기본 메시지 컨버터

0 = ByteArrayHttpMessageConverter -> 바이트 변환
1 = StringHttpMessageConverter -> 스트링 변환
2 = MappingJackson2HttpMessageConverter -> JSON 변환

 

  • 메시지 컨버터는 대상 클래스 타입과 미디어 타입을 체크하여 사용여부를 결정한다. 조건에 맞지 않으면 다음 메시지 컨버터로 우선순위가 넘어가게 된다.

 

HandlerMethodArgumentResolver

  • 개발자는 컨트롤러 메서드(핸들러 메서드)의 파라미터로 HttpServletRequest, Model, @RequestBody, @ModelAttribute 등 다양한 타입을 받을 수 있다. 개발자가 필요로 하는 이런 객체를 생성해주는 것이 바로 HandlerMethodArgumentResolver이다. 
  • RequestMappingHandlerAdaptor가 컨트롤러를 호출하기 전에 HandlerMethodArgumentResolver에게 컨트롤러에 맞는 파라미터 객체 생성을 요청하고 객체가 생성되면 어뎁터가 컨트롤러를 호출할때 해당 객체를 넣어준다.

HandlerMethodReturnValueHandler

  • 개발자는 컨트롤러 메서드의 리턴 타입으로 String, ModelAndView, void, ResponseEntity 등 다양한 타입을 리턴할 수 있다. ArgumentResolver와 마찬가지로 응답값을 변환한다.