The difference between @RequestParam and @RequestBody annotations

Getting parameters from client requests is a very common requirement when developing web applications. In Spring MVC, we can use @RequestParamand @RequestBodyto get request parameters, but they have some differences in usage and function.

@RequestParam

@RequestParamThe annotation is used to get the value of the request parameter. It can be used to get query parameters or form parameters in the URL. By default, the parameter of this annotation is required, if there is no such parameter in the request, an exception will be thrown. required = falseIt can be set as an optional parameter by setting .

The specific usage is as follows:

@GetMapping("/example")
public void example(@RequestParam("param") String param) {
    
    
    // 处理请求参数
}

In the above example, paramis the name of the request parameter and Stringis the type of the parameter. Spring MVC will automatically bind the parameter value in the request to paramthe parameter.

@RequestBody

@RequestBodyAnnotations are used to get data in the request body. It can bind data in JSON, XML or other formats in the request body to method parameters. Usually used to handle POST or PUT requests, where the request body contains data that needs to be passed to the backend.

The specific usage is as follows:

@PostMapping("/example")
public void example(@RequestBody User user) {
    
    
    // 处理请求体中的数据
}

In the above example, Userit is an entity class, and the JSON data in the request body will be automatically mapped to Userthe object. Spring MVC uses a message converter (MessageConverter) to convert the data in the request body to the type required by the method parameter.

It should be noted that when the front end sends a request, the in the request header Content-Typeneeds to be set to the corresponding format, such as application/json.

Summarize:

  • @RequestParamUsed to get the value of the request parameter, suitable for getting URL query parameters or form parameters.
  • @RequestBodyIt is used to obtain the data in the request body, and is suitable for obtaining data in formats such as JSON and XML in the request body.

By using these two annotations, we can easily obtain and process parameters in client requests to achieve more flexible and precise data interaction. Such usage can improve development efficiency and make code clearer and easier to read.

Guess you like

Origin blog.csdn.net/weixin_65837469/article/details/131383794