@RequestParam & @PathVariable 어노테이션

seheeee_97·2024년 2월 4일
0

개인 공부

목록 보기
35/44

@RequestParam :

HTTP 요청의 쿼리 매개변수를 추출

주로 URL의 끝에 ?를 사용하여 전달되는 매개변수 값을 읽음
http://example.com/api/user?id=123에서 @RequestParam을 통해 id 추출

@GetMapping("/api/user")
public ResponseEntity<String> getUserById(@RequestParam("id") String userId) {
    // 코드
}

@PathVariable:

URI 템플릿에서 경로 변수를 추출

주로 URL의 경로 부분에 들어있는 값을 읽음
http://example.com/api/user/123에서 @PathVariable을 통해 123이 추출

@GetMapping("/api/user/{id}")
public ResponseEntity<String> getUserById(@PathVariable String id) {
    // 코드
}

정리

@RequestParam은 쿼리 매개변수를 추출
@PathVariable은 URL 경로에서 변수를 추출

0개의 댓글