Difference Between @RequestParam vs @PathVariable



In this quick article, we will discuss one important interview question that is the main difference between @RequestParam vs @PathVariable annotations in Spring.

Difference Between @RequestParam vs @PathVariable

@PathVariable annotation

With the @PathVariable annotation, we bind the request URL template path variable to the method variable. 
For instance, with the http://localhost:8080/springmvc/hello-world/100/Ramesh/ URL, the 100 value is bound to the id variable and the "Ramesh" value to the name variable.
    @GetMapping(path = "/hello-world/{id}/{name}")
    public HelloWorldBean helloWorldPathVariable(@PathVariable long id, 
        @PathVariable(name = "name") String name) {
        return new HelloWorldBean(id, name);
    }

@RequestParam annotation

With @RequestParam annotation, we can extract values from the query string.

    @GetMapping(path = "/hello-world")
    public HelloWorldBean helloWorldPathVariable(@RequestParam long id, 
        @RequestParam String name) {
        return new HelloWorldBean(id, name);
    }
So the main difference between @RequestParam and @PathVariable annotations is that @RequestParam we use to extract values from the query string, while @PathVariable we use to extract values from the URI path.

References

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments