0
0
Spring Bootframework~5 mins

@RequestParam for query strings in Spring Boot

Choose your learning style9 modes available
Introduction

@RequestParam helps you get values from the URL query string easily. It lets your program read small pieces of information sent by the user in the web address.

When you want to get user input from the URL like ?name=John
When you need to filter or search data based on query parameters
When you want to handle optional values sent in the URL
When building simple APIs that accept parameters via URL
When you want to read multiple parameters from the query string
Syntax
Spring Boot
@RequestParam(type) parameterName

You usually put @RequestParam before a method parameter in a controller.

You can set a default value or make the parameter optional.

Examples
Gets a required query parameter named 'name' as a String.
Spring Boot
@RequestParam String name
Gets an optional query parameter 'age' as an Integer. If missing, it will be null.
Spring Boot
@RequestParam(required = false) Integer age
Gets 'user' parameter, but if missing, uses "guest" as default.
Spring Boot
@RequestParam(defaultValue = "guest") String user
Sample Program

This controller has a GET endpoint /greet that reads 'name' and optional 'lang' from the query string. It returns a greeting in English or Spanish based on 'lang'.

Spring Boot
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, @RequestParam(required = false, defaultValue = "en") String lang) {
        if (lang.equals("es")) {
            return "Hola, " + name + "!";
        } else {
            return "Hello, " + name + "!";
        }
    }
}
OutputSuccess
Important Notes

If you forget to send a required parameter, Spring will return an error automatically.

You can use @RequestParam with many types like int, boolean, or even lists.

Always validate or sanitize query parameters to keep your app safe.

Summary

@RequestParam reads values from the URL query string.

You can make parameters required, optional, or give default values.

It helps your app respond differently based on user input in the URL.