0
0
SpringbootConceptBeginner · 3 min read

@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.

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 greetUser(@RequestParam String name) {
        return "Hello, " + name + "!";
    }
}
Output
If you visit /greet?name=Anna in your browser, the output will be: Hello, Anna!
🎯

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

  • @RequestParam binds 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.
It is ideal for simple data like filters, search terms, or options sent in the URL.
You can mark parameters as required or provide default values for optional ones.
It keeps your controller code clean and easy to understand.