1. A Simple Mapping
requested api | result |
---|---|
http://localhost:8080/api/foos?id=abc | ID: abc |
@GetMapping("/foos")
@ResponseBody
public String getFoos(@RequestParam String id) {
return "ID: " + id;
}
In this example, we used @RequestParam to extract the id query parameter.
2. Rename query params
@PostMapping("/foos")
@ResponseBody
public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name) {
return "ID: " + fooId + " Name: " + name;]
}
3. Optional Request Parameters
@GetMapping("/f")
@ResponseBody
public String getFoos(@RequestParam(required = false) String id) {
return "ID: " + id;
}
4. defaultValue
@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}