웹/Spring

HTTP 메시지 컨버터란?

컴퓨터과학 2023. 9. 3. 16:08

 

  1. 웹 브라우저가 "localhost:8080/hello-api" 접근
  2. 서버를 거쳐 helloController 호출
  3. helloController의 @ResponseBody를 통해 HttpMessageConverter가 호출
  4. return 타입에 따라 JsonConverter 또는 StringConverter를 이용해 return

@ResponseBody의 사용

  • HTTP의 Body에 문자 내용을 직접 반환
  • viewResolver 대신 HttpMessageConverter 동작
  • 기본 문자 처리: StringHttpMessageConverter
  • 기본 객체 처리: MappingJacksonHttpMessageConverter
  • 바이트 처리 등: HttpMessageConverter가 기본으로 등록

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

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;

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

ByteArrayHttpMessageConverter
StringHttpMessageConverter
MappingJacksonHttpMessageConverter
...

기본적으로 위의 컨버터들을 지원함
대상 클래스 타입과 미디어 타입을 체크해 사용여부 결정
(만족하지 않는 경우 다음 메시지 컨버터로 우선순위 넘어감)
ex)
StringHttpMessageConverter

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

MappingJackson2HttpMessageConverter

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

컨버트 실패

content-type:text/html
@RequestMapping
void hello(@Request HelloData data){}

HTTP 요청 데이터 읽기

  1. HTTP 요청이 들어오고, 컨트롤러에서 @RequestBody나 HttpEntity 파라미터 사용
  2. 메시지 컨버터가 canRead() 호출    // 읽을 수 있는 메시지인지 확인
    - 대상 클래스 타입과 HTTP의 Content-Type 미디어 타입 지원하는지
  3. canRead() 만족 시 read() 호출해 객체 생성 및 반환


HTTP 응답 데이터 생성

  • 컨트롤러에서 @ResponseBody나 HttpEntity로 값 반환
  • 메시지 컨버터가 canWrite() 호출    // 메시지를 쓸 수 있는지 확인
    - 대상 클래스 타입과 HTTP의 Accept 미디어 타입 지원하는지
  • canWrite() 만족 시 write() 호출해 HTTP 응답 메시지 바디에 데이터 생성

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의

웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., 원

www.inflearn.com