1.常用注解:
@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull 用在基本类型上
2.使用方法
1.使用全局异常类捕获 MethodArgumentNotValidException.class 在方法中不要写BindingResult参数,否则异常不会抛出,无法捕获校验信息
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleValidException(MethodArgumentNotValidException e) {
BaseResult baseResult = new BaseResult();
baseResult.setReturnCode("400");
baseResult.setReturnMsg(e.getBindingResult().getFieldError().getDefaultMessage());
//将错误信息返回给前台
return baseResult;
}
2.在方法中传入BindingResult参数,将异常封装在参数中,通过切面方法获取此参数取出校验信息
@Aspect
@Component
public class ParamValidAspect {
@Pointcut("execution(public * com.soc.cloud..controller.*.*(..))")
public void pointCut() {
}
@Before(value = "pointCut()")
public void paramValid(JoinPoint joinPoint) {
BindingResult bindingResult = null;
//遍历被通知方法(controller方法)的参数列表
for (Object arg : joinPoint.getArgs()) {
//参数校验结果会存放在BindingResult中
if (arg instanceof BindingResult) {
bindingResult = (BindingResult) arg;
String message = validRequestParams(bindingResult);
if (message.length() > 0) {
throw new BaseException("400", message);
}
break;
}
}
}
/**
* 校验
*/
private String validRequestParams(BindingResult result) {
StringBuilder sb = new StringBuilder();
if (result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
for (ObjectError objectError : allErrors) {
sb.append(objectError.getDefaultMessage()).append(";");
}
}
return sb.toString();
}
}
/**
* 测试
*/
@RequestMapping(value = "/testNotNull", method={RequestMethod.POST})
@ResponseBody
public BaseResult testNotNull(@RequestBody @Valid LombokTest lombokTest, BindingResult result) {
System.out.println(lombokTest);
return BaseResult.success();
}
@Data
static class LombokTest{
@NotNull(message = "a不能为空")
private String a;
@NotNull(message = "b不能为空")
private String b;
}