-
스프링 MVC - 기본 기능스프링/스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 2024. 1. 16. 22:05
@ResponseBody 사용 원리
@ResponseBody를 사용
- HTTP의 BODY에서 문자내용을 직접 반환
- 뷰 리졸버 대신에 HttpMessageConverter가 동작
- 기본 문자처리: StringHttpMessageConverter
- 기본 객체처리: MappingJackson2HttpMessageConverter
- byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록
HTTP 메시지 컨버터
뷰 템플릿으로 HTML을 생성해서 응답하는 것이 아니라, HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우, HTTP 메시지 컨버트를 사용하면 편리하다.스프링 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 요청, 응답 둘 다 사용된다
- canRead(), canWrite() : 메시지 컨버터가 해당 클래스, 미디어타입을 지원하는 지 체크
- read(), write() : 메시지 컨버터를 통해서 메시지를 읽고, 쓰는 기능
스프링 부트 기본 메시지 컨버터
0 = ByteArrayHttpMessageConvert 1 = StringHttpMessageConvert 2 = MappingJackson2HttpMessageConverter
스프링 부트는 다양한 메시지 컨버터를 제공하는데, 대상 클래스 타입과 미디어 타입 둘을 체크해서 사용여부를 체크한다.
만약 만족하지 않으면 다음 메시지 컨버터로 우선순위가 넘어간다.
몇가지의 주요한 메시지 컨버터를 알아보자
- ByteArrayHttpMessageConverter : byte[] 데이터를 처리한다.
- 클래스 타입: byte[], 미디어 타입: *\*,
- 요청 예) @RequestBody String data
- 응답 예) @ResponseBody return "ok"
- 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 관련
'스프링 > 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술' 카테고리의 다른 글
스프링 MVC- 구조이해 (0) 2024.01.12 프론트 컨트롤러 패턴 (0) 2024.01.12 MVC 패턴 (1) 2024.01.08 웹 어플리케이션 이해 (0) 2024.01.04