본문 바로가기

카테고리 없음

[Spring MVC] HTTP 메시지 컨버터(JSON<=>Object)

반응형

HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다.

서블릿 처리 살펴보기

@ResponseBody 사용 원리

  • ResponseBody를 사용
    • HTTP의 BODY에 문자 내용을 직접 반환
    • viewResolver 대신에 HttpMessageConverter 가 동작
    • 기본 문자처리: StringHttpMessageConverter
    • 기본 객체처리: MappingJackson2HttpMessageConverter
    • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

응답의 경우 클라이언트의 HTTP Accept 해더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서 HttpMessageConverter 가 선택된다.

스프링 MVC는 다음의 경우에 HTTP 메시지 컨버터를 적용한다.

  • HTTP 요청: @RequestBody , HttpEntity(RequestEntity)
  • HTTP 응답: @ResponseBody , HttpEntity(ResponseEntity)

 

HTTP 메시지 컨버터 인터페이스

org.springframework.http.converter.HttpMessageConverter

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;
}

 HTTP 메시지 컨버터는 HTTP 요청, HTTP 응답 둘 다 사용된다.

  • canRead() , canWrite() : 메시지 컨버터가 해당 클래스, 미디어타입을 지원하는지 체크
  • read() , write() : 메시지 컨버터를 통해서 메시지를 읽고 쓰는 기능

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

(생략 많음)

0 = ByteArrayHttpMessageConverter
1 = StringHttpMessageConverter
2 = MappingJackson2HttpMessageConverter

 

  • 스프링 부트는 다양한 메시지 컨버터를 제공한다.
  • 대상 클래스 타입과 미디어 타입 둘을 체크해서 사용여부를 결정한다.
  • 만약 만족하지 않으면 다음 메시지 컨버터로 우선순위가 넘어간다.

주요한 메시지 컨버터

  • ByteArrayHttpMessageConverter : byte[] 데이터를 처리한다. 주로 파일 업로드.
    • 클래스 타입: byte[] , 미디어타입: */* ,
    • 요청 예) @RequestBody byte[] data
    • 응답 예) @ResponseBody return byte[] 쓰기
      • 응답 미디어타입 application/octet-stream

StringHttpMessageConverter

 String 문자로 데이터를 처리한다.

  content-type: application/json
  @RequestMapping
  void hello(@RequetsBody String data) {}

 클래스 타입: String , 미디어타입: */*

  • 요청 예) @RequestBody String data
  • 응답 예) @ResponseBody return "ok" 
  • 응답 미디어타입 text/plain

MappingJackson2HttpMessageConverter

application/json관련 타입을 처리한다.

content-type: application/json
  @RequestMapping
  void hello(@RequetsBody HelloData data) {}

클래스 타입: 객체 또는 HashMap , 미디어타입 application/json 관련
요청 예) @RequestBody HelloData data
응답 예) @ResponseBody return helloData 응답 미디어타입 application/json 관련

 메세지 컨버터 작동 메커니즘

HTTP 요청 데이터 읽기

  • HTTP 요청이 오고, 컨트롤러에서 @RequestBody , HttpEntity 파라미터를 사용한다.
  • 메시지 컨버터가 메시지를 읽을 수 있는지 확인하기 위해 canRead() 를 호출한다.
    • 대상 클래스 타입을 지원하는가.
      • ) @RequestBody 의 대상 클래스 ( byte[] , String , HelloData )
    • HTTP 요청의 Content-Type 미디어 타입을 지원하는가.
      • ) text/plain , application/json , */*
    • canRead() 조건을 만족하면 read() 를 호출해서 객체 생성하고, 반환한다.

HTTP 응답 데이터 생성

  • 컨트롤러에서 @ResponseBody , HttpEntity 로 값이 반환된다.
  • 메시지 컨버터가 메시지를 쓸 수 있는지 확인하기 위해 canWrite() 를 호출한다.
    • 대상 클래스 타입을 지원하는가.
      • 예) return의 대상 클래스 ( byte[] , String , HelloData )
    • HTTP 요청의 Accept 미디어 타입을 지원하는가(우선순위 2).(더 정확히는 @RequestMapping 의 produces -있으면 우선순위 1)
      • 예) text/plain , application/json , */*
  • canWrite() 조건을 만족하면 write() 를 호출해서 HTTP 응답 메시지 바디에 데이터를 생성한다.

 예제로 알아보기

content-type: text/html
@RequestMapping
void hello(@RequetsBody HelloData data) {}
  • byte[] 타입 아님. (파일 업로드)
  • String 타입 아님.
  • 객체 타입인데, application/json 관련 아님.
컨버터를 찾을 수 없다거나, 컨버팅을 할 수 없다는 예외가 발생하게 됩니다.

 

요청 매핑 헨들러 어뎁터 구조

그렇다면 HTTP 메시지 컨버터는 스프링 MVC 어디쯤에서 사용되는 것일까?

모든 비밀은 애노테이션 기반의 컨트롤러(@RequestMapping)을 처리하는 핸들러 어댑터인

RequestMappingHandlerAdapter (요청 매핑 헨들러 어뎁터)에 있다.

 

RequestMappingHandlerAdapter 동작 방식

RequestMappingHandlerAdapter&nbsp;동작 방식

 

ArgumentResolver(HandlerMethodArgumentResolver)

 애노테이션 기반의 컨트롤러는 매우 다양한 파라미터를 사용할 수 있었다.

HttpServletRequest , Model 은 물론이고,

@RequestParam , @ModelAttribute 같은 애노테이션

그리고 @RequestBody , HttpEntity 같은 HTTP 메시지를 처리하는 부분까지 매우 큰 유연함을 보여주었다.
이렇게 파라미터를 유연하게 처리할 수 있는 이유가 바로 ArgumentResolver 덕분이다

애노테이션 기반 컨트롤러를 처리하는 RequestMappingHandlerAdaptor

바로 이 ArgumentResolver 를 호출해서

컨트롤러(핸들러)가 필요로 하는 다양한 파라미터의 값(객체)을 생성한다.

그리고 이렇게 파리미터의 값이 모두 준비되면 컨트롤러를 호출하면서 값을 넘겨준다.

스프링은 30개가 넘는 ArgumentResolver 를 기본으로 제공한다.

 

 

요약 :

ArgumentResolver는 컨트롤러의 파라미터를 본다(리플렉션으로 가능.)

자신이 지원 가능하면 ServletRequest객체를 이용해 해당 파라미터로 객체를 만들어 넘겨준다.

 

가능한 파라미터 목록은 다음 공식 메뉴얼에서 확인할 수 있다.
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-arguments

 

정확히는 HandlerMethodArgumentResolver 인데 줄여서 ArgumentResolver 라고 부른다.

public interface HandlerMethodArgumentResolver {
      
      boolean supportsParameter(MethodParameter parameter);
	  
      
      @Nullable
      Object resolveArgument(MethodParameter parameter, @Nullable
      ModelAndViewContainer mavContainer,
                NativeWebRequest webRequest, @Nullable WebDataBinderFactory
      binderFactory) throws Exception;
}

동작 방식

ArgumentResolver supportsParameter() 를 호출해서 해당 파라미터를 지원하는지 체크하고,

지원하면 resolveArgument() 를 호출해서 실제 객체를 생성한다.

그리고 이렇게 생성된 객체가 컨트롤러 호출시 넘어가는 것이다.

그리고 원한다면 직접 이 인터페이스를 확장해서 원하는 ArgumentResolver 를 만들 수도 있다.

ReturnValueHandler

HandlerMethodReturnValueHandler 를 줄여서 ReturnValueHandle 라 부른다. ArgumentResolver 와 비슷한데, 이것은 응답 값을 변환하고 처리한다.

컨트롤러에서 String으로 뷰 이름을 반환해도, 동작하는 이유가 바로 ReturnValueHandler 덕분이다.

 

스프링은 10여개가 넘는 ReturnValueHandler 를 지원한다.

예) ModelAndView , @ResponseBody , HttpEntity , String

가능한 응답 값 목록은 다음 공식 메뉴얼에서 확인할 수 있다.

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-return-types

 

HTTP 메시지 컨버터

HTTP 메시지 컨버터 위치.

HTTP 메시지 컨버터는 어디쯤 있을까?

ArgumentResolver와 ReturnValueHandler에서 HTTP 메시지 컨버터를 이용한다.
HTTP 메시지 컨버터를 사용하는 @RequestBody 도 컨트롤러가 필요로 하는 파라미터의 값에 사용된다.

또한, @ResponseBody 의 경우도 컨트롤러의 반환 값을 이용한다.

요청의 경우 @RequestBody 를 처리하는 ArgumentResolver 가 있고,

HttpEntity 를 처리하는 ArgumentResolver 가 있다.

ArgumentResolver 들이 HTTP 메시지 컨버터를 사용해서 필요한 객체를 생성하는 것이다. 

 

응답의 경우 @ResponseBody HttpEntity 를 처리하는 ReturnValueHandler 가 있다.

그리고 여기에서 HTTP 메시지 컨버터를 호출해서 응답 결과를 만든다.

스프링 MVC는 @RequestBody @ResponseBody 가 있으면 RequestResponseBodyMethodProcessor (ArgumentResolver)
HttpEntity 가 있으면 HttpEntityMethodProcessor (ArgumentResolver)를 사용한다.

 HttpMessageConverter 를 구현한 클래스를 한번 확인해보자.

확장

스프링은 다음을 모두 인터페이스로 제공한다. 따라서 필요하면 언제든지 기능을 확장할 수 있다.

  • HandlerMethodArgumentResolver
  • HandlerMethodReturnValueHandler
  • HttpMessageConverter

스프링이 필요한 대부분의 기능을 제공하기 때문에 실제 기능을 확장할 일이 많지는 않다.

기능 확장은 WebMvcConfigurer 를 상속 받아서 스프링 빈으로 등록하면 된다.

실제 자주 사용하지는 않으니 실제 기능 확장이 필요할 때 WebMvcConfigurer 를 검색해보자.

WebMvcConfigurer 확장

@Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addArgumentResolvers(List<HandlerMethodArgumentResolver>
            resolvers) {
            //...
                 }
            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>>
            converters) {
            //...
            } 
        };
}

 

다시한번 요약

ArgumentResolver는 컨트롤러(핸들러)의 파라미터 타입을 조사한다.

자신이 support가능하면,  HttpMessageConverter를 이용하여 핸들러의 파라미터를 만들어 핸들러를 호출한다.

ReturnValueHandler는 핸들러의 응답값과 애노테이션, 리턴 타입, Content-Type, Accept 정보를 이용해 응답 메세지를 생성한다.

 

 

참고 

응답 content-Type으로

일반적으로 urlencoded, multipart, json 포맷 등을 사용합니다.

text/html 형식은 거의 없다고 보시면 됩니다.

 

 

Web on Servlet Stack

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, “Spring Web MVC,” comes from the name of its source module (spring-webmvc), but it is more com

docs.spring.io

 

HTTP Accept 헤더 : 클라이언트가 해석할 수 있는 mime type

바디에 메세지가 있으면 컨텐츠 타입과 length를 지정해줘야 함

반응형