Spring

[Spring Boot] @PathVariable과 @RequestParam - 파라미터 받기

HSRyuuu 2023. 4. 21. 21:23

@PathVariable 경로변수

PathVariable을 사용하면 리소스 경로에 식별자를 넣어서 동적으로 URL에 정보를 담을 수 있다.

URL 경로의 중괄호 { } 안쪽에 변수를 담고, 그 변수를 @PathVariable(" ")로 받아서 사용할 수 있다.


1. 기본

URL의{postId}와 매개변수 long orderId이름을 맞춰준다.

@GetMapping ("/order/{orderId}")
public String getOrder(@PathVariable String orderId){
    log.info("orderId : {}", orderId);
    
    return "orderId:"+ orderId;
}

요청 : http://localhost:8080/order/123

응답 : orderId:123


2. @PathVariable 매칭

PathVariable과 다른 변수명을 사용하려면 @PathVariable("orderId")로 url의 path-variable와 이름을 맞춰주고,

메서드에서 사용할 변수명을 다르게 설정할 수 있다.

@GetMapping ("/order/{orderId}")
public String getOrder(@PathVariable("orderId") String id){
    log.info("orderId : {}", id);
    
    return "orderId:"+ id;
}

요청 : http://localhost:8080/order/123

응답 : orderId:123


3. 다중 사용

여러 개의 PathVariable을 동시에 사용할 수 있다.

@GetMapping("/order/{orderId}/{amount}")
public String getOrder(@PathVariable String orderId, @PathVariable String amount){
    log.info("orderID : {}, amount : {}", orderId, amount);
    
    return "orderId:"+ orderId + "amount:" + amount;
}

요청 : http://localhost:8080/order/123/900

응답 : orderId:123 amount:900

 


@RequestParam 요청 파라미터

웹에서 쿼리 파라미터를 포함한 url 요청이 있을 때,

컨트롤러에서는 @RequestParam 어노테이션으로 파라미터 값을 읽어서 사용할 수 있다.


기본

/order url에 쿼리파라미터들이 붙은 요청이 들어오면, 아래와 같이 해당 파라미터들을 읽어서 사용할 수 있다. 

@GetMapping("/order")
public String getOrderRequestParam1(
        @RequestParam("orderId") String id,
        @RequestParam("orderAmount") String amount) {
        
    log.info("orderID : {}, orderAmount : {}", id, amount);
    
    return "orderId:" + id + " amount:" + amount;
}

요청 : http://localhost:8080/order? orderId=123&orderAmount=900

응답 : orderId:123 amount:900

 

required, defaultValue 옵션

required = false로 지정하면 필수값이 아니게 되고,

defaultValue로 해당 쿼리파라미터가 존재하지 않을 때 디폴트 값을 설정할 수 있다.

@GetMapping("/order")
public String getOrderRequestParam2(
        @RequestParam(value = "orderId", required = true) String id,
        @RequestParam(value = "orderAmount", required = false, defaultValue = "100") String amount) {
    log.info("orderID : {}, orderAmount : {}", id, amount);
    return "orderId:" + id + " amount:" + amount;
}

요청 : http://localhost:8080/order? orderId=123

응답 : orderId:123 amount:100

반응형