@PathVariable / @RequestParam

StrayCat·2026년 2월 10일

@PathVariable과 @RequestParam의 차이점과 실무 활용법

URL에서 데이터를 추출하는 방식

  • @PathVariable - URL 경로에서 추출
// URL: /users/123
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userService.findById(id);  // id = 123
}

// URL: /posts/5/comments/10
@GetMapping("/posts/{postId}/comments/{commentId}")
public Comment get(@PathVariable Long postId, @PathVariable Long commentId) {
    // postId = 5, commentId = 10
}
  • @RequestParam - Query String에서 추출
// URL: /search?keyword=spring&page=2
@GetMapping("/search")
public List<Post> search(
    @RequestParam String keyword,
    @RequestParam int page
) {
    // keyword = "spring", page = 2
}

// 기본값 설정
@RequestParam(defaultValue = "1") int page
@RequestParam(required = false) String keyword

언제, 무엇을 사용하는가?

  • @PathVariable : 리소스 식별 (필수값, RESTful)
    - /users/123 , /products/456 ...
  • RequestParam : 필터, 옵션 (선택값)
    - /search?keyword=java&sort=date ...

핵심 차이

  • @PathVariable : URL 구조의 일부로서 존재
  • @RequestParam: URL 뒤 ? 이후의 파라미터로서 존재
profile
알면 좋은 것보단 잊어버리기 싫은 것들을 기록합니다.

0개의 댓글