https://github.com/MaHanZhen/SpringBootStudy/tree/master/demo3
第一步,编写接收参数类
public class Student {
@NotNull(message = "传入姓名为null")
@NotEmpty(message = "传入姓名为空字符串")
private String name;
@NotNull(message = "传入成绩为null")
@Min(value = 0,message ="成绩应大于0")
@Max(value = 0,message ="成绩应小于100")
private Integer score;
@NotNull(message = "传入电话为null")
@NotEmpty(message = "传入电话为空字符串")
@Length(min = 11,max =11,message ="电话号码长度有误")
private String mobile;
//get,set
}
第二步,在请求处添加注解
//@Valid 注解 启用参数校验
@RequestMapping("/testValid")
public String testValid(@Valid Student student){
System.out.println(student);
return "success";
}
测试
但是这里返回结果过于复杂,就需要使用过滤器
定义全局异常处理器
@ControllerAdvice //定义全局处理器
@ResponseBody
public class GlobalExceptionInterceptor {
@ExceptionHandler(value = Exception.class) //定义异常处理器
public String exceptionHandler(HttpServletRequest request,Exception e) {
String failMessage = null;
//判断是否为绑定异常
if(e instanceof BindException){
BindException ex = (BindException)e;
failMessage = ex.getBindingResult().getFieldError().getDefaultMessage();
}
return failMessage;
}
}
测试