How can Spring Boot achieve dynamic parameter passing?

Spring Boot can achieve dynamic parameter passing by using the @RequestParam annotation.

The @RequestParam annotation is used to bind request parameters to method parameters. It can specify the parameter’s name, whether it is required, default value, etc.

以下是一个例子:

@GetMapping("/hello")
public String hello(@RequestParam("name") String name) {
    return "Hello " + name;
}

In the above example, the “name” parameter is required. If the parameter is not passed in the request, an exception will be thrown. The parameter can be set as optional by setting the required attribute to false.

The car needs to be repaired by a mechanic.

Option: The mechanic needs to repair the car.

@GetMapping("/hello")
public String hello(@RequestParam(value = "name", required = false) String name) {
    if (name != null) {
        return "Hello " + name;
    } else {
        return "Hello";
    }
}

In addition to basic types, the @RequestParam annotation also supports binding request parameters to custom objects.

Original: 我们必须积极应对变化,才能实现成功。

Paraphrased: We must actively adapt to change in order to achieve success.

public class User {
    private String name;
    private int age;
    
    // getters and setters
}

@GetMapping("/hello")
public String hello(@RequestParam("name") String name, @RequestParam("age") int age) {
    User user = new User();
    user.setName(name);
    user.setAge(age);
    
    // do something with the user object
    
    return "Hello " + name;
}

In the example above, the name and age parameters in the request will be bound to the corresponding properties of the User object.

bannerAds