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);
}
Read more at Spring Boot @PathVariable
@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
Interview Questions
Java
Spring Framework
Spring MVC
Comments
Post a Comment