使用spring-boot-starter-validation来进行参数校验
- 在pom配置中,引入包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
- 然后创建一个对象用来接收参数,在属性上添加需要校验的规则,如 @NotEmpty,Size(min=1,max=xxx,message=“错误后的提示”)
public class LoginByPhoneForm extends ToString { @NotEmpty @Size(min=3,max = 11,message = "请输入3-11位手机号") private String phone; @NotEmpty @Size(min = 1,max=20,message = "请输入1-20位密码") private String password; }
- 然后在mapping上面加入 @Valid @RequestBody这两个注解,如果不加@RequestBody表示表单提交,加了后表示是json提交参数.
@RequestMapping(value = "/uncheck/loginByPhone", method = RequestMethod.POST)
public Object loginByPhone(@Valid @RequestBody LoginByPhoneForm loginForm) {
}
-
最后在全局异常处理的类中,捕获异常,异常类为 MethodArgumentNotValidException,
并且获得的的Error对象需要强转成fieldError才能获取验证不通过的参数和错误信息.FieldError error = (FieldError) methodE.getBindingResult().getAllErrors().get(0)
@ControllerAdvice public class ExceptionHandle { @ExceptionHandler(value = Exception.class) @ResponseBody public ExceptionResult handle(Exception e) { if( e instanceof MethodArgumentNotValidException){ MethodArgumentNotValidException methodE = (MethodArgumentNotValidException) e; FieldError error = (FieldError) methodE.getBindingResult().getAllErrors().get(0); return new ExceptionResult(error.getField()+error.getDefaultMessage(), HttpCode.CODE_ERROR_ILLEGAL); } }