一、自定义类实现Validator接口
重写supports和validate这两个方法,在supports中写你要需校验的参数,在validate中定义你需要校验的规则
public class WarehouseAreaValidator implements Validator {@Overridepublic boolean supports(Class<?> clazz) {return WareHouseAreaReqDTO.class.equals(clazz);}@Overridepublic void validate(Object target, Errors errors) {WareHouseAreaReqDTO warehouseAreaReqDTO = (WareHouseAreaReqDTO) target;if (Objects.isNull(warehouseAreaReqDTO.getUniqueId())) {errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), "唯一标识不能为空");}if (Objects.isNull(warehouseAreaReqDTO.getLngAndLat())) {errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), "库区点位值不能为空");} else if (Objects.equals(warehouseAreaReqDTO.getGeoType(), "POINT")) {if (!ValidateUtil.validateWktPoint(warehouseAreaReqDTO.getLngAndLat())) {errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), "库区点位值格式不正确");}} else if (Objects.equals(warehouseAreaReqDTO.getGeoType(), "POLYGON")) {if (!ValidateUtil.validateWktPolygon(warehouseAreaReqDTO.getLngAndLat())) {errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), "库区点位值格式不正确");}} else {errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), "请正确输入点位类型和值");}}
}
二、在controller中实现校验Dto
毕竟应用场景不一样,并且也不止这一种方法,大家自行参考
//校验参数List<String> errorMessageList = new ArrayList<>();for (WareHouseAreaReqDTO wareHouseAreaReqDTO : wareHouseAreaReqDTOList) {ValidateUtil.validate(errorMessageList,wareHouseAreaReqDTO,new WarehouseAreaValidator());}if (!CollectionUtils.isEmpty(errorMessageList)) {String errorMessage = StringUtils.join(errorMessageList,",");return Response.failure(errorMessage);}
Validate工具类
/*** 校验参数* @param errrorMessageList 错误信息* @param object 校验对象* @param validator 自定义validator实现类* @return 错误信息*/public static List<String> validate(List<String> errrorMessageList, Object object, Validator validator) {DataBinder binder = new DataBinder(object);binder.setValidator(validator);binder.validate();BindingResult result = binder.getBindingResult();if (result.hasErrors()) {for (ObjectError allError : result.getAllErrors()) {errrorMessageList.add(allError.getDefaultMessage());}}return errrorMessageList;}