BackEnd/SpringBoot
[spring] - @RequestParam과 @PathVariable의 차이
영지는 달리는중
2020. 7. 28. 02:54
스프링 프로젝트를 진행하며 문든 둘의 차이가 무엇인지 궁금해서 찾아보았다
별거 아닌 내용이지만 나는 몰랐으니까 ㅎㅂㅎ 정리해야겠다!!
1. @RequestParam - 파라메터의 값과 이름을 함께 전달하는 방식으로 게시판 등에서 페이지 및 검색 정보를 함께 전달하는 방식을 사용할 때 많이 사용한다.
controller layer에서의 사용법
@GetMapping("/comments")
@ResponseStatus(HttpStatus.OK)
public GetCommentsResponse getComments(
@RequestHeader String accessToken,
@RequestParam(required = false, defaultValue = "0", "page") int currentPage,
@RequestParam(required = false, defaultValue = "10", "size") int size) {
.
.
.
}
위의 경우 /comments?page=1와 같이 url이 전달될 때 page 파라메터를 받아오게 된다.
이렇게 @RequestParam의 경우 url 뒤에 붙는 파라메터의 값을 가져올 때 사용한다.
2. @PathVariable - Rest api에서 값을 호출할 때 주로 많이 사용한다.
controller layer에서의 사용법
@PostMapping("/{postId}")
@ResponseStatus(HttpStatus.CREATED)
public WriteCommentResponse writeComment(@PathVariable Long postId,
url에서 각 구분자에 들어오는 값을 처리해야 할 때 사용한다.