解决方法:
1.导入依赖,版本与springboot一致
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${spring-boot-starter-validation}</version>
</dependency>
2.在需要校验的实体类的字段上加上注解
如下
@NotBlank(message = "品牌名必须提交")
private String name;
3.编写捕捉到错误的逻辑,记住要开启数据校验要加@Valid注解
@RequestMapping("/save")
public R save(@Valid @RequestBody BrandEntity brand, BindingResult bindingResult){
log.info("提交表单:{}",brand);
if(bindingResult.hasErrors()){
Map<String ,String> map = new HashMap<>();
//获取错误提示
bindingResult.getFieldErrors().forEach((item) ->{
//获取错误提示
String message = item.getDefaultMessage();
//获取错误属性名字
String field = item.getField();
map.put(field,message);
});
return R.error(400,"提交的数据不合法").put("data",map);
}else {
brandService.save(brand);
}
return R.ok();
}
完成
标签:String,不可,boot,校验,brand,注解,message,save,bindingResult From: https://blog.csdn.net/2401_84763035/article/details/143617118