본문 바로가기

Java

[Spring] @RequestBody vs @RequestParam

@RequestBody vs @RequestParam

@RequestBody

  • JSON 형식의 데이터로 받는다.
  • 변수명 상관없이 단일 데이터(Map, Object)로 받는다.
@RestController
@RequestMapping(value = "/test")
public class TestController {
	
	@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST) 
	public void testRequestBody(@RequestBody String param) {
	
		System.out.println("param : " + param);
		System.out.println("text : " + param.get("TEXT"));
	
	}

}

 

▶ Postman Test

 

  • [ URL ]
    http://localhost:8080/yeyo/test/testRequestBody.do
  • [ Method ]
    POST
  • [ Header ]
    Content-Type : application/json
  • [ Body ]
    {"TEXT" : "HELLO"}
  • [ Result ]
    param : {TEXT=HELLO}
    text : HELLO

@RequestParam

  • JSON 형식의 데이터로 받을 수 없다.
  • URL 상에서 데이터를 찾는다.
  • 데이터의 보낼 때 변수 명과 받을 때 변수 명이 일치해야 한다.
@RestController
@RequestMapping(value = "/test")
public class TestController {
	
	@RequestMapping(value = "/testRequestParam", method = RequestMethod.POST) 
	public void testRequestParam(@RequestParam String text, @RequestParam Map<String, String> param) {
	
		System.out.println("text : " + text);

		System.out.println("param : " + param);
		System.out.println("number : " + param.get("number"));
	
	}

}

 

▶ Postman Test

 

  • [ URL ]
    http://localhost:8080/yeyo/test/testRequestParam.do?text=HELLO&number=5
  • [ Method ]
    POST
  • [ Header ]
    Content-Type : application/x-www-form-urlencoded
  • [ Result ]
    text : HELLO
    param : {text=HELLO, number=5}
    number : 5

 

▷ 출처

https://ocblog.tistory.com/49

728x90

'Java' 카테고리의 다른 글

Stream(2)  (0) 2024.07.19
Stream(1)  (0) 2024.07.18
[Spring] @Controller VS @RestController  (0) 2024.07.09
재귀 알고리즘  (0) 2024.07.04
Interface  (0) 2024.07.02