Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags more
Archives
Today
Total
관리 메뉴

luke

[Spring/스프링] @PathVariable 본문

Study/Spring

[Spring/스프링] @PathVariable

luke-king 2023. 12. 28. 19:43

@PathVariable

  • 경로 변수를 표시하기 위해 메서드에 매개변수에 사용된다.
  • 경로 변수는 중괄호 {id}로 둘러싸인 값을 나타낸다.
  • URL 경로에서 변수 값을 추출하여 매개변수에 할당한다.
  • 기본적으로 경로 변수는 반드시 값을 가져야 하며, 값이 없는 경우 404 오류가 발생한다.
  • 주로 상세 조회, 수정, 삭제와 같은 작업에서 리소스 식별자로 사용된다.

ex1)

http://localhost:8080/api/emplayees/userA

(userA라는 값을 url에서 가져오고 싶을때 @PathVariable 이용하면 쉽게 처리 가능.)

@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesByld(@PathVariable("id") String id){
	return "ID: " + id;
}

이 예시에서는 @PathVariable 어노테이션을 사용하여{id} 변수로 표시되는 URI의 템플릿 부분을 추출한다.

/api/employees/{id} 에 대한 간단한 GET 요청은 추출된 id 값으로 getEmployessByld를 호출한다.

 

또 @PathVariable의 이름과 파라미터 이름이 같으면 생략 가능하다.

ex2)

@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesByld(@PathVariable String id){
	return "ID: " + id;
}

 

<http://localhost:8080/api/employees/userA> 
---- 
ID: userA