네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

 이전 글 

https://frogand.tistory.com/114

 

[Spring] @RequestBody, @RequestParam, @ModelAttribute의 차이

Client에서 받은 요청을 객체로 바인딩하기 위해 사용하는 방법에는 총 @RequestBody, @RequestParam, @ModelAttribute 총 3가지가 있다. 🥑 @RequestParam @RequestParam은 1개의 HTTP 요청 파라미터를 받기 위해..

frogand.tistory.com

https://frogand.tistory.com/162

1. @RequestBody와 @ModelAttribute

// Controller.java
@PostMapping
public ResponseEntity<String> createPost(@ModelAttribute PostDto postDto) {
}

@PostMapping
public ResponseEntity<String> createComment(@RequestBody CommentDto commentDto) {
}

@RequestBody와 @ModelAttribute는 클라이언트 측에서 보낸 데이터를 Java 코드에서 사용할 수 있는 오브젝트로 만들어주는 공통점이 있다. 하지만 두 어노테이션은 세부 수행 동작에서 큰 차이가 있다. 

 

2. @RequestBody

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.

POST HTTP1.1 /requestbody
Body:
{ “password”: “1234”, “email”: “kevin@naver.com” }

@RequestBody 어노테이션의 역할은 클라이언트가 보내는 HTTP 요청 본문(JSON, XML 등)을 Java 객체로 변환하는 것이다. HTTP 요청 본문 데이터는 Spring에서 제공하는 HttpMessageConverter를 통해 타입에 맞는 객체로 변환된다.

 

// Controller.java

@PostMapping("/requestbody")
public ResponseEntity<RequestBodyDto> testRequestBody(@RequestBody RequestBodyDto dto) {
    return ReponseEntity.ok(dto);
}
// RequestBodyDto.java

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class RequestBodyDto {

    private String name;
    private long age;
    private String password;
    private String email;
}
// ControllerTest.java

@Test
void requestsBody() throws Exception {
    
    ObjectMapper objectMapper = new ObjectMapper();
    RequestBodyDto dto = new RequestBodyDto("req", 1L, "pass", "email");
    String requestBody = objectMapper.writeValueAsString(dto);
    
    mockMvc.perform(post("/requestbody")
           .contentType(MediaType.APPLICATION_JSON_VALUE)
           .content(requestBody))
           .andExpect(status().isOk())
           .andExpect(jsonPath("name").value("req"))
           .andExpect(jsonPath("age").value("1"))
           .andExpect(jsonPath("password").value("pass"))
           .andExpect(jsonPath("email").value("email"));
}

RequestBodyDto 객체를 JSON 문자열로 변환한 뒤, 이를 Post 요청 본문에 담아 보내고 다시 응답 본문으로 받는 테스트이다. 해당 테스트를 실행하면 요청 본문의 JSON 값이 DTO로 잘 변환되어 성공한다.

 

1) 생성자와 setter가 없다면?

// RequestBodyDto.java

@NoArgsConstructor // 기본 생성자
// @AllArgsConstructor
@Getter
// @Setter
public class RequestBodyDto {

    private String name;
    private long age;
    private String password;
    private String email;
}
// ControllerTest.java

@Test
void requestBody() throws Exception {
    String requestBody = "{\"name\":\"req\",\"age\":1,\"password\":\"pass\",\"email\":\"email\"}\n";

    mockMvc.perform(post("/requestbody")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content(requestBody))
            .andExpect(status().isOk())
            .andExpect(jsonPath("name").value("req"))
            .andExpect(jsonPath("age").value("1"))
            .andExpect(jsonPath("password").value("pass"))
            .andExpect(jsonPath("email").value("email"));
}

RequestBodyDto의 필드를 바인딩해줄 수 있는 생성자 및 setter 메서드를 삭제하고 테스트를 실행해도 테스트는 성공한다.

어떻게 기본 생성자만을 가지고 JSON 값을 Java 객체로 재구성할 수 있을까?

2) MappingJackson2HttpMessageConverter

org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver 클래스의 readWithMessageConverters()라는 메서드에 브레이크 포인트를 찍고 다시 Post 요청을 보내면, Spring에 등록된 여러 MessageConverter 중 MappingJackson2HttpMessageConverter를 사용한다.

 

내부적으로 ObjectMapper를 통해 JSON 값을 Java 객체로 역직렬화하는 것을 알 수 있다. 역직렬화란 생성자를 거치지 않고 리플렉션을 통해 객체를 구성하는 매커니즘이다. 직렬화 가능한 클래스들은 기본 생성자가 항상 필수이다. 따라서 @RequestBody에 사용하려는 RequestBodyDto가 기본 생성자를 정의하지 않으면 데이터 바인딩에 실패한다.

 

어떻게 ObjectMapper는 JSON에 명시된 필드명 Key를 Java 객체의 필드명에 매핑시켜 값을 대입할까?

How Jackson ObjectMapper Matches JSON Fields to Java Fields
To read Java objects from JSON with Jackson properly, it is important to know how Jackson maps the fields of a JSON object to the fields of a Java object, so I will explain how Jackson does that.
By default Jackson maps the fields of a JSON object to fields in a Java object by matching the names of the JSON field to the getter and setter methods in the Java object. Jackson removes the "get" and "set" part of the names of the getter and setter methods, and converts the first character of the remaining name to lowercase.
For instance, the JSON field named brand matches the Java getter and setter methods called getBrand() and setBrand(). The JSON field named engineNumber would match the getter and setter named getEngineNumber() and setEngineNumber().
If you need to match JSON object fields to Java object fields in a different way, you need to either use a custom serializer and deserializer, or use some of the many Jackson Annotations.

Jackson ObjectMapper는 JSON 오브젝트의 필드를 Java 오브젝트의 필드에 매핑할 때 getter 혹은 setter 메서드를 사용한다. getter나 setter 메서드명의 접두사(get, set)를 지우고, 나머지 문자의 첫 문자를 소문자로 변환한 문자열을 참조하여 필드명을 찾아낸다.

 

RequestBodyDto에 getter 및 setter 메서드가 모두 정의되어 있지 않으면, 테스트 실행시 HttpMessageNotWritableException 예외가 발생해 실패한다.

 

3) conclusion

- @RequestBody를 사용하면 요청 본문의 JSON, XML, TEXT 등의 데이터가 적합한 HttpMessageConverter를 통해 파싱되어 Java 객체로 변환된다.

- @RequestBody를 사용할 객체는 필드를 바인딩할 생성자나 setter 메서드가 필요없다.

다만, 직렬화를 위해 기본 생성자는 필수다.

또한, 데이터 바인딩을 위한 필드명을 알아내기 위해 getter나 setter 중 한가지는 정의되어 있어야 한다.

 

3. @ModelAttribute

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.

POST HTTP1.1 /modelattribute
Request params: id=13 name=kevin

@ModelAttribute 어노테이션의 역할은 클라이언트가 보내는 HTTP 파라미터들을 특정 Java 객체에 바인딩(매핑)하는 것이다. /modelattribute?name=req&age=1 같은 query string 형태 혹은 요청 본문에 삽입되어있는 Form 형태의 데이터를 처리한다.

// Controller.java

@Getmapping("/modelattribute")
public ResponseEntity<ModelAttributeDto> testModelAttribute(@ModelAttribute ModelAttributeDto dto) {
    return ReponseEntity.ok(dto);
}
// ModelAttributeDto.java

@AllArgsConstructor
@Getter
public class ModelAttributeDto {

    private String name;
    private long age;
    private String password;
    private String email;
}
// ControllerTest.java

@Test
void modelAttribute() throws Exception {
    mockMvc.perform(get("/modelattribute")
            .param("name", "req")
            .param("age", "1")
            .param("password", "pass")
            .param("email", "naver"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("name").value("req"))
            .andExpect(jsonPath("age").value("1"))
            .andExpect(jsonPath("password").value("pass"))
            .andExpect(jsonPath("email").value("naver"));
}

먼저, Http 파라미터와 함께 Get 요청을 테스트하자. Http 파라미터들은 URL 뒤에 붙어 /modelattribute?name=req&age=1&password=pass&email=naver 형태의 query string이 된다. 테스트 실행 결과는 ModelAttributeDto{name='req', age='1', password='pass', email='naver'}로 데이터가 잘 바인딩된다.

 

// Controller.java

@PostMapping("/modelattribute") 
public ResponseEntity<ModelAttributeDto> testModelAttribute(@ModelAttribute ModelAttributeDto dto) {
    return ResponseEntity.ok(dto);
}
// ControllerTest.java

@Test
void modelAttribute() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    ModelAttributeDto modelAttributeDto = new ModelAttributeDto("req", 1L, "pass", "email");
    String requestBody = objectMapper.writeValueAsString(modelAttributeDto);

    mockMvc.perform(post("/modelattribute")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content(requestBody))
            .andExpect(status().isOk())
            .andExpect(jsonPath("name").value("req"))
            .andExpect(jsonPath("age").value("1"))
            .andExpect(jsonPath("password").value("pass"))
            .andExpect(jsonPath("email").value("email"));
}

Post 요청 테스트를 해보자. 이 테스트를 실행하면 실패한다. @ModelAttribute는 Form 형식의 HTTP 요청 본문 데이터만을 인식해 매핑하지만, JSON 형태의 데이터를 전송하고 있다. 데이터가 바인딩되지 않거나 415 Unsupported Media Type 에러가 발생한다.

 

// ControllerTest.java

mockMvc.perform(post("/modelattribute")
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .content("name=req&age=1&password=pass&email=naver"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("name").value("req"))
        .andExpect(jsonPath("pass").value("pass"))
        //...

이와 같이 contentType을 x-www-form-url-encoded로 요청 본문 내용을 Form 형식으로 보내도록 테스트를 수정하면 테스트 실행 결과로 ModelAttributeDto{name='req', age=1, password='pass', email='naver'}로 데이터가 잘 바인딩됨을 확인할 수 있다.

1) 생성자가 없을 때는 setter를

@RequestBody 예제처럼 필드에 접근해 데이터를 바인딩할 수 있는 ModelAttributeDto의 생성자를 삭제해보자.

// ModelAttributeDto.java

// @AllArgsConstructor
@Getter
public class ModelAttributeDto {

    private String name;
    private long age;
    private String password;
    private String email;
}

 

ModelAttributeDto{name='null', age=0, password='null', email='null'}가 출력된다. Post 요청으로 HTTP 파라미터는 정상적으로 보냈지만, Controller에서 데이터를 ModelAttributeDto에 바인딩하지 못하고 있다.

그럼 ModelAttributeDto에 setter 메서드를 추가하고 테스트를 실행하면, 테스트는 생성자가 있을 때처럼 성공하게 됩니다.

2) conclusion

- @ModelAttribute를 사용하면 HTTP 파라미터 데이터를 Java 객체에 매핑한다.

따라서, 객체의 필드에 접근해 데이터를 바인딩할 수 있는 생성자나 setter 메서드가 필요하다.

- query string 및 form 형식이 아닌 데이터는 처리할 수 없다.

 

 참고 

https://tecoble.techcourse.co.kr/post/2021-05-11-requestbody-modelattribute/

 

@RequestBody vs @ModelAttribute

1. @RequestBody와 @ModelAttribute Controller.java @RequestBody와 @ModelAttribute는 클라이언트 측에서 보낸 데이터를 Java…

tecoble.techcourse.co.kr

https://jenkov.com/tutorials/java-json/jackson-objectmapper.html#how-jackson-objectmapper-matches-json-fields-to-java-fields

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !