HttpMessageConverter
📌 클라이언트와 서버 간의 HTTP 요청과 응답을 처리할 때 데이터 형식 변환을 담당 한다. 클라이언트가 보낸 데이터를 서버가 이해할 수 있는 형태로 변환하거나, 서버가 응답으로 보내는 데이터를 클라이언트가 이해할 수 있는 형태로 변환할 때 사용됩니다. [ View를 응답하는 것이 아닌, Rest API(HTTP API)로 JSON, TEXT, XML 등의 데이터를 응답 Message Body에 직접 입력하는 경우 HttpMessageConverter를 사용한다. ]
- 1. SSR → @Controller + View Template → 서버 측에서 화면을 동적으로 그린다.
- 2. CSR → @RestController + Data → 클라이언트 측에서 화면을 동적으로 그린다.
- 3. 실제로는 두가지 기술이 함께 사용되는 경우가 많다.
- HTTP 응답 메세지 Body에 데이터를 직접 입력 후 반환한다.
- 요청 Accept Header + Controller 반환 타입
ViewResolver가 아닌 HttpMessageConverter가 동작한다.
- HttpMessageConverter가 적용되는 경우
- HTTP 요청 : @RequestBody, HttpEntity<>, RequestEntity<>
- HTTP 응답 : @ResponseBody, HttpEntity<>, ResponseEntity<>
- HttpMessageConverter는 요청과 응답 모두 사용된다.
@RestController = @Controller + @ResponseBody |
우선순위
📌 Spring은 다양한 HttpMessageConverter를 제공하고 있고 우선순위가 있다. 대상 Class와 MediaType을 체크해서 어떤 Converter를 사용할지 결정한다.
동작 순서와 예시
요청 데이터 읽기
위 코드는 Spring Framework에서 REST API를 구현한 예제입니다. RESTful 엔드포인트를 제공하며, 클라이언트로부터 JSON 데이터를 받고, 처리 후 JSON 데이터를 응답으로 반환합니다. 아래에서 각 부분을 상세히 분석하겠습니다.
1. 클래스 수준 어노테이션
@RestController
- @RestController:
- **@Controller**와 **@ResponseBody**를 합친 기능을 합니다.
- 이 클래스의 모든 메서드는 기본적으로 JSON 또는 XML 형식으로 응답을 생성합니다. (HTML View가 아닌 데이터만 반환)
- 따라서 각 메서드에 **@ResponseBody**를 명시할 필요가 없습니다.
2. 메서드 수준 어노테이션
@PostMapping(value = "/example", produces = "application/json")
- @PostMapping:
- HTTP POST 요청을 처리하는 메서드를 정의합니다.
- value = "/example": 이 API는 /example URL에 매핑됩니다.
- produces = "application/json": 이 API는 클라이언트에게 JSON 형식으로 응답을 반환합니다.
3. 메서드 파라미터
public ResponseDto example(@RequestBody RequestDto dto)
- @RequestBody:
- 클라이언트가 요청 본문에 포함한 데이터를 읽어와, Java 객체(RequestDto)로 변환합니다.
- Spring은 **HttpMessageConverter**를 사용해 JSON 데이터를 RequestDto로 변환합니다.
- 이 메서드는 클라이언트가 보낸 JSON 데이터를 받아, 내부에서 사용할 수 있는 DTO 객체로 변환하여 사용합니다.
- 예: 클라이언트가 다음과 같은 JSON 데이터를 보냈다고 가정:
-> Spring이 이 JSON 데이터를 RequestDto 객체로 변환합니다.{ "id": 123, "name": "Example" }
4. 메서드 로직
ResponseDto responseDto = service.example(dto);
- service.example(dto):
- 서비스 계층으로 RequestDto 데이터를 전달하여, 요청을 처리합니다.
- 서비스 계층은 보통 비즈니스 로직을 처리하는 곳입니다. (데이터베이스 호출, 데이터 변환 등)
- 처리 결과를 ResponseDto 객체로 반환받습니다.
return responseDto;
- 반환값:
- ResponseDto 객체를 반환합니다.
- Spring은 **HttpMessageConverter**를 사용해 ResponseDto 객체를 JSON으로 변환하여 클라이언트에게 응답합니다.
5. DTO(Data Transfer Object)
- RequestDto:
- 클라이언트에서 전송한 데이터를 담는 객체입니다.
- 예시:
public class RequestDto { private int id; private String name; // Getters and Setters }
- ResponseDto:
- 처리 결과를 클라이언트로 반환할 때 사용하는 객체입니다.
- 예시:
public class ResponseDto { private String status; private String message; // Getters and Setters }
6. 전체 실행 흐름
- 클라이언트가 /example로 POST 요청을 보냅니다. 요청 본문에 JSON 데이터를 포함합니다.
{ "id": 123, "name": "Example" }
- Spring은 JSON 데이터를 RequestDto 객체로 변환합니다.
- example 메서드가 호출되어 RequestDto 데이터를 서비스 계층으로 전달합니다.
- 서비스 계층이 요청 데이터를 처리하고, 결과를 ResponseDto로 반환합니다.
- ResponseDto 객체는 다시 JSON으로 변환되어 클라이언트에게 응답됩니다.
{ "status": "success", "message": "Operation completed" }
7. 주요 특징
- RESTful API: 데이터만을 전송하고 반환하는 RESTful 스타일의 API입니다.
- JSON 데이터 처리: HttpMessageConverter를 통해 JSON 데이터를 주고받습니다.
- 계층화: 서비스 계층을 사용해 비즈니스 로직과 컨트롤러 로직을 분리합니다.
- 재사용성: DTO 객체를 통해 데이터를 깔끔하게 전달하고 관리합니다.
boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType)는 Spring Framework의 HttpMessageConverter 인터페이스에서 정의된 메서드 중 하나로, 특정 타입의 객체를 지정된 미디어 타입(MediaType)으로 변환할 수 있는지 확인합니다. 이 메서드는 HTTP 응답을 생성할 때 사용됩니다.
메서드 정의
boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
파라미터
- Class<?> clazz:
- HTTP 응답으로 변환하려는 Java 객체의 클래스 타입입니다.
- 예: ResponseDto.class, String.class 등.
- 이 매개변수를 통해 현재 HttpMessageConverter가 처리 가능한 객체인지 확인합니다.
- @Nullable MediaType mediaType:
- 변환 대상의 **미디어 타입(MediaType)**입니다.
예: application/json, application/xml, text/plain 등. - @Nullable이므로 null일 수도 있습니다.
- null인 경우 미디어 타입과 관계없이 클래스 타입만 확인합니다.
- 변환 대상의 **미디어 타입(MediaType)**입니다.
반환값
- true: 이 HttpMessageConverter가 지정된 클래스와 미디어 타입에 대해 쓰기 작업(HTTP 응답 데이터 변환)을 처리할 수 있습니다.
- false: 처리할 수 없으면 false를 반환합니다.
메서드 동작
이 메서드는 Spring이 적절한 **HttpMessageConverter**를 선택할 때 사용됩니다. 요청 데이터의 Java 객체 타입과 응답 데이터의 미디어 타입을 비교하여 적합한 컨버터를 결정합니다.
- Spring은 등록된 여러 HttpMessageConverter를 순차적으로 탐색합니다.
- 각 컨버터의 canWrite 메서드를 호출하여, 특정 객체와 미디어 타입을 처리할 수 있는지 확인합니다.
- 적합한 컨버터를 찾으면 해당 컨버터가 쓰기 작업을 수행합니다.
사용 예시
JSON 변환 컨버터 예
MappingJackson2HttpMessageConverter는 JSON 데이터를 처리하는 HttpMessageConverter 구현체입니다. 이를 기준으로 canWrite 메서드를 구현하면 다음과 같이 동작합니다:
@Override
public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
// JSON 컨버터는 기본적으로 모든 객체 타입을 지원
if (mediaType == null || mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
return true; // JSON 형식으로 변환 가능
}
return false; // JSON 외 미디어 타입은 변환 불가
}
동작 방식
- clazz: 응답으로 반환할 객체의 클래스가 전달됩니다. 예: ResponseDto.class.
- mediaType: 응답 헤더의 Content-Type에 설정된 미디어 타입이 전달됩니다.
- 예: application/json, application/xml, text/plain.
만약 다음 요청이 왔다고 가정:
GET /api/example HTTP/1.1
Accept: application/json
Spring은 다음을 수행합니다:
- MappingJackson2HttpMessageConverter.canWrite(ResponseDto.class, application/json)를 호출합니다.
- canWrite가 true를 반환하면, JSON으로 응답을 변환합니다.
유스 케이스
- 클라이언트 요청 처리:
- 클라이언트가 Accept 헤더에 특정 미디어 타입을 요청한 경우, 해당 미디어 타입으로 응답을 생성할 수 있는지 확인합니다.
- 다양한 컨버터 사용:
- Spring은 여러 컨버터를 지원하므로, 각 컨버터가 자신이 지원하는 클래스와 미디어 타입만 처리하도록 canWrite를 구현합니다.
- 예: MappingJackson2HttpMessageConverter는 JSON 처리.
- StringHttpMessageConverter는 단순 텍스트 처리.
- Spring은 여러 컨버터를 지원하므로, 각 컨버터가 자신이 지원하는 클래스와 미디어 타입만 처리하도록 canWrite를 구현합니다.
흐름 예시
다음은 Spring이 canWrite를 호출하는 시나리오입니다:
- 컨트롤러에서 객체를 반환:
- @GetMapping("/example") public ResponseDto example() { return new ResponseDto("Success", "Operation completed"); }
- Spring이 등록된 HttpMessageConverter들을 순회하며 canWrite를 호출:
- MappingJackson2HttpMessageConverter.canWrite(ResponseDto.class, application/json)
- 반환값: true
- MappingJackson2HttpMessageConverter를 사용해 ResponseDto를 JSON으로 변환:
- { "status": "Success", "message": "Operation completed" }
정리
- **canWrite**는 특정 객체(clazz)를 특정 미디어 타입(mediaType)으로 변환 가능한지 확인합니다.
- Spring은 이 메서드를 사용해 적합한 HttpMessageConverter를 결정합니다.
- REST API 응답에서 주로 활용되며, JSON, XML, TEXT 등의 데이터 형식을 처리할 수 있는지 판단하는 핵심 메서드입니다.
void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)는 Spring의 HttpMessageConverter 인터페이스에서 정의된 메서드로, 데이터를 HTTP 응답 메시지에 쓰는 역할을 합니다. 이 메서드는 REST API에서 서버가 클라이언트로 데이터를 반환할 때 사용됩니다.
메서드 정의
void write(
T t,
@Nullable MediaType contentType,
HttpOutputMessage outputMessage
) throws IOException, HttpMessageNotWritableException;
파라미터 설명
- T t:
- HTTP 응답 본문에 쓰려는 데이터 객체입니다.
- 예를 들어, 컨트롤러에서 반환하는 DTO 객체가 여기에 전달됩니다.
- 데이터의 타입은 HttpMessageConverter의 제네릭 타입 T로 제한됩니다.
- @Nullable MediaType contentType:
- 응답의 Content-Type을 나타냅니다.
- 예: application/json, application/xml, text/plain.
- @Nullable이므로 null일 수 있습니다.
- null인 경우, 기본값이나 자동 결정된 MediaType이 사용됩니다.
- HttpOutputMessage outputMessage:
- HTTP 응답 메시지를 나타내는 객체입니다.
- 실제로 응답 데이터를 쓰는 데 필요한 출력 스트림(OutputStream)과 헤더(HttpHeaders)를 포함합니다.
예외
- IOException:
- 데이터 쓰기 중 IO 문제가 발생할 경우 던집니다.
- 예: 네트워크 연결 문제.
- HttpMessageNotWritableException:
- 데이터 객체를 변환하거나 쓰는 데 실패한 경우 던집니다.
- 예: 객체를 JSON으로 변환하지 못하거나 변환 로직에 오류가 있는 경우.
메서드의 역할
이 메서드는 데이터(t)를 지정된 형식(contentType)으로 변환하고, 이를 HTTP 응답 메시지(outputMessage)의 본문에 쓰는 작업을 수행합니다.
실제 동작 흐름
- 컨트롤러에서 데이터 반환:
- 예: 컨트롤러 메서드가 DTO 객체를 반환.
@GetMapping("/example") public ResponseDto example() { return new ResponseDto("success", "Operation completed"); }
- Spring이 적절한 HttpMessageConverter 선택:
- canWrite 메서드를 사용해 변환 가능한 컨버터를 선택합니다.
- 예: MappingJackson2HttpMessageConverter가 JSON 변환을 담당.
- write 메서드 호출:
- Spring이 선택한 컨버터의 write 메서드를 호출해, 반환 객체(ResponseDto)를 JSON으로 변환하고 HTTP 응답 본문에 씁니다.
구현 예: JSON 변환기
MappingJackson2HttpMessageConverter의 write 메서드가 어떻게 동작할지 간단히 구현 예로 살펴보겠습니다.
@Override
public void write(
Object t,
@Nullable MediaType contentType,
HttpOutputMessage outputMessage
) throws IOException {
// 1. JSON 변환기 초기화 (예: ObjectMapper 사용)
ObjectMapper objectMapper = new ObjectMapper();
// 2. Content-Type 설정
if (contentType != null) {
outputMessage.getHeaders().setContentType(contentType);
} else {
outputMessage.getHeaders().setContentType(MediaType.APPLICATION_JSON);
}
// 3. 객체를 JSON으로 변환하여 OutputStream에 쓰기
OutputStream bodyStream = outputMessage.getBody();
objectMapper.writeValue(bodyStream, t);
// 4. OutputStream 닫기 (Spring이 자동으로 관리)
}
사용 예제
클라이언트 요청
GET /example HTTP/1.1
Accept: application/json
컨트롤러 반환
@GetMapping("/example")
public ResponseDto example() {
return new ResponseDto("success", "Operation completed");
}
write 메서드 동작
- 파라미터 전달:
- t: ResponseDto 객체 ({"status":"success", "message":"Operation completed"}).
- contentType: application/json.
- outputMessage: 클라이언트로 보낼 HTTP 응답 메시지.
- 동작:
- ObjectMapper가 ResponseDto 객체를 JSON 문자열로 변환.
- 변환된 JSON 문자열을 outputMessage.getBody()의 출력 스트림에 씀.
- outputMessage.getHeaders()를 사용해 Content-Type 헤더를 설정.
결과 응답
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 58
{"status":"success","message":"Operation completed"}
주요 특징
- 데이터 변환:
- write 메서드는 Java 객체를 HTTP 응답 형식(JSON, XML 등)으로 변환합니다.
- 변환은 HttpMessageConverter 구현체에 따라 다릅니다.
- 스트림 기반 쓰기:
- 변환된 데이터를 직접 HttpOutputMessage의 출력 스트림에 씁니다.
- 이를 통해 대규모 데이터 처리도 효율적으로 수행할 수 있습니다.
- 유연성:
- 미디어 타입이 null인 경우 기본값을 사용할 수 있습니다.
- 개발자가 원하는 방식으로 데이터 변환을 커스터마이징할 수 있습니다.
정리
- **write**는 데이터를 HTTP 응답 본문에 쓰는 메서드로, REST API에서 클라이언트에 데이터를 반환할 때 사용됩니다.
- Spring의 HttpMessageConverter 구현체마다 이 메서드가 다르게 동작하여 다양한 데이터 형식(JSON, XML, TEXT 등)을 처리합니다.
- 사용자는 커스터마이징된 HttpMessageConverter를 구현해 특정 데이터 포맷을 지원할 수도 있습니다.
응답 데이터 쓰기
HttpMessageConverter 구조
📌 HttpMessageConverter를 주로 사용하는 어노테이션 @RequestBody, @ResponseBody
- 요청시에는 Argument Resolver가 사용하는것이다.
- 응답시에는 ReturnValueHandler가 사용한다.
대표적인 ArgumentResolver, ReturnValueHandler
1. ArgumentResolver
**ArgumentResolver**는 컨트롤러 메서드 파라미터에 요청 데이터를 바인딩하는 역할을 합니다.
대표적인 ArgumentResolver
Resolver 이름 설명
RequestParamMethodArgumentResolver | @RequestParam 어노테이션 처리. 요청의 쿼리 파라미터 또는 폼 데이터를 메서드 파라미터로 바인딩. |
PathVariableMethodArgumentResolver | @PathVariable 어노테이션 처리. URL 경로 변수 값을 메서드 파라미터로 바인딩. |
RequestHeaderMethodArgumentResolver | @RequestHeader 어노테이션 처리. HTTP 요청 헤더 값을 메서드 파라미터로 바인딩. |
CookieValueMethodArgumentResolver | @CookieValue 어노테이션 처리. HTTP 쿠키 값을 메서드 파라미터로 바인딩. |
RequestBodyArgumentResolver | @RequestBody 어노테이션 처리. 요청 본문(JSON/XML)을 Java 객체로 변환. |
ModelAttributeMethodProcessor | @ModelAttribute 어노테이션 처리. 요청 데이터를 객체에 바인딩하고, 모델에 추가. |
SessionAttributeMethodArgumentResolver | @SessionAttribute 어노테이션 처리. 세션에서 특정 속성을 가져와 메서드 파라미터에 주입. |
RequestAttributeMethodArgumentResolver | @RequestAttribute 어노테이션 처리. 요청 속성(request scope)을 메서드 파라미터에 바인딩. |
HttpEntityMethodProcessor | HttpEntity<T> 및 RequestEntity<T> 처리. 요청 전체(헤더와 본문 포함)를 객체로 바인딩. |
PrincipalMethodArgumentResolver | 현재 인증된 사용자의 정보를 나타내는 java.security.Principal 객체 처리. |
DefaultMethodArgumentResolver | HTTP 요청 및 응답 객체(HttpServletRequest, HttpServletResponse) 처리. |
ArgumentResolver의 예제
@RequestParam과 @RequestBody 사용
@GetMapping("/greet")
public String greetUser(@RequestParam String name) {
return "Hello, " + name;
}
@PostMapping("/process")
public String processData(@RequestBody MyDto data) {
return "Processed: " + data.getValue();
}
- RequestParamMethodArgumentResolver: name 값을 쿼리 파라미터에서 추출.
- RequestBodyArgumentResolver: 요청 본문(JSON)을 MyDto 객체로 변환.
2. ReturnValueHandler
**ReturnValueHandler**는 컨트롤러 메서드가 반환한 데이터를 클라이언트에게 적절히 변환하여 응답으로 전달합니다.
대표적인 ReturnValueHandler
Handler 이름 설명
RequestResponseBodyMethodProcessor | @ResponseBody와 HttpEntity를 처리. Java 객체를 JSON/XML 등으로 변환. |
ModelAndViewMethodReturnValueHandler | ModelAndView 객체를 처리하여 뷰를 렌더링. |
ViewMethodReturnValueHandler | View 객체를 처리하여 뷰를 렌더링. |
HttpEntityMethodProcessor | HttpEntity<T> 및 ResponseEntity<T>를 처리. 헤더와 본문을 설정하여 응답. |
ModelMethodProcessor | 모델 객체를 처리하여 View에서 사용할 데이터로 추가. |
DeferredResultMethodReturnValueHandler | 비동기 작업 결과를 처리(DeferredResult, CompletableFuture 등). |
CallableMethodReturnValueHandler | Callable 객체를 처리하여 비동기 응답 생성. |
StringMethodReturnValueHandler | 단순 문자열(String)을 처리하여 응답 본문에 쓰거나, 뷰 이름으로 해석. |
ReturnValueHandler의 예제
@ResponseBody와 ResponseEntity 사용
@RestController
public class ExampleController {
@GetMapping("/json")
public MyDto getJson() {
return new MyDto("data", 123); // RequestResponseBodyMethodProcessor 처리
}
@GetMapping("/response")
public ResponseEntity<String> getResponse() {
return ResponseEntity.ok("OK"); // HttpEntityMethodProcessor 처리
}
}
- RequestResponseBodyMethodProcessor:
- MyDto 객체를 JSON 형식으로 변환하여 응답 본문에 작성.
- HttpEntityMethodProcessor:
- ResponseEntity의 상태 코드, 헤더, 본문을 설정하여 응답.
전체 흐름 정리
Spring MVC의 요청 처리 과정에서 **ArgumentResolver**와 **ReturnValueHandler**는 다음처럼 동작합니다:
- ArgumentResolver:
- 클라이언트 요청 데이터를 컨트롤러 메서드 파라미터에 맞게 변환.
- 예: 쿼리 파라미터 → @RequestParam, 본문(JSON) → @RequestBody.
- ReturnValueHandler:
- 컨트롤러 메서드의 반환값을 클라이언트 응답으로 변환.
- 예: 객체 → JSON, 문자열 → 뷰 이름 해석.
예제 통합
@RestController
public class ExampleController {
@PostMapping("/submit")
public ResponseEntity<String> submit(@RequestBody MyDto dto) {
// ArgumentResolver: RequestBodyArgumentResolver 처리
System.out.println("Received: " + dto.getValue());
return ResponseEntity.ok("Processed successfully"); // ReturnValueHandler: HttpEntityMethodProcessor 처리
}
}
요청:
POST /submit
Content-Type: application/json
{
"value": "example"
}
응답:
HTTP/1.1 200 OK
Content-Type: text/plain
Processed successfully
이렇게 Spring MVC는 ArgumentResolver로 요청 데이터를 바인딩하고, ReturnValueHandler로 응답 데이터를 변환합니다!
요청과 응답
📌 ArgumentResolver와 HttpMessageConverter는 다르다.
WebMvcConfigurer
📌 Spring MVC의 설정을 사용자 정의할 수 있도록 제공되는 인터페이스로 implements하여 설정을 확장하거나 커스터마이징할 수 있다.
- 주요 인터페이스
- HandlerMethodArgumentResolver
- HandlerMethodReturnValueHandler
- HttpMessageConverter
- 모두 인터페이스로 구현되어 있으며 대부분 구현되어 있다.
- Spring에서 기본적으로 제공하고 있다.
- 개발자는 잘 사용하면 된다.
- 기능의 확장
- WebMvcConfigurer를 상속받고 Spring Bean으로 등록
public interface WebMvcConfigurer {
default void configurePathMatch(PathMatchConfigurer configurer) {
}
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
default void addFormatters(FormatterRegistry registry) {
}
default void addInterceptors(InterceptorRegistry registry) {
}
default void addResourceHandlers(ResourceHandlerRegistry registry) {
}
default void addCorsMappings(CorsRegistry registry) {
}
default void addViewControllers(ViewControllerRegistry registry) {
}
default void configureViewResolvers(ViewResolverRegistry registry) {
}
default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
}
default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
}
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}
default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
}
default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}
default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}
@Nullable
default Validator getValidator() {
return null;
}
@Nullable
default MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
- addArgumentResolvers()
- addReturnValueHandlers()
- extendMessageConverters()
- 필요한 메서드를 오버라이딩 하면된다.
- @Configuration
- @Component 를 포함하고 있다. (Spring Bean 등록이 된다.)
HttpMessageConverter 요약
HttpMessageConverter는 Spring MVC에서 클라이언트와 서버 간 데이터를 변환하는 데 사용되는 컴포넌트입니다. HTTP 요청과 응답의 본문을 Java 객체와 JSON, XML, TEXT 등으로 상호 변환합니다.
HttpMessageConverter의 역할
- 요청 처리:
- 클라이언트가 JSON, XML 등 형식으로 요청 본문을 보내면 이를 Java 객체로 변환.
- 응답 생성:
- 컨트롤러가 반환한 Java 객체를 JSON, XML, TEXT 등으로 변환하여 클라이언트로 전송.
일상적인 비유
- 비유: 번역가(Translator)
- 한 사람이 영어로 말을 하고, 다른 사람이 한국어로 이해하려면 번역가가 필요합니다.
- 여기서 영어는 JSON, XML 등의 데이터 형식이고, 한국어는 Java 객체입니다.
- 번역가(HttpMessageConverter)가 데이터를 양쪽에서 서로 이해할 수 있도록 변환합니다.
HttpMessageConverter의 동작 흐름
- 클라이언트 요청:
- 클라이언트가 JSON 요청을 보냅니다.
- 예: {"name": "John", "age": 30}
- 요청 데이터 변환:
- HttpMessageConverter가 JSON 데이터를 Java 객체로 변환.
- 컨트롤러 처리:
- 컨트롤러 메서드에서 비즈니스 로직 처리.
- 응답 데이터 변환:
- 컨트롤러 메서드가 반환한 Java 객체를 JSON 형식으로 변환하여 클라이언트에 응답.
대표적인 HttpMessageConverter 구현체
Converter 이름 역할
MappingJackson2HttpMessageConverter | JSON 데이터를 Java 객체로 변환 또는 반대로 변환. |
MappingJackson2XmlHttpMessageConverter | XML 데이터를 Java 객체로 변환 또는 반대로 변환. |
StringHttpMessageConverter | 문자열 데이터를 처리. |
FormHttpMessageConverter | application/x-www-form-urlencoded 폼 데이터를 처리. |
ByteArrayHttpMessageConverter | 바이너리 데이터를 처리 (예: 파일 다운로드). |
HttpMessageConverter 사용 예제
요청 본문(JSON) → Java 객체 (@RequestBody)
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody UserDto userDto) {
return "User created: " + userDto.getName();
}
}
- 클라이언트 요청:
- POST /api/users Content-Type: application/json { "name": "John", "age": 30 }
- HttpMessageConverter 동작:
- MappingJackson2HttpMessageConverter가 JSON 데이터를 UserDto 객체로 변환.
- 컨트롤러는 변환된 UserDto 객체를 사용.
- 컨트롤러 결과:
- User created: John
Java 객체 → JSON 응답 (@ResponseBody)
@RestController
public class ExampleController {
@GetMapping("/user/{id}")
public UserDto getUser(@PathVariable Long id) {
return new UserDto(id, "John", 30); // Java 객체 반환
}
}
- 클라이언트 요청:
- GET /user/1 Accept: application/json
- HttpMessageConverter 동작:
- 컨트롤러에서 반환한 UserDto 객체를 MappingJackson2HttpMessageConverter가 JSON으로 변환.
- 클라이언트 응답:
- HTTP/1.1 200 OK Content-Type: application/json { "id": 1, "name": "John", "age": 30 }
HttpMessageConverter의 장점
- 자동 변환:
- JSON, XML, TEXT 등 다양한 데이터 형식을 Java 객체로 쉽게 변환 가능.
- 개발자가 수동으로 데이터 변환 코드를 작성할 필요 없음.
- 확장 가능:
- 필요에 따라 커스텀 HttpMessageConverter를 작성해 특별한 데이터 형식을 처리 가능.
- REST API 친화적:
- RESTful 서비스를 개발할 때 요청과 응답 데이터를 간단하게 처리.
커스텀 HttpMessageConverter
Spring MVC에서 특정 데이터 포맷을 처리하기 위해 커스텀 HttpMessageConverter를 구현할 수 있습니다.
예제: CSV 데이터를 처리하는 HttpMessageConverter
- 커스텀 HttpMessageConverter 구현:
- public class CsvHttpMessageConverter extends AbstractHttpMessageConverter<MyCsvDto> { public CsvHttpMessageConverter() { super(new MediaType("text", "csv")); } @Override protected boolean supports(Class<?> clazz) { return MyCsvDto.class.isAssignableFrom(clazz); } @Override protected MyCsvDto readInternal(Class<? extends MyCsvDto> clazz, HttpInputMessage inputMessage) throws IOException { // CSV 데이터를 Java 객체로 변환하는 로직 return new MyCsvDto("example", 123); } @Override protected void writeInternal(MyCsvDto myCsvDto, HttpOutputMessage outputMessage) throws IOException { // Java 객체를 CSV 데이터로 변환하는 로직 String csv = myCsvDto.getName() + "," + myCsvDto.getValue(); outputMessage.getBody().write(csv.getBytes()); } }
- Spring에 등록:
- @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new CsvHttpMessageConverter()); } }
결론
HttpMessageConverter는 클라이언트와 서버 간 데이터 변환을 자동화하여 개발자의 작업을 간소화합니다. 데이터를 JSON, XML 등 다양한 포맷으로 처리할 수 있으며, 필요에 따라 커스터마이징하여 확장할 수도 있습니다.
비유: 데이터를 주고받는 번역가로, 클라이언트와 서버가 서로 다른 언어(JSON, XML, Java 객체 등)를 이해할 수 있게 해주는 역할을 합니다.
'Back-End (Web) > Spring' 카테고리의 다른 글
Formatter (0) | 2025.01.11 |
---|---|
TypeConverter (0) | 2025.01.10 |
ArgumentResolver (0) | 2025.01.08 |
[Spring] 스프링 정리 (0) | 2025.01.07 |
[Spring] 의존관계 주입 (0) | 2024.12.26 |