클라이언트에서 URL에 parameter를 같이 전달하여 HTTP request를 요청하는 경우가 있다.
이경우 스프링에서는 controller단에서 @PathVariable과 @RequestParam을 사용해 처리한다.
@RequestParam
http://localhost:8080/api/post/search?board=1&page=1
위의 URL의 경우 parameter의 key와 value를 쿼리 스트링으로 전달하는 방식으로, 이런 경우 @RequestParam을 사용하여 처리한다.
@GetMapping("/api/post/search")
public Page<Post> getPostsBySearchKeywordInBoard(
@RequestParam("board") Long boardId,
@RequestParam Integer page,
@RequestParam(required = false) String type,
@RequestParam(required = false) String keyword) {
return postService.getPostsBySearchKeywordInBoard(boardId, type, keyword, page);
}
주로 GET 방식 요청에 사용되며, 페이지나 검색 조건 등 비계층적인 정보를 전달받을 때 사용한다.
@PathVariable
http://localhost:8080/api/post/4
위의 URL의 경우 parameter의 value만 전달하는 방식으로, 이런 경우 @PathVariable을 사용하여 처리한다.
@PutMapping("/api/post/{id}")
public Long update(@PathVariable Long id,
@RequestBody PostUpdateRequestDto reqDto) {
return postService.update(id, reqDto);
}
주로 POST 방식 요청에 사용되며, 계층이 있는 정보를 전달받을 때 사용한다. URL에 계층 정보를 담기 때문에 Restful한 API를 설계할 때 사용된다.
예시의 경우 URL이 계층적으로 설계되어있기 때문에, 클라이언트 측에서 게시물 update 요청을 할 때 필요한 post Id값을 전달해야 하는 것을 알 수 있다.
@PostMapping("/api/post/{postId}/comment/{commentId}")
public Long writeComment (@PathVariable Long postId,
@PathVariable Long commentId,
@RequestBody CommentWriteRequestDto reqDto) {
return commentService.writeComment(postId, commentId, reqDto);
}
각각의 @PathVariable마다 다른 변수명을 사용해 값을 두 개 이상 받을 수 있다.
@GetMapping("api/post/{postId}")
public Post getPost(@RequestParam("category") Long postCategoryId,
@PathVariable Long postId) {
return postService.getPost(postCategoryId, postId);
}
또한 @RequestParam과 @PathVariable을 혼용할 수 있다.
결론
@RequestParam과 @PathVariable은 다양하게 조합하여 사용할 수 있다. Restful한 API를 만들기 위해 계층이 있는 정보를 전달할 때는 @PathVariable을 사용하는 것이 좋고, 추가로 필요한 비계층적인 정보들을 전달할 때는 @RequestParam를 사용하는 방식으로 처리하는 것이 좋다.
'BE > Spring' 카테고리의 다른 글
본인 확인은 어떤 layer에서 이루어져야 할까? (0) | 2022.07.22 |
---|---|
yaml 파일을 그룹으로 관리하기 (0) | 2022.07.09 |
Springboot에서 Redis Cache 적용하기 (0) | 2022.06.27 |
스프링 스케줄러(@Scheduled) 사용하는 법 (0) | 2022.06.23 |
스프링 부트 실행 환경 분리 (0) | 2022.02.02 |
댓글