SpringBoot 基于Hibernate Validator参数校验

jar:org.hibernate hibernate-validator 5.4.1.Final


1.JSON格式


(1)实体字段添加注解

@Length(max=16,message="卡号不能超过16位")

private String cardNo;


(2)controller方法添加@Validated注解

test(@RequestBody @Validated ReqVO reqVO){};


(3)需在处理器增强@ControllerAdvice配置MethodArgumentNotValidException异常处理

@ExceptionHandler(MethodArgumentNotValidException.class)

@ResponseBody

public Model handleMethodArgumentNotValidException(MethodArgumentNotValidExceptione){

List errors = e.getBindingResult().getAllErrors();

StringBuffer errorMsg = new StringBuffer();

errors.forEach(x->errorMsg.append(x.getDefaultMessage()).append(";"));

return newModel(ApiBaseErrEnum.getErrCode(),errorMsg.toString());

}


2.form-data 封装对象接收参数


(1)实体字段添加注解

@Length(max=16,message="卡号不能超过16位")

private String cardNo;


(2)controller方法添加@Validated注解

test(@Validated ReqVO reqVO){};


(3)需在处理器增强@ControllerAdvice配置BindException异常处理

@ExceptionHandler(BindException.class)

@ResponseBody

public Model handleBindException(BindExceptione){

List errors = e.getBindingResult().getAllErrors();

StringBuffer errorMsg = new StringBuffer();

errors.forEach(x->errorMsg.append(x.getDefaultMessage()).append(";"));

return new Model(ApiBaseErrEnum.getErrCode(),errorMsg.toString());

}


3. form-data 普通字段接收参数


(1)校验请求是否包含所需参数,只需于@ControllerAdvice配置MissingServletRequestParameterException异常处理

//接收参数需配@Requestparam

@ExceptionHandler({MissingServletRequestParameterException.class})

@ResponseBody

public Model test(MissingServletRequestParameterExceptionex){

return new Model(ApiBaseErrEnum.getErrCode(),ex.getParameterName());

}


(2)校验接收参数格式是否正确


(2.1)首先需要创建MethodValidationPostProcessor

@Bean

public MethodValidationPostProcessor methodValidationPostProcessor(){

return new MethodValidationPostProcessor();

}


(2.2) 需在处理器增强@ControllerAdvice配置 ConstraintViolationException 异常处理

@ExceptionHandler(ConstraintViolationException.class)

@ResponseBody

public Model handleConstraintViolationException(ConstraintViolationExceptione) {

Set> errors = e.getConstraintViolations();

StringBuffe rerrorMsg = new StringBuffer();

errors.forEach(x->errorMsg.append(x.getMessageTemplate()).append(";"));

return new Model(ApiBaseErrEnum.getErrCode(),errorMsg.toString());

}


(2.3)controller添加@Validated注解

@RestController

@RequestMapping

@Validated

public class TestController{


(2.4)controller方法添加所需注解,具体注解请自行查看

public Model test( @Length(min=3,message="最小长度为3") String id ) { }



随手笔记,如有错误请指出,谢谢!


你可能感兴趣的:(SpringBoot 基于Hibernate Validator参数校验)