Table of contents
When using the Spring Web framework to develop Web applications, we usually need to obtain information such as request parameters, request body, and request attributes. In order to easily extract this information, Spring Web provides multiple annotations, including @RequestParam
, @RequestBody
, @RequestAttribute
and@RequestPart
etc.
In this blog, we will introduce the use of these annotations and provide concrete examples.
1. @RequestParam
The @RequestParam annotation is used to obtain the value of an HTTP request parameter.
Attributes such as name, value, required, and defaultValue can be used to specify information such as the parameter name, whether it is required, and the default value. If the request parameter name is inconsistent with the method parameter name, it can be solved by setting the value attribute of @RequestParam.
The sample code is as follows:
conventional usage
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/info")
public String userInfo(@RequestParam("user_id") int userId) {
//处理业务逻辑
return "user_info";
}
}
In the above code, the @RequestParam annotation obtains the value of the parameter named user_id submitted by the front-end page, and assigns it to the method parameter userId.
@PathVariable
annotation
value
Attributes can be omitted if the request parameter and method parameter have the same name .
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id, @RequestParam String name) {
return userService.getUserByIdAndName(id, name);
}
In this example, we use @PathVariable
annotations to id
map URL path parameters to method parameters id
, and use annotations to map @RequestParam
request parameters to method parameters .name
name
optional parameters
Sometimes, request parameters may not be necessary. To avoid throwing an exception, we can set required
the property to false
.
@GetMapping("/users")
public List<User> getUsers(@RequestParam(required = false) String name) {
if (name == null) {
return userService.getAllUsers();
} else {
return userService.getUsersByName(name);
}
}
In this example, we use @RequestParam
annotations to name
map request parameters to method parameters name
and set required
the property to false
. If the request parameter does not exist, returns all users; otherwise returns a list of users with the specified name.
2. @RequestBody
The @RequestBody annotation is used to obtain the content in the request body of the HTTP request, and is often used to process POST requests.
After using this annotation, Spring will automatically encapsulate the data such as JSON/XML in the request body into Java objects for easy operation.
The sample code is as follows:
conventional usage
@Controller
@RequestMapping("/user")
public class UserController {
@PostMapping("/add")
public String addUser(@RequestBody User user) {
//处理业务逻辑
return "add_success";
}
}
In the above code, the @RequestBody annotation encapsulates the JSON/XML data in the request body into a User object to facilitate subsequent operations.
JSON format data
If the request body is data in JSON format, we can use @RestController
annotations and @PostMapping
annotations to automatically convert it to a Java object.
@RestController
public class UserController {
@PostMapping("/users")
public User createUser(@RequestBody CreateUserRequest request) {
User user = new User(request.getName(), request.getAge());
return userService.createUser(user);
}
}
public class CreateUserRequest {
private String name;
private int age;
// getters and setters
}
In this example, we use @RestController
annotations and @PostMapping
annotations to handle POST requests, and use CreateUserRequest
classes to automatically convert the request body to a Java object.
3. @RequestAttribute
The @RequestAttribute annotation is used to obtain the attribute value in the HTTP request, usually set by a filter or interceptor before the request is processed.
The attribute name can be specified through the name attribute. The sample code is as follows:
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/info")
public String userInfo(@RequestAttribute("user_name") String userName) {
//处理业务逻辑
return "user_info";
}
}
In the above code, the @RequestAttribute annotation obtains the attribute value named user_name in the request and assigns it to the method parameter userName.
4. @RequestPart
The @RequestPart annotation is used to process file upload requests, and can directly encapsulate files into Java objects.
When processing file uploads, you need to use the multipart/form-data encoding method, and the name value in the form needs to be consistent with the value value in the @RequestPart annotation. The sample code is as follows:
conventional usage
@Controller
@RequestMapping("/user")
public class UserController {
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadFile(@RequestPart MultipartFile file, @RequestParam String description) {
// 处理文件和参数
}
}
In this example, we use @RequestPart
annotations to map uploaded files to method parameters file
, and @RequestParam
annotations to map request parameters description
to method parameters description
. This way, we can upload the file with description information.
upload multiple files
If you want to upload multiple files, you can use MultipartFile[]
the type parameter.
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadFiles(@RequestPart("fileList") MultipartFile[] fileList, @RequestParam String description) {
// 处理文件和参数
}
In this example, we use @RequestPart
annotations to map multiple uploaded files to method parameters fileList
. In this way, we can upload multiple files with description information.
Note: @RequestPart
When using annotations, it must be specified at the same time Content-Type
, multipart/form-data
otherwise an exception will be thrown.
Summarize:
The above is the detailed explanation and specific examples of @RequestParam, @RequestBody, @RequestAttribute, @RequestPart annotations. They can greatly simplify the acquisition of HTTP request parameters and the operation of file upload.