본문 바로가기
Spring

@RequestParam ,@RequestBody 차이점 완전정복

by 디찌s 2022. 11. 3.
728x90
반응형

 

회사 동료중 한분이 계속 파라미터가 안넘어 온다고해서 확인해보니 postman에서 json을 보내는데 스프링에서 @RequestParam 으로 받고 있었다.. 이번일 계기로 RequestParam 과 RequestBody에 대한 차이점을 간단히 정리해보고자한다.

 

 

@RequestParam

requestParam에 대한 doc 문서에 설명은 아래와 같다.

 

더보기

Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servlet and Portlet environments.

위 말을 해석해보면 RequestParam '에노테이션은  웹 요청에 매개변수가 바인딩 된다' 라고 한다. 즉 무슨말이냐면, 

 

'http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true'

 

위 url은 localhost:7777 서버에 요청하는 문장인데 여기서 username,passowrd등 매개변수를 함께 전송할때 reqeustParam을 통해 매개변수를 바인딩하여 컨트롤러 쪽에 전달해준다.

 

즉, requestParam은 url에서 매개변수를 찾는다.

 

 

그렇다면 requestBody 는??

@RequestBody

requestBody에 대한 doc 문서에 설명은 아래와 같다.

더보기

The @RequestBody method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body.

해석하자면 위 애노테이션은 '파라미터가 http 요청 body에 매개변수가 바운딩되어야 한다' 라고 한다.

 

 

즉 ! http 요청을 할때 위 첨부사진 body에 바운딩 해야된다.  그래서

 

 

정리하자면

 

@RequestParam 은 쿼리 매개변수, 양식 데이터 및 멀티파트 요청(form) 형식 의 파트에 매핑하며,

이름-값 양식 필드와 함께 사용될 가능성이 높다.

 

그리고

 

@RequestBody 는 웹 요청의 본문에 바인딩되고, 요청 본문은 요청에 따라 메서드 인수를 해결하기 위해

content type 를 통해 전달됩니다 . (예: JSON, XML)

 

 

처음 글에서 말한것처럼, postman으로 application/json 을 보내는데 @requestParam으로 받아 값이 안넘어 갔던거고

@requestBody를 통해 body에 바인딩된 데이터를 받아야 정상처리 된것이다.

 

 

728x90
반응형

댓글