관리 메뉴

샐님은 개발중

10. HTTP 메세지 컨버터 본문

스프링 MVC 1편 -인프런 김영한/섹션6-스프링MVC - 기본 기능

10. HTTP 메세지 컨버터

샐님 2023. 7. 10. 23:33
728x90
반응형

1. HTTP 메세지 컨버터

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

@ResponseBody 사용 원리

 

 - HTTP 의 BODY에 문자 내용을 직접 반환

 - viewResolver 대신 HttpMessageConverter 가 동작

 - 기본 문자처리 : StringHttpMessageonverter , 기본 객체처리 : MappingJackson2HttpMessageConverter (json) 처리

 - btye 처리 등 기타 여러 HttpMessageconverter 가 기본으로 등록되어 있다. 

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

 

스프링 MVC  HTTP 메시지 컨버터 적용

 - HTTP 요청 :  @RequestBody , HttpEntity(RequestEntitiy) -HTTP 응답 : @ResponseBody, HttpEntity()ResponseEntity)

 

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

 

몇가지 주요한 메시지 컨버터
ByteArrayHttpMessageConverter : byte[] 데이터를 처리
클래스 타입: byte[] , 미디어타입: */* ,
요청 예) @RequestBody byte[] data
응답 예) @ResponseBody return byte[] 쓰기 미디어타입 application/octet-stream
StringHttpMessageConverter : String 문자로 데이터를 처리
클래스 타입: String , 미디어타입: */*
요청 예) @RequestBody String data
응답 예) @ResponseBody return "ok" 쓰기 미디어타입 text/plain
MappingJackson2HttpMessageConverter : application/json
클래스 타입: 객체 또는 HashMap , 미디어타입 application/json 관련
요청 예) @RequestBody HelloData data
응답 예) @ResponseBody return helloData 쓰기 미디어타입 application/json 관련

 

 

StringHttpMessageConverter
content-type: application/json
@RequestMapping
void hello(@RequestBody String data) {}
MappingJackson2HttpMessageConverter
content-type: application/json
@RequestMapping
void hello(@RequestBody HelloData data) {}
?
content-type: text/html
@RequestMapping
void hello(@RequestBody HelloData data) {}

 

 

 

 

 

   

728x90
반응형