[Spring] @RequestBody vs @RequestParam 차이

민지·2022년 6월 16일
0

Spring

목록 보기
6/19

@RequestParam

form 태그로 데이터 전달

@RequestParam 은 url 상에서 데이터를 찾는다.
form 태그를 이용하여 데이터를 입력하고 제출 버튼을 누르면 입력한 데이터들이 url을 통해서 전달된다.

GET
http://localhost:8080/hello/request/form/param?name=BTS&age=28

@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam String name, @RequestParam int age)
{
	return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}

POST http://localhost:8080/hello/request/form/param
Header
Content type: application/x-www-form-urlencoded
Body
name=BTS&age=28

@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age)
{
	return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}

Json 형식으로 데이터 전달

Json 형식으로 데이터를 전달할때 url은 변함이 없고, body에 데이터를 포함하여 전송하기 때문에 @RequestParam 으로는 받을 수 없다.

@RequestBody

name 과 age 의 속성을 갖는 Star 클래스에 getter 가 구현되어 있다면 Start 객체를 자동으로 생성이 가능하다.

Json 형식으로 데이터 전달

POST http://localhost:8080/hello/request/form/json
Header
Content type: application/json
Body
{"name":"BTS","age":"28"}

@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star)
{
	return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}
profile
개발일지

0개의 댓글