Request Parameters
A request parameter is a named value in the address after a question mark. It lets one route answer many similar requests.
Read one parameter
Ask for /greet?name=Ana. The method reads name and builds the greeting.
@GetMapping("/greet")
public String greet(@RequestParam(defaultValue = "World") String name) {
return "Hello, " + name + "!";
}A parameter with no default
This method has no default value. A request without name gets an error answer.
@GetMapping("/hello")
public String hello(@RequestParam String name) {
return "Hello, " + name + "!";
}Read a number
Ask for /double?n=4. Spring Boot turns the text 4 into the number 4, and the method doubles it.
@GetMapping("/double")
public int twice(@RequestParam int n) {
return n * 2;
}Example
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetController {
@GetMapping("/greet")
public String greet(@RequestParam(defaultValue = "World") String name) {
return "Hello, " + name + "!";
}
}Key points
- A query string is the part of an address after a question mark.
- ?name=Ana carries the value Ana for the name name.
- @RequestParam reads one value from the query string.
- The value arrives as a method argument with the same name.
- A missing parameter gives an error answer by default.
- defaultValue gives a value when the parameter is missing.
In this example, the controller has one route. The route answers GET requests for /greet. The method takes name from the query string. The default is World when no name arrives. The method joins the name into a greeting. The first request carries ?name=Ana and gets Hello, Ana! back. The second request carries no query string and gets Hello, World! back.
Note
Values in a query string are always text.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @RequestParam(defaultValue = "World") String name do?