Getting parameters from client requests is a very common requirement when developing web applications. In Spring MVC, we can use @RequestParam
and @RequestBody
to get request parameters, but they have some differences in usage and function.
@RequestParam
@RequestParam
The 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 = false
It 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, param
is the name of the request parameter and String
is the type of the parameter. Spring MVC will automatically bind the parameter value in the request to param
the parameter.
@RequestBody
@RequestBody
Annotations 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, User
it is an entity class, and the JSON data in the request body will be automatically mapped to User
the 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-Type
needs to be set to the corresponding format, such as application/json
.
Summarize:
@RequestParam
Used to get the value of the request parameter, suitable for getting URL query parameters or form parameters.@RequestBody
It 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.