@PathVariable , @RequestParam

jaeyong Lee·2024년 9월 2일

Spring

목록 보기
2/2
post-thumbnail

예시 코드

Url과 각 controller에서 메서드 어떻게 받는 지 확인

 // [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);
    }



    //쿼리스트링 방식
    // [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);
    }

각각의 특징

●PathVariable은 URL에 리소스를 식별할 수 있도록 경로에 식별자를 포함시키고 싶을 때 사용하니까 RESTful 설계에 적합하다.
●RequestParam은 선택적인 파라미터를 사용하고 싶을 때 활용하며, 필터링이나 검색 조건을 쿼리스트링으로 전달하는 데 적합하다. (필터링과 검색조건은 쿼리스트링으로 적용)

생각

막연히 알고 있던 두 가지 방법을 다시 정리하면서, 각 애너테이션이 어떤 경우에 사용되는지 명확히 이해할 수 있어 좋았고 실제 웹 프로젝트에서 페이징 처리와 조건 전달 api를 구현했었는데 이러한 개념이 적용되었음을 다시 한 번 인식할 수 있었다.

0개의 댓글