T_era

@PathVariable 정리 본문

Programing/Spring

@PathVariable 정리

블스뜸 2025. 5. 6. 16:18

역할 및 특징

  • HTTP 비연결성을 극복하여 데이터를 전달하는 방식 중 하나로, URL 경로에 포함된 값을 파라미터로 받아오는 역할을 수행한다.
  • 경로 변수는 URL 경로 내에서 중괄호 {} 로 묶어 표현한다. (예: /users/{id})
  • 기본적으로 @PathVariable로 설정된 경로 변수는 필수 값으로 간주되며, 값이 없을 경우 HTTP 상태 코드 404 Not Found 에러가 발생한다.
  • Restful API 설계가 일반화됨에 따라 해당 어노테이션의 사용 빈도가 높아지고 있다.

Restful API 설계 예시

POST + posts/{postId}/comments        : postId 글에 댓글 작성
GET  + posts/{postId}/comments        : postId 글의 모든 댓글 조회
GET  + posts/{postId}/comments/{commentId} : postId 글의 특정 commentId 댓글 조회
PUT  + posts/{postId}/comments/{commentId} : postId 글의 특정 commentId 댓글 수정
DELETE + posts/{postId}/comments/{commentId} : postId 글의 특정 commentId 댓글 삭제

사용 예시

예시 1: 단일 경로 변수

@RequestMapping("/posts")
@RestController
public class PathVariableController {

    // postId로 된 post 단건 조회
    @GetMapping("/{postId}")
    public String pathVariableV1(@PathVariable("postId") Long data) {
        String result = "PathvariableV1 결과입니다 : " + data;
        return result;
    }
}
@RequestMapping("/posts")
@RestController
public class PathVariableController {

    // 변수명과 파라미터명이 같은 경우 속성값 생략 가능
    @GetMapping("/{postId}")
    public String pathVariableV2(@PathVariable Long postId) {
        String result = "PathvariableV2 결과입니다 : " + postId;
        return result;
    }
}
  • 위 두 예시는 동일한 기능을 수행하며, @PathVariable의 속성값을 생략하는 방법을 보여준다.

예시 2: 다중 경로 변수

@RequestMapping("/posts")
@RestController
public class PathVariableController {

    @GetMapping("/{postId}/comments/{commentId}")
    public String pathVariableV3(@PathVariable Long postId, @PathVariable Long commentId) {
        String result = "PathvariableV3 결과입니다 postId : " + postId + " commentsId : " + commentId;
        return result;
    }
}
@RequestMapping("/posts/{postId}")
@RestController
public class PathVariableController {

    @GetMapping("/comments/{commentId}")
    public String pathVariableV4(@PathVariable Long postId, @PathVariable Long commentId) {
        String result = "PathvariableV4 결과입니다 postId : " + postId + " commentsId : " + commentId;
        return result;
    }
}
  • @PathVariable은 메서드 파라미터에 다중으로 선언하여 URL 경로의 여러 변수 값을 각각 바인딩할 수 있다.
  • URL 매핑 경로는 계층 구조를 가질 수 있으며, @PathVariable을 통해 각 계층의 변수 값을 추출할 수 있다.