February 08, 2020

Difference between Spring's @RequestParam vs @PathVariable


What is the difference between Spring's @RequestParam vs @PathVariable Annotations.
Let's first understand the purpose and usage of @RequestParam and @PathVariable.

@RequestParam annotation is used to get the request parameters from URI, also known as query parameters. e.g If we have an incoming request with order id – http://scrutinybykhimaanshu.com/posts?postId=72

Then we can read the get the postId, using @RequestParam like below

@RequestMapping("/posts")
public String getPostDetails(@RequestParam("postId") String postId) {
  return "postDetails";
}

The required=false can be used to make the query parameter optional. e.g

@RequestMapping("/posts")
public String getPostDetails(@RequestParam(value="postId", required=false) String postId) {
  return "postDetails";
}

@PathVariable annotation is used to extract values from URI. e.g let's assume the request URI is http://scrutinybykhimaanshu.com/posts/72

We can get the postId by using @PathVariable like below

@RequestMapping("/posts/{postId}")
public String getPostDetails(@PathVariable String postId) {
  return "postDetails";
}

Difference
  • @RequestParam is used to get the request parameters from URL, also known as query parameters, while @PathVariable extracts values from URI.
  • @RequestParam annotation can specify default values if a query parameter is not present or empty by using a defaultValue attribute (provided the required attribute is false).
  • Because @PathVariable is extracting values from the URI path, it’s not encoded. On the other hand, @RequestParam is.
-K Himaanshu Shuklaa..

No comments:

Post a Comment