HTTP 데이터를 객체로 처리하는 방법은 @ModelAttribute 또는 @RequestBody를 사용하는 것이다.
@ModelAttribute
HTML중 Form 태그를 사용하여 Form태그 내 특정 값들 가지고 전달받기
// [Request sample]
// POST http://localhost:8080/hello/request/form/model
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=Robbie&age=95
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}
Java
복사
•
HTML의 form 태그를 사용하여 POST 방식으로 HTTP 요청 전달
•
이때 데이터는 HTTP Body에 name=Robbie&age=95 형태로 담겨져 옴
•
Java의 객체 형태로 받는 방법은 @ModelAttribute 애너테이션을 사용한 후 Body 데이터를 Star star 받아올 객체를 선언
Query String 방식
•
?name=Robbie&age=95 처럼 데이터가 두 개만 있다면 괜찮지만 여러 개 있다면 @RequestParam 애너테이션으로 하나 씩 받아오기 힘들 수 있습니다.
•
이때 @ModelAttribute 애너테이션을 사용하면 Java의 객체로 데이터를 받아올 수 있습니다.
◦
파라미터에 선언한 Star 객체가 생성되고, 오버로딩된 생성자 혹은 Setter 메서드를 통해 요청된 name & age 의 값이 담겨집니다.
@RequestBody 방식
// [Request sample]
// POST http://localhost:8080/hello/request/form/json
// Header
// Content type: application/json
// Body
// {"name":"Robbie","age":"95"}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}
Java
복사