@RequestParam in Spring Boot: What It Is and How to Use It
@RequestParam in Spring Boot is an annotation used to extract query parameters from HTTP requests and bind them to method parameters in controller methods. It helps you easily access data sent by clients in the URL query string.How It Works
Imagine you are ordering a pizza by phone and you tell the person your choices like size and toppings. In Spring Boot, when a client sends a request to your app with extra information in the URL (called query parameters), @RequestParam listens for those details and passes them to your code.
For example, if the client visits /order?size=large&topping=cheese, @RequestParam grabs the values "large" and "cheese" and gives them to your method so you can use them to prepare the order. It works like a translator between the URL and your program.
Example
This example shows a simple Spring Boot controller method using @RequestParam to get a user's name from the URL and return a greeting message.
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 greetUser(@RequestParam String name) { return "Hello, " + name + "!"; } }
When to Use
Use @RequestParam when you want to get simple data sent by the client in the URL query string, like filters, search terms, or options. It is perfect for small pieces of information that control what your app should do.
For example, you might use it to get a page number for pagination, a search keyword, or a flag to turn on/off a feature. It keeps your URLs clean and your code easy to read.
Key Points
@RequestParambinds URL query parameters to method arguments.- It can handle required and optional parameters with default values.
- It works only with query parameters, not with request bodies.
- It helps keep controller methods simple and clear.
Key Takeaways
@RequestParam extracts query parameters from HTTP requests into method parameters.