DEV Community

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

Posted on

3 3

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay