뷰 템플릿으로 HTML을 생성해서 응답하는 것이 아니라, HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다
스프링 MVC는 다음의 경우에 HTTP 메시지 컨버터를 적용한다
@RequestBody
,HttpEntity(RequestEntity)
@ResponseBody
,HttpEntity(ResponseEntity)
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;
}
canRead()
,canWrite()
: 메시지 컨버터가 해당 클래스, 미디어 타입을 지원하는지 체크read()
,write()
: 메시지 컨버터를 통해 읽거나 쓰는 기능0 = ByteArrayHttpMessageConverter
1 = StringHttpMessageConverter
2 = MappingJackson2HttpMessageConverter
스프링 부트는 다양한 메시지 컨버터를 제공하는데, 대상 클래스 타입과 미디어 타입 둘을 체크해서 사용여부를 결정한다. 만족하지 않으면 다음 메시지 컨버터로 우선순위가 넘어간다.
1.ByteArrayHttpMessageConverter
: byte[]
데이터를 처리한다
byte[]
, 미디어 타입: */*
@RequestBody byte[] data
@ResponseBody return byte[]
쓰기 미디어 타입: application/octet-stream
2.StringHttpMessageConverter
: String 문자로 데이터를 처리한다.
String
, 미디어 타입: */*
@RequestBody String data
@ResponseBody return "ok"
쓰기 미디어 타입: text/plain
3.MappingJackson2HttpMessageConverter
:application/json
HashMap
, 미디어 타입: application/json
@RequestBody HelloData data
@ResponseBody return helloData
쓰기 미디어 타입: application/json
관련
메시지 컨버터들의 대표적 예시)
StringMessageConverter
content-type: application/json
@RequestMapping
void hello(@RequetsBody String data) {}
MappingJackson2HttpMessageConverter
content-type : application/json
@RequestMapping
void hello(@RequestBody HelloData data) {}
X(안되는 예시)
content-type : text/html
@RequestMapping
void hello(@RequetsBody HelloData data) {}
@RequestBody
,HttpEntity
파라미터를 사용한다canRead()
를 호출한다.@RequestBody
의 대상 클래스 (byte[], String, 객체)text/plain
, application/json
, */*
canRead()
조건을 만족하면, read()
를 호출해서 객체를 생성하고, 반환한다.@ResponseBody
,HttpEntity
로 값이 반환된다.canWrite()
를 호출한다.produces
)text/plain
, application/json
,*/*
canWite()
조건을 만족하면, write()
를 호출해서 HTTP 응답 메시지 바디에 데이터를 생성한다.