@PathVariable 어노테이션

seheeee_97·2024년 1월 22일
0

개인 공부

목록 보기
29/44

@PathVariable : URL 경로에서 변수를 추출하여 메서드의 파라미터로 전달할 때 사용
동적인 URI 패턴에서 추출한 값을 메서드의 인자로 받아올 수 있다.

예시

https://example.com/api/users/123

123은 사용자 id일 수 있음


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/api/users/{id}")
    public String getUserById(@PathVariable long id) {
        return "User ID: " + id;
    }
}

@GetMapping("/api/users/{id}")는 /api/users/{id} 경로로 들어오는 GET 요청을 처리하는 메서드
@PathVariable long id는 경로에서 추출한 id 값을 메서드의 인자로 받음

/api/users/123에 대한 요청이 오면, getUserById 메서드가 실행되고 id 파라미터에는 123이 전달됨
따라서 메서드는 "User ID: 123"을 반환

0개의 댓글