[Springboot] @Valid parameter check

Editor:

  https://blog.csdn.net/cp026la/article/details/86495659

Nonsense:

  The beginning of time writing code or do not do to check parameters, or write many similar if (xx == null) {...} statement, parameters always want to check to be front-end processing (very witty), end of service calibration parameters are equally important.

Check parameters:

springboot need to introduce springboot-starter-validation (verification using Hibernate Validator framework provides functionality) dependent calibration parameter, since the item has been introduced springboot-starter-web-dependent (comprising springboot-starter-validation dependent ), you do not need to repeat references.

1, the basic introduction notes:

@NotEmpty: role String, collection, map, the array is not null, the size> 0 
@NotBlank: only for String, can not be null, can not be "", i.e., trim (rear) length is greater than 0 
@ @NotNull: acting on any type and can not be null, can be null 
@AssertTrue: must be to true 
@AssertFalse: must to false 
@min (value): it must be a number that is equal to and greater than a specified value 
@Max (value) : must be a number, and the value of a specified value or less 
@Size (max, min): limiting parameter size range 
@Future: it must be a future date 
@Past: a date in the past must be 
@Pattern (value): Specifies regular

2, the entity class:

/ ** 
 * @Auther: XF 
 * @date: 2018/11/01 23:27 
 * @Description: 
 * / 
@Data 
public class ValidEntity { 

    @NotBlank (Message = "name may not be empty") 
    @Size (= 2 min , max = 4, message = "name length is 2-4") 
    Private String name; 

    @NotNull (Message = "Age is not null") 
    @min (value = 0, Message = "Age not less than the minimum value 0 ") 
    Private int Age; 

}  

 

3, the test Controller:

/ ** 
 * @Auther: XF 
 * @date: 2018/11/01 23:35 
 * @Description: check test parameters 
 * / 
@RestController 
@ SLF4J 
public class TestValidController { 

    @PostMapping (value = "/ Valid") 
    public ApiResult Valid (@Valid @RequestBody validEntity validEntity) { 
        log.info ( "entity class information >>>>: >>>> {}", JSON.toJSONString (validEntity)); 
        return ApiResult.ok (validEntity); 
    } 
}  

 

4, the test results:
here POST request, using Postman:
4.1, the correct transmission parameter (here parameter JSON format) returns the correct result.
4.2, mass participation error error response message

Error Log:

5、注意:
此处的日志很显然是统一异常处理类GlobalExceptionHandler中的日志,即参数校验不通过的时候走到了统一异常处理类中了。这里返回了所有的异常信息,显得不优雅,我们可以在统一异常处理类中断点调试得到该JSON格式错误的参数校验不通过是使用的MethodArgumentNotValidException 返回的。

 

 

6、当我将请求参数的@RequestBody 去掉后:

@PostMapping(value = "/valid")
public ApiResult valid(@Valid ValidEntity validEntity) {
     log.info(">>>>实体类信息为:>>>>{}", JSON.toJSONString(validEntity));
     return ApiResult.ok(validEntity);
}

 

再次请求:

断点调试得到的是BindException

于是,我们可以在统一异常处理类中添加这两个异常的处理方法,当然也可以在原来的Exception 处理中去做判断,这里分别添加这两个异常的处理。

7、修改原来的全局异常处理类:

@RestControllerAdvice(annotations = {RestController.class})
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 默认统一异常处理方法
     * @ExceptionHandler 注解用来配置需要拦截的异常类型, 也可以是自定义异常
     */
    @ExceptionHandler(Exception.class)
    // 此处可以指定返回的状态码 和 返回 结果说明
    // @ResponseStatus(reason = "exception",value = HttpStatus.BAD_REQUEST)
    public Object runtimeExceptionHandler(Exception e) {
        // 打印异常信息到控制台
        e.printStackTrace();
        log.error("请求出现异常,异常信息为: {}", e.getMessage());
        // 使用公共的结果类封装返回结果, 这里我指定状态码为 400
        return ApiResult.build(400, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        return ApiResult.build(400, fieldError.getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    public ApiResult handleBindException(BindException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        return ApiResult.build(400, fieldError.getDefaultMessage());
    }
} 

 

至此参数校验配置完毕。

Guess you like

Origin www.cnblogs.com/wjqhuaxia/p/12148888.html