@PathVariable, @RequestParam 란? (12.07)

차우빈·2023년 12월 7일
post-thumbnail

오늘은 @PathVariable, @RequestParam 에 대해 정리해보려고 한다.

@PathVariable

  • 개념: @PathVariable은 URL 경로에 포함된 변수를 컨트롤러 메서드의 매개변수로 바인딩하는 데 사용됩니다.
  • 특징: URL 경로의 일부를 변수로 사용하여, 동적으로 변하는 URL 경로를 처리할 수 있습니다.
  • 간결하고 직관적인 API 경로를 설계할 수 있습니다.

Spring Controller 예제:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{userId}")
    public String getUser(@PathVariable("userId") Long userId) {
        // userId를 사용한 로직 처리
        return "User ID: " + userId;
    }
}


cURL 요청http://localhost:8080/users/123 URL로 GET 요청을 보내며, 여기서 123은 userId로 컨트롤러에서 처리됩니다.
curl -X GET "http://localhost:8080/users/123"

@RequestParam

  • 개념: @RequestParam은 클라이언트가 전송하는 HTTP 요청 파라미터를 컨트롤러 메서드의 매개변수로 바인딩하는 데 사용됩니다.
  • 특징: URL에서 지정된 이름의 파라미터를 메서드 매개변수로 전달합니다.
  • 필수 여부, 기본값 설정 등의 추가적인 설정이 가능합니다.

Spring Controller 예제:

@GetMapping("/product/{productId}/detail")
public String getProduct(@RequestParam("id") Long detailId, @PathVariable Long productId) {
    // productId를 사용한 로직 처리
}


cURL 요청:이 cURL 요청은 id 파라미터로 123을 전달합니다.
bashCopy code
curl -X GET "http://localhost:8080/product/1/detail?id=123"

@GetMapping("/product")
public String getProduct(@RequestParam("id") Long productId) {
    // productId를 사용한 로직 처리
  • 배운점 :
    1. @PathVariable은 간결하고 직관적이다.
    2.@RequestParam URL에서 지정된 이름의 파라미터를 메서드 매개변수로 전달 한다.
profile
코린이입니다.

0개의 댓글