DEV Community

Cover image for Spring - @RequestParam
Yiğit Erkal
Yiğit Erkal

Posted on

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

Top comments (0)