@RequestParam、@RequestBody、@RequestPart 对比
- 请求体格式:
- @RequestParam:application/x-www-form-urlencoded
- @RequestBody:application/json、application/xml
- @RequestPart:multipart/form-data
- 入参类型:
- @RequestParam:基本类型、String、MultipartFile
- @RequestBody:k-v
- @RequestPart:k-v,MultipartFile
- 注解属性
- @RequestParam:value/name、required、defaultValue
- @RequestBody:required
- @RequestPart:value/name、required
匹配解析器:
/**
* Find a registered {@link HandlerMethodArgumentResolver} that supports
* the given method parameter.
*/
@Nullable
private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
if (result == null) {
for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) {
if (resolver.supportsParameter(parameter)) {
result = resolver;
this.argumentResolverCache.put(parameter, result);
break;
}
}
}
return result;
}
@RequestHeader、@RequestAttribute、@PathVariable、@CookieValue、@SessionAttribute 对比
作用:
@RequestHeader:用于接收请求头中的参数
@RequestAttribute:用于接收上一个请求中设置的参数
@PathVariable:用于接收路径中的参数
@CookieValue:用于接收 Cookie 中的参数
@SessionAttribute:用于接收 Session 中的参数
用例:
// 1 @RequestParam
// 1.1 指定属性名
@GetMapping("/test")
public Result test(@RequestParam("param") String param);
// 1.2 指定非必传,默认是必传
@GetMapping("/test")
public Result test(@RequestParam(value = "param", required = false) String param);
// 2 @RequestBody
@PostMapping("/test")
public Result test(@RequestBody Map<String, Object> params);
// 3 @RequestPart
@PostMapping("/test")
public Result test(@RequestParam("file") MultipartFile file, @RequestPart("params") Map<String, Object> params);
// 4 @RequestHeader
@GetMapping("/test")
public Result test(@RequestHeader("param") String param);
// 5 @RequestAttribute
@GetMapping("/test")
public Result test(@RequestAttribute("param") String param);
// 6 @PathVariable
@GetMapping("/test/{param}")
public Result test(@PathVariable("param") String param);
// 7 @CookieValue
@GetMapping("/test")
public Result test(@CookieValue("param") String param);
// 8 @SessionAttribute
@GetMapping("/test")
public Result test(@SessionAttribute("param") String param);