SoFunction
Updated on 2025-04-13

Detailed explanation of the main usage of @RequestParam

1. Basic usage

  • effect: Extract query parameters or form data from the request.
  • grammar
@RequestParam("Parameter name") Data Type Parameter name
  • Example
@GetMapping("/greet")
public String greet(@RequestParam("name") String name) {
    return "Hello, " + name + "!";
}
  • ask:/greet?name=John
  • response:Hello, John!

2. Default value

  • effect: When the parameter does not exist, use the default value.
  • grammar
@RequestParam(value = "Parameter name", defaultValue = "default value") Data Type Parameter name
  • Example
@GetMapping("/greet")
public String greet(@RequestParam(value = "name", defaultValue = "Guest") String name) {
    return "Hello, " + name + "!";
}
  • ask:/greet
  • response:Hello, Guest!

3. Optional parameters

  • effect: The allowed parameters do not exist.
  • grammar
@RequestParam(value = "Parameter name", required = false) Data Type Parameter name
  • Example
@GetMapping("/greet")
public String greet(@RequestParam(value = "name", required = false) String name) {
    return "Hello, " + (name != null ? name : "Guest") + "!";
}
  • ask:/greet
  • response:Hello, Guest!

4. Bind to an object

  • effect: Bind multiple parameters into one object.
  • Example
public class User {
    private int id;
    private String name;
    // Getter and Setter methods}
@GetMapping("/user")
public String getUser(User user) {
    return "User ID: " + () + ", Name: " + ();
}
  • ask:/user?id=1&name=John
  • response:User ID: 1, Name: John

5. Bind to a collection or array

  • effect: Bind multiple parameters of the same name into a collection or array.
  • Example
@GetMapping("/hobbies")
public String getHobbies(@RequestParam("hobby") List<String> hobbies) {
    return "Hobbies: " + (", ", hobbies);
}
  • ask:/hobbies?hobby=Reading&hobby=Traveling
  • response:Hobbies: Reading, Traveling

6. Bind to Map

  • effect: Bind dynamic parameters toMapmiddle.
  • Example
@GetMapping("/params")
public String getParams(@RequestParam Map<String, String> params) {
    return "Params: " + ();
}
  • ask:/params?name=John&age=25
  • response:Params: {name=John, age=25}

7. Handle complex types

  • effect: Supports conversion of complex types such as dates and enumerations.
  • Example
@GetMapping("/date")
public String getDate(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
    return "Date: " + ();
}
  • ask:/date?date=2023-10-01
  • response:Date: 2023-10-01

Summary

The above is personal experience. I hope you can give you a reference and I hope you can support me more.