[스프링 MVC 1편] HTTP 메시지 컨버터

강신현·2022년 9월 21일
0

💡 HTTP 메시지 컨버터

뷰 템플릿으로 HTML을 생성해서 응답하는 것이 아니라, HTTP API처럼 JSON 데이터를 HTTP 메시지
바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다.

  • HTTP의 BODY에 문자 내용을 직접 반환
  • viewResolver 대신에 HttpMessageConverter 가 동작

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

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

📕 주요 메시지 컨버터

적용 순서 : ByteArrayHttpMessageConverter 👉 StringHttpMessageConverter 👉 MappingJackson2HttpMessageConverter

  1. ByteArrayHttpMessageConverter
  • byte[] 데이터를 처리한다.
  • 클래스 타입: byte[]
  • 미디어타입 : all
  • 요청 예) @RequestBody byte[] data
  • 응답 예) @ResponseBody return byte[] 쓰기 미디어타입 application/octet-stream
  1. StringHttpMessageConverter
  • String 문자로 데이터를 처리한다.
  • 클래스 타입: String
  • 미디어타입 : all
  • 요청 예) @RequestBody String data
  • 응답 예) @ResponseBody return "ok" 쓰기 미디어타입 text/plain
  1. MappingJackson2HttpMessageConverter
  • application/json
  • 클래스 타입: 객체 또는 HashMap
  • 미디어타입 : application/json 관련
  • 요청 예) @RequestBody HelloData data
  • 응답 예) @ResponseBody return helloData 쓰기 미디어타입 application/json 관련

예시 1

content-type: application/json

@RequestMapping
void hello(@RequetsBody String data) {}

👉 StringHttpMessageConverter 컨버터 동작

예시 2

content-type: application/json

@RequestMapping
void hello(@RequetsBody HelloData data) {}

👉 MappingJackson2HttpMessageConverter 컨버터 동작

예시 3

content-type: text/html

@RequestMapping
void hello(@RequetsBody HelloData data) {}

클래스 타입이 객체이지만 미디어 타입이 application/json 이 아닌 text/html 이므로
👉 적용 가능한 컨버터 없음


동작 위치


강의 출처

[인프런 - 김영한] 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술

profile
땅콩의 모험 (server)

0개의 댓글