How to Get Query Parameter in Spring Boot: Simple Guide
In Spring Boot, you get query parameters by using the
@RequestParam annotation in your controller method parameters. This tells Spring to extract the value from the URL query string and pass it to your method.Syntax
The @RequestParam annotation is placed before a method parameter in a Spring controller. It binds the query parameter from the URL to that parameter.
@RequestParam("paramName"): specifies the query parameter name.- Method parameter type: the type you want to convert the query parameter to (e.g.,
String,int). - Optional
requiredattribute: if set tofalse, the parameter is optional. - Optional
defaultValue: provides a default if the query parameter is missing.
java
public String exampleMethod(@RequestParam("name") String name) { // use the 'name' query parameter }
Example
This example shows a Spring Boot controller that reads a query parameter called name from the URL and returns a greeting message. If the parameter is missing, it uses a default value.
java
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @GetMapping("/greet") public String greet(@RequestParam(name = "name", required = false, defaultValue = "Guest") String name) { return "Hello, " + name + "!"; } }
Output
When you visit /greet?name=Alice, the output is: Hello, Alice!
When you visit /greet without a name parameter, the output is: Hello, Guest!
Common Pitfalls
Common mistakes when getting query parameters include:
- Not specifying
required = falsefor optional parameters, causing errors if the parameter is missing. - Using the wrong parameter name in
@RequestParam, so Spring can't find the query parameter. - Not providing a
defaultValuewhen the parameter is optional, which can lead to null values.
java
/* Wrong: Missing required=false for optional parameter */ @GetMapping("/test") public String test(@RequestParam("id") String id) { return "ID: " + id; } /* Right: Mark parameter optional with default value */ @GetMapping("/test") public String test(@RequestParam(name = "id", required = false, defaultValue = "0") String id) { return "ID: " + id; }
Quick Reference
Summary tips for using @RequestParam:
- Use
@RequestParam("paramName")to bind query parameters. - Set
required = falsefor optional parameters. - Use
defaultValueto avoid nulls. - Match the query parameter name exactly.
Key Takeaways
Use @RequestParam to get query parameters in Spring Boot controller methods.
Set required=false and defaultValue for optional query parameters to avoid errors.
Always match the query parameter name in @RequestParam with the URL parameter.
Missing required parameters without defaults cause errors at runtime.
You can convert query parameters to common types like String, int, boolean automatically.