**
Springboot required = false运用
**
先上代码
Controller
public JsonResult<?> addTest(@RequestBody(required = false)LuTestStudent luTestStudent){
return luTestStudentService.add(luTestStudent);
}
impl
public JsonResult<?> add(LuTestStudent luTestStudent) {
/**
* 除字符串外需用ObjectUtils 判断是否为null
*/
if (ObjectUtil.isEmpty(luTestStudent)){
throw new BaseException("传入参数异常");
}
/**
* 字符串需用 StringUtils isBlank进行判断 字符串为 ""或null 都不允许 isEmpty 不判断 ""
*/
if (StringUtils.isBlank(luTestStudent.getName())){
throw new BaseException("名称不能为空");
}
return new JsonResult<>("添加成功");
}
required = false的作用是 如果传来的值是空 也能进入impl的方法
很显然 这里的报错是进入了impl ObjectUtil.isEmpty判断对象是否为空的错
当测试接口改成如下
这里json传值 加了 {} ObjectUtil.isEmpty只参数判断是否为null 不判断里面是否""
当我们把controller中的required = false删除
再进行访问
很显然 required = false删除之后 null的参数无法让方法正常执行
但当我测试接口 json再加{}之后
爆错为 名称不能为空 说明 required 和 ObjectUtil.isEmpty 不判断 json的{} 是空