[스프링] @RequestBody와 @ModelAttribute

jyleever·2022년 6월 8일
0

스프링

목록 보기
1/1

@ModelAttribute와 @RequestBody는 클라이언트에서 보낸 데이터를 Java 코드에서 사용할 수 있는 객체로 만들어주는 애노테이션이지만 내부 수행 동작에서 차이가 존재한다.

@ModelAttribute

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)
  • 클라이언트로부터 받은 HTTP 파라미터 데이터를 특정 Java Object(보통 DTO 객체)에 바인딩(맵핑) 하는 것
  • 객체를 생성하고 요청 파라미터의 값을 프로퍼티 접근법(setXXX)으로 입력
  • 모델에 @ModelAttribute로 지정한 객체를 자동으로 넣어준다.
    • (model.addAttribute(”이름”, 데이터)) 과정이 자동으로 이루어짐
  • 모델에 데이터를 담을 때는 이름이 필요. 이름은 @ModelAttribute에 지정한 name(value) 속성 사용
  • Query String 형태 혹은 요청 본문에 삽입되는 Form 형태의 데이터를 처리
    • URL의 쿼리스트링으로 들어오는 GET방식 HTTP 요청 정보를 @ModelAttribute가 붙은 파라미터 타입 오브젝트에 모두 담아서 전달
    • 페이지 내의 폼 데이터를 받는 경우에도 @ModelAttribute를 사용
  • 파라미터 값으로 DTO객체에 바인딩을 하는 방식이기 때문에 바인딩하려는 DTO객체에 Setter메소드가 반드시 있어야 함

@RequestBody

요청 본문의 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";
}
  • 요청 본문의 body에 JSON, XML, TEXT 데이터로 요청
  • 한 마디로, json 형태를 java 객체로 쓰겠다는 의미
  • 요청 데이터는 Spring에서 제공하는 적합한 HttpMessageConveter를 통해 파싱되어 객체(DTO)에 맞는 타입으로 변환돼 바인딩
  • 객체의 필드를 바인딩할 생성자나 setter 메서드가 필요없음
    • 다만 직렬화를 위해 기본 생성자는 필수
    • 데이터 바인딩을 위한 필드명을 알아내기 위해 getter나 setter 중 1가지는 정의되어 있어야 한다.

💡 HTTP 메시지 바디를 통해 데이터가 넘어오는 경우는 @RequestParam @ModelAttribute 를 사용할 수 없다.

  • 요청 파라미터를 조회하는 기능: @RequestParam , @ModelAttribute
  • HTTP 메시지 바디를 직접 조회하는 기능: @RequestBody

참고
spring docs
김영한 - 스프링 MVC 1편
https://tecoble.techcourse.co.kr/post/2021-05-11-requestbody-modelattribute/
https://dionysus2074.tistory.com/172

0개의 댓글