SpringBoot

Path Variable과 Request Param

공부처음하는사람 2024. 8. 6. 22:51

 

Client에서 서버로 HTTP 요청을 보낼 때 데이터를 함께 보낼 수 있다.

서버에서는 이 데이터를 받아서 사용해야하는데 데이터를 보내는 방식은 여러가지가 있기에 여러 방식에 대한 학습이 필요함

 

Path Variable

http://localhost:8080/hello/request/star/Robbie/age/95

    // [Request sample]
// GET http://localhost:8080/hello/request/star/Robbie/age/95
    @GetMapping("/star/{name}/age/{age}")
    @ResponseBody
    public String helloRequestPath(@PathVariable String name, @PathVariable int age)
    {
        return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
    }

 

Robbie, 95 데이터를 서버에 보내기 위해 url 경로에 추가

데이터를 받기 위해선 URL 경로에 {data}처럼 중괄호를 사용한다.

그리고 해당 요청 메서드 파라미터에 @PathVariable 어노테이션과 함께 {name} 중괄호에 선언한 변수명과 변수타입을 선언하면 

해당 경로의 데이터를 받아올 수 있다.

 

 

Request Param

http://localhost:8080/hello/request/form/param?name=Robbie&age=95

 

서버에 보내려는 데이터를 URL 경로 마지막에 ? 와 &를 사용해 추가할 수 있다.

    // [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
    @GetMapping("/form/param")
    @ResponseBody
    public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }

 

데이터를 받기 위해서는 key 부분에 선언한 name과 age를 사용하여 value에 선언된 Robbie, 95 데이터를 받아올 수 있다.

(@RequestPAram String name, int age)