Spring接口传参非空校验@RequestParam默认值设置

时间:2025-03-17 18:24:58

场景

在写接口时,需要对传入的参数做是否位空的校验,减少if判断的代码逻辑,可以使用spring自带注解实现。

实现方式

在参数前增加@RequestParam注解来实现参数非空校验

@RequestMapping("api")
public void api(
String param0, // 非必传,默认值位Null
@RequestParam(required = false) String param1, // 非必传,默认值位Null
@RequestParam String param2, // 必传参数
@RequestParam(required = true) String param3, // 必传参数
@RequestParam(defaultValue = "0") Long param4 // 必传参数,空值默认时,赋默认值
){
...
}

不满足校验条件时返回400

{
    "timestamp": "2021-10-08T10:00:58.836+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/batch/encode"
}