Processing front-end POST request parameters in Spring Boot

The @RequestParam annotation or @RequestBody annotation can be used to process the front-end POST request parameters in Spring Boot.

1. @RequestParam annotation

The @RequestParam annotation is used to obtain the value of the request parameter and can be used to process GET and POST requests. It can specify attributes such as the name of the parameter, whether it is required, and the default value.

For example, suppose the front end sends a POST request with the request parameters name and age, you can use the @RequestParam annotation to get the values ​​of these parameters:

@PostMapping("/user")
public String addUser(@RequestParam("name") String name, @RequestParam("age") int age) {
    
    
    // 处理请求参数
    return "success";
}

2. @RequestBody annotation

The @RequestBody annotation is used to obtain the data in the request body, usually used to process POST requests. It converts the data in the request body into Java objects and binds them to the parameters of the method.

For example, suppose the front end sends a POST request, and the request body contains a JSON object, which can be converted into a Java object using the @RequestBody annotation:

@PostMapping("/user")
public String addUser(@RequestBody User user) {
    
    
    // 处理请求参数
    return "success";
}

Among them, User is a Java class used to represent the JSON object in the request body. Spring Boot will automatically convert the JSON data in the request body into a User object and bind it to the parameters of the method.

In general, the @RequestParam annotation is used to obtain the value of the request parameter, and the @RequestBody annotation is used to obtain the data in the request body. Depending on the request, you can choose to use different annotations to process request parameters.

Guess you like

Origin blog.csdn.net/weixin_45506717/article/details/130401479