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;
}
and a simple GET request would invoke getProduct:
http://localhost:8080/api/product?id=123
----
ID: 123
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;
}
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;
}
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();
}
Top comments (0)