@ModelAttribute와 @RequestBody는 클라이언트에서 보낸 데이터를 Java 코드에서 사용할 수 있는 객체로 만들어주는 애노테이션이지만 내부 수행 동작에서 차이가 존재한다.
HTTP 파라미터 데이터를 특정 JAVA 객체(DTO)에 바인딩을 하는 방식이기 때문에 바인딩하려는 DTO객체에
Setter메소드가 반드시 필요
Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view. Supported for controller classes with @RequestMapping methods.
@RequestMapping("/modelAttribute")
public String modelAttributeEx(@ModelAttribute HelloData helloData)
Query String 형태
혹은 요청 본문에 삽입되는 Form 형태의 데이터를 처리
요청 본문의 body에
JSON
,XML
,TEXT
데이터로 요청하여HttpMessageConveter
를 통해 파싱되어 객체(DTO)에 맞는 타입으로 변환돼 바인딩
Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.
@ResponseBody
@PostMapping("/requestBody")
public String requestBodyEx(@RequestBody HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
JSON
, XML
, TEXT
데이터로 요청HttpMessageConveter
를 통해 파싱되어 객체(DTO)에 맞는 타입으로 변환돼 바인딩setter 메서드가 필요없음
💡 HTTP 메시지 바디를 통해 데이터가 넘어오는 경우는 @RequestParam @ModelAttribute 를 사용할 수 없다.
참고
spring docs
김영한 - 스프링 MVC 1편
https://tecoble.techcourse.co.kr/post/2021-05-11-requestbody-modelattribute/
https://dionysus2074.tistory.com/172