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 메시지 컨터버 인터페이스
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 문자로 데이터를 처리한다.
- 클래스 타입 : String, 미디어 타입 : */*
- 요청 예) @RequestBody byte[] data
- 응답 예) @ResponseBody return "ok" 쓰기 미디어타입 text/plain
- MappingJackson2HttpMessageConverter : application/json
- 클래스 타입 : 객체 또는 HashMap, 미디어타입 application/json 관련
- 요청 예) @RequestBody HelloData data
- 응답 예) @ResponseBody return HelloData 쓰기 미디어타입 application/json 관련
HTTP 요청 데이터 읽기
- HTTP 요청이 오고, 컨트롤러에서 @RequestBody, HttpEntity 파라미터를 사용한다.
- 메시지 컨버터가 메시지를 읽을 수 있는지 확인하기 위해 canRead()를 호출한다.
- 대상 클래스 타입을 지원하는가
- 예) @RequestBody의 대상 클래스 (byte[], String, HeloData)
- HTTP 요청의 Content-Type 미디어 타입을 지원하는가
- 예) text/plain, application/json. */*
- 대상 클래스 타입을 지원하는가
- canRead() 조건을 만족하면 read()를 호출해서 객체 생성하고, 반환한다.
HTTP 응답 데이터 생성
- 컨트롤러에서 @ResponseBody, HttpEntity로 값이 반환된다.
- 메시지 컨버터가 메시지를 쓸 수 있는지 확인하기 위해 canWrite()를 호출한다.
- 대상 클래스 타입을 지원하는가.
- 예) return의 대상 클래스 (byte[], String, HelloData)
- HTTP 요청의 Accpet 미디어 타입을 지원하는가. (@RequestMapping의 produces)
- 예) text/plain, applicaion/json, */*
- 대상 클래스 타입을 지원하는가.
- canWrite() 조건을 만족하면 write()를 호출해서 HTTP 응답 메시지 바디에 데이터를 생성한다.
요청 매핑 핸들러 어뎁터 구조
RequestMappingHandlerAdapter 동작 방식
ArgumentResolver
다양한 파라미터를 유연하게 처리할 수 있는 이유는 ArgumentResolver 덕분이다.
애노테이션 기반 컨트롤러를 처리하는 RequestMappingHandlerAdapter는 바로 이 ArgumentResolver를 호출해서 컨트롤러(핸들러)가 필요로 하는 다양한 파라미터의 값(객체)를 생성한다. 이렇게 파라미터의 값이 모두 준비되면 컨트롤러를 호출하면서 값을 넘겨준다.
정확히는 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()를 호출해서 실제 객체를 생성한다. 그리고 이렇게 생성된 객체가 컨트롤러 호출 시 넘어가는 것이다.
ReturnValueHandler
HandlerMethodReturnValueHandler를 줄여서 ReturnValueHandler라 부른다.
ArgumentResolver와 비슷한데, 이것은 응답 값을 변환하고 처리한다.
컨트롤러에서 String으로 뷰 이름을 반환해도, 동작하는 이유가 바로 ReturnValueHandler 덕분이다.
HTTP 메시지 컨버터
HTTP 메시지 컨버터를 사용하는 @RequestBody도 컨트롤러가 필요로 하는 파라미터의 값에 사용된다. @ResponseBody의 경우도 컨트롤러의 반환 값을 이용한다.
요청의 경우 @RequestBody를 처리하는 ArgumentResolver가 있고, HttpEntity를 처리하는 ArgumentResolver가 있다. 이 ArgumentResolver들이 HTTP 메시지 컨버터를 사용해서 필요한 객체를 생성하는 것이다.
응답의 경우 @ResponseBody와 HttpEntity를 처리하는 ReturnValueHandler가 있다. 그리고 여기에서 HTTP 메시지 컨버터를 호출해서 응답 결과를 만든다.
스프링 MVC는 @RequestBody @ResponseBody가 있으면 RequestResponseBodyMethodProcessor (ArgumentResolver, ReturnValueHandler 둘다 구현) HttpEntity 가 있으면 HttpEntityMethodProcessor(ArgumentResolver, ReturnValueHandler 둘다 구현) 를 사용한다.
ArgumentResolver로 파라미터를 바인딩 시킨 다음, HttpMessageConverter로 body의 값을 객체로 변환
확장
스프링은 다음을 모두 인터페이스로 제공한다. 따라서 언제든지 기능을 확장할 수 있다.
- HandlerMethodArgumentResolver
- HandlerMethodReturnValueHandler
- HttpMessageConverter
'Spring > Spring MVC' 카테고리의 다른 글
스프링 MVC Validation - BindingResult, Field Error, Object Error (1) | 2024.10.01 |
---|---|
스프링 메세지, 국제화 (3) | 2024.10.01 |
스프링 MVC 응답 (0) | 2024.09.30 |
스프링 MVC 요청 파라미터 , 요청 메시지 (1) | 2024.09.30 |
스프링 MVC 요청 - 기본, 헤더 조회 (2) | 2024.09.30 |