Spring - @RequestParam

yigi

Yiğit Erkal

Posted on April 17, 2022

Spring - @RequestParam

Simple terms, we can extract query parameters, form parameters, and even files from a request using @RequestParam.

Let's say that we have an endpoint /api/product that takes a query parameter called id:

@GetMapping("/api/product")
@ResponseBody
public String getProduct(@RequestParam String id) {
    return "ID: " + id;
}
Enter fullscreen mode Exit fullscreen mode

and a simple GET request would invoke getProduct:

http://localhost:8080/api/product?id=123
----
ID: 123
Enter fullscreen mode Exit fullscreen mode

Both the variable name and the argument name are the same in the previous example. However, there are times when we wish they were different.

In this case we use name attribute

@PostMapping("/api/product")
@ResponseBody
public String addProduct(@RequestParam(name = "id") String pId,
 @RequestParam String name) { 
    return "ID: " + pId + " Name: " + name;
}
Enter fullscreen mode Exit fullscreen mode

We can also do @RequestParam(value = “id”) or just @RequestParam(“id”).

Moreover, we can configure our @RequestParam to be optional, though, with the required attribute:

@GetMapping("/api/product")
@ResponseBody
public String getProduct(@RequestParam(required = false) String id) { 
    return "ID: " + id;
}
Enter fullscreen mode Exit fullscreen mode

Finally, we can also have multiple parameters without defining their names or count by just using a Map:

@PostMapping("/api/product")
@ResponseBody
public String updateProduct(@RequestParam Map<String,String> allParams) {
    return "Parameters are " + allParams.entrySet();
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
yigi
Yiğit Erkal

Posted on April 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Spring - @RequestParam
spring Spring - @RequestParam

April 17, 2022