javax.validation.constraints 中定义了非常多的校验注解
@Email、@Future、@NotBlank、@Size 等
使用校验功能
提取校验错误信息
BindingResult 获取校验结果
分组校验与自定义校验
Groups 定义校验分组信息; 可以编写自定义校验注解和自定义校验器 默认情况下,异常信息会从应用的 classpath 下的 ValidationMessages.properties 文件中加载
* 1)给bean添加校验注解,并定义自己的message提示
* 2)开启校验功能@valid
* 效果:校验错误以后会有默认的响应
* 3)给校验的bean后紧跟一个bindingResult ,就可以获取到校验结果
* 4)分组校验
* 1)@NotNull(message = "修改必须指定品牌id",groups = UpdateGroup.class)
@Null(message = "新增不能指定id",groups = AddGroup.class)
* 2)@Validated(UpdateGroup.class)
* 3)默认没有指定分组的校验注解,@Null,在分组校验的情况下@Validated(UpdateGroup.class)不生效
public interface AddGroup {
}
public interface UpdateGroup {
}
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 品牌id
*/
@NotNull(message = "修改必须指定品牌id",groups = UpdateGroup.class)
@Null(message = "新增不能指定id",groups = AddGroup.class)
@TableId
private Long brandId;
/**
* 品牌名
*/
@NotBlank(message = "品牌名必须提交",groups = {AddGroup.class,UpdateGroup.class})
private String name;
/**
* 品牌logo地址
*/
@NotEmpty(groups = AddGroup.class)
@URL(message = "logo必须是一个url地址",groups = {AddGroup.class,UpdateGroup.class})
private String logo;
/**
* 介绍
*/
private String descript;
/**
* 显示状态[0-不显示;1-显示]
*/
@ListValue(vals = {0,1},groups = {UpdateStatusGroup.class})
@NotNull
private Integer showStatus;
/**
* 检索首字母
*/
@NotEmpty(groups = AddGroup.class)
@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是首字母",groups = {AddGroup.class,UpdateGroup.class})
private String firstLetter;
/**
* 排序
*/
@NotEmpty(groups = AddGroup.class)
@Min(value = 0,message = "排序必须大于等于0",groups = {AddGroup.class,UpdateGroup.class})
private Integer sort;
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@Validated({ AddGroup.class })@RequestBody BrandEntity brand, BindingResult result){
if(result.hasErrors()){
//1.获取校验错误的结果
Map<String, String> map = new HashMap<>();
result.getFieldErrors().forEach((item)->{
//FieldError获取到错误的提示
String message = item.getDefaultMessage();
//获取错误的属性的名字
String field = item.getField();
map.put(field,message);
System.out.println("******");
});
return R.error(400,"提交的数据不合法").put("data",map);
}
brandService.save(brand);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@Validated(UpdateGroup.class)@RequestBody BrandEntity brand){
brandService.updateById(brand);
return R.ok();
}