補習系列(4)-springboot 參數校驗詳解

[TOC]html

目標

  1. 對於幾種常見的入參方式,瞭解如何進行校驗以及該如何處理錯誤消息;
  2. 瞭解springboot 內置的參數異常類型,並能利用攔截器實現自定義處理;
  3. 能實現簡單的自定義校驗規則

1、PathVariable 校驗

在定義 Restful 風格的接口時,一般會採用 PathVariable 指定關鍵業務參數,以下:java

@GetMapping("/path/{group:[a-zA-Z0-9_]+}/{userid}")
@ResponseBody
public String path(@PathVariable("group") String group, @PathVariable("userid") Integer userid) {
    return group + ":" + userid;
}

{group:[a-zA-Z0-9_]+} 這樣的表達式指定了 group 必須是以大小寫字母、數字或下劃線組成的字符串。 咱們試着訪問一個錯誤的路徑:git

GET /path/testIllegal.get/10000

此時會獲得 404的響應,所以對於PathVariable 僅由正則表達式可達到校驗的目的web

2、方法參數校驗

相似前面的例子,大多數狀況下,咱們都會直接將HTTP請求參數映射到方法參數上。正則表達式

@GetMapping("/param")
@ResponseBody
public String param(@RequestParam("group")@Email String group, 
                    @RequestParam("userid") Integer userid) {
   return group + ":" + userid;
}

上面的代碼中,@RequestParam 聲明瞭映射,此外咱們還爲 group 定義了一個規則(複合Email格式) 這段代碼是否能直接使用呢?答案是否認的,爲了啓用方法參數的校驗能力,還須要完成如下步驟:spring

  • 聲明 MethodValidationPostProcessor
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
     return new MethodValidationPostProcessor();
}
  • Controller指定**@Validated**註解
@Controller
@RequestMapping("/validate")
@Validated
public class ValidateController {

如此以後,方法上的@Email規則才能生效。json

校驗異常 若是此時咱們嘗試經過非法參數進行訪問時,好比提供非Email格式的 group 會獲得如下錯誤:api

GET /validate/param?group=simple&userid=10000
====>
{
    "timestamp": 1530955093583,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "javax.validation.ConstraintViolationException",
    "message": "No message available",
    "path": "/validate/param"
}

而若是參數類型錯誤,好比提供非整數的 userid,會獲得:spring-mvc

GET /validate/param?group=simple&userid=1f
====>
{
    "timestamp": 1530954430720,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"1f\"",
    "path": "/validate/param"
}

當存在參數缺失時,因爲定義的@RequestParam註解中,屬性 required=true,也將會致使失敗:springboot

GET /validate/param?userid=10000
====>
{
    "timestamp": 1530954345877,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required String parameter 'group' is not present",
    "path": "/validate/param"
}

3、表單對象校驗

頁面的表單一般比較複雜,此時能夠將請求參數封裝到表單對象中, 並指定一系列對應的規則,參考JSR-303

public static class FormRequest {

    @NotEmpty
    @Email
    private String email;

    @Pattern(regexp = "[a-zA-Z0-9_]{6,30}")
    private String name;

    @Min(5)
    @Max(199)
    private int age;

上面定義的屬性中:

  • email必須非空、符合Email格式規則;
  • name必須爲大小寫字母、數字及下劃線組成,長度在6-30個;
  • age必須在5-199範圍內

Controller方法中的定義:

@PostMapping("/form")
@ResponseBody
public FormRequest form(@Validated FormRequest form) {
    return form;
}

@Validated指定了參數對象須要執行一系列校驗。

校驗異常 此時咱們嘗試構造一些違反規則的輸入,會獲得如下的結果:

{
    "timestamp": 1530955713166,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.validation.BindException",
    "errors": [
        {
            "codes": [
                "Email.formRequest.email",
                "Email.email",
                "Email.java.lang.String",
                "Email"
            ],
            "arguments": [
                {
                    "codes": [
                        "formRequest.email",
                        "email"
                    ],
                    "arguments": null,
                    "defaultMessage": "email",
                    "code": "email"
                },
                [],
                {
                    "arguments": null,
                    "codes": [
                        ".*"
                    ],
                    "defaultMessage": ".*"
                }
            ],
            "defaultMessage": "不是一個合法的電子郵件地址",
            "objectName": "formRequest",
            "field": "email",
            "rejectedValue": "tecom",
            "bindingFailure": false,
            "code": "Email"
        },
        {
            "codes": [
                "Pattern.formRequest.name",
                "Pattern.name",
                "Pattern.java.lang.String",
                "Pattern"
            ],
            "arguments": [
                {
                    "codes": [
                        "formRequest.name",
                        "name"
                    ],
                    "arguments": null,
                    "defaultMessage": "name",
                    "code": "name"
                },
                [],
                {
                    "arguments": null,
                    "codes": [
                        "[a-zA-Z0-9_]{6,30}"
                    ],
                    "defaultMessage": "[a-zA-Z0-9_]{6,30}"
                }
            ],
            "defaultMessage": "須要匹配正則表達式\"[a-zA-Z0-9_]{6,30}\"",
            "objectName": "formRequest",
            "field": "name",
            "rejectedValue": "fefe",
            "bindingFailure": false,
            "code": "Pattern"
        },
        {
            "codes": [
                "Min.formRequest.age",
                "Min.age",
                "Min.int",
                "Min"
            ],
            "arguments": [
                {
                    "codes": [
                        "formRequest.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                },
                5
            ],
            "defaultMessage": "最小不能小於5",
            "objectName": "formRequest",
            "field": "age",
            "rejectedValue": 2,
            "bindingFailure": false,
            "code": "Min"
        }
    ],
    "message": "Validation failed for object='formRequest'. Error count: 3",
    "path": "/validate/form"
}

若是是參數類型不匹配,會獲得:

{
    "timestamp": 1530955359265,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.validation.BindException",
    "errors": [
        {
            "codes": [
                "typeMismatch.formRequest.age",
                "typeMismatch.age",
                "typeMismatch.int",
                "typeMismatch"
            ],
            "arguments": [
                {
                    "codes": [
                        "formRequest.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                }
            ],
            "defaultMessage": "Failed to convert property value of type 'java.lang.String' 
to required type 'int' for property 'age'; nested exception is java.lang.NumberFormatException: 
For input string: \"\"",
            "objectName": "formRequest",
            "field": "age",
            "rejectedValue": "",
            "bindingFailure": true,
            "code": "typeMismatch"
        }
    ],
    "message": "Validation failed for object='formRequest'. Error count: 1",
    "path": "/validate/form"
}

Form表單參數上,使用@Valid註解可達到一樣目的,而關於二者的區別則是:

@Valid 基於JSR303,即 Bean Validation 1.0,由Hibernate Validator實現; @Validated 基於JSR349,是Bean Validation 1.1,由Spring框架擴展實現;

後者作了一些加強擴展,如支持分組校驗,有興趣可參考這裏

4、RequestBody 校驗

對於直接Json消息體輸入,一樣能夠定義校驗規則:

@PostMapping("/json")
@ResponseBody
public JsonRequest json(@Validated @RequestBody JsonRequest request) {

    return request;
}

...
public static class JsonRequest {

    @NotEmpty
    @Email
    private String email;

    @Pattern(regexp = "[a-zA-Z0-9_]{6,30}")
    private String name;

    @Min(5)
    @Max(199)
    private int age;

校驗異常 構造一個違反規則的Json請求體進行輸入,會獲得:

{
    "timestamp": 1530956161314,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
    "errors": [
        {
            "codes": [
                "Min.jsonRequest.age",
                "Min.age",
                "Min.int",
                "Min"
            ],
            "arguments": [
                {
                    "codes": [
                        "jsonRequest.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                },
                5
            ],
            "defaultMessage": "最小不能小於5",
            "objectName": "jsonRequest",
            "field": "age",
            "rejectedValue": 1,
            "bindingFailure": false,
            "code": "Min"
        }
    ],
    "message": "Validation failed for object='jsonRequest'. Error count: 1",
    "path": "/validate/json"
}

此時與FormBinding的狀況不一樣,咱們獲得了一個MethodArgumentNotValidException異常。 而若是發生參數類型不匹配,好比輸入age=1f,會產生如下結果:

{
    "timestamp": 1530956206264,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "Could not read document: Can not deserialize value of type int from String \"ff\": not a valid Integer value\n at [Source: java.io.PushbackInputStream@68dc9800; line: 2, column: 8] (through reference chain: org.zales.dmo.boot.controllers.ValidateController$JsonRequest[\"age\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type int from String \"ff\": not a valid Integer value\n at [Source: java.io.PushbackInputStream@68dc9800; line: 2, column: 8] (through reference chain: org.zales.dmo.boot.controllers.ValidateController$JsonRequest[\"age\"])",
    "path": "/validate/json"
}

這代表在JSON轉換過程當中已經失敗!

5、自定義校驗規則

框架內預置的校驗規則能夠知足大多數場景使用, 但某些特殊狀況下,你須要製做本身的校驗規則,這須要用到ContraintValidator接口。

咱們以一個密碼校驗的場景做爲示例,好比一個註冊表單上, 咱們須要檢查 密碼輸入密碼確認 是一致的。

**首先定義 PasswordEquals 註解

@Documented
@Constraint(validatedBy = { PasswordEqualsValidator.class })
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface PasswordEquals {

    String message() default "Password is not the same";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

在表單上聲明@PasswordEquals 註解

@PasswordEquals
public class RegisterForm {
   
    @NotEmpty
    @Length(min=5,max=30)
    private String username;
    
    @NotEmpty
    private String password;
    
    @NotEmpty
    private String passwordConfirm;

針對@PasswordEquals實現校驗邏輯

public class PasswordEqualsValidator implements ConstraintValidator<PasswordEquals, RegisterForm> {

    @Override
    public void initialize(PasswordEquals anno) {
    }

    @Override
    public boolean isValid(RegisterForm form, ConstraintValidatorContext context) {
        String passwordConfirm = form.getPasswordConfirm();
        String password = form.getPassword();

        boolean match = passwordConfirm != null ? passwordConfirm.equals(password) : false;
        if (match) {
            return true;
        }

        String messageTemplate = context.getDefaultConstraintMessageTemplate();
        
        // disable default violation rule
        context.disableDefaultConstraintViolation();

        // assign error on password Confirm field
        context.buildConstraintViolationWithTemplate(messageTemplate).addPropertyNode("passwordConfirm")
                .addConstraintViolation();
        return false;

    }
}

如此,咱們已經完成了自定義的校驗工做。

6、異常攔截器

SpringBoot 框架中可經過 @ControllerAdvice 實現Controller方法的攔截操做。 能夠利用攔截能力實現一些公共的功能,好比權限檢查、頁面數據填充,以及全局的異常處理等等。

在前面的篇幅中,咱們說起了各類校驗失敗所產生的異常,整理以下表:

異常類型 描述
ConstraintViolationException 違反約束,javax擴展定義
BindException 綁定失敗,如表單對象參數違反約束
MethodArgumentNotValidException 參數無效,如JSON請求參數違反約束
MissingServletRequestParameterException 參數缺失
TypeMismatchException 參數類型不匹配

若是但願對這些異常實現統一的捕獲,並返回自定義的消息, 能夠參考如下的代碼片斷:

@ControllerAdvice
public static class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { ConstraintViolationException.class })
    public ResponseEntity<String> handle(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations) {
            strBuilder.append(violation.getInvalidValue() + " " + violation.getMessage() + "\n");
        }
        String result = strBuilder.toString();
        return new ResponseEntity<String>("ConstraintViolation:" + result, HttpStatus.BAD_REQUEST);
    }

    @Override
    protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status,
            WebRequest request) {
        return new ResponseEntity<Object>("BindException:" + buildMessages(ex.getBindingResult()),
                HttpStatus.BAD_REQUEST);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>("MethodArgumentNotValid:" + buildMessages(ex.getBindingResult()),
                HttpStatus.BAD_REQUEST);
    }

    @Override
    public ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>("ParamMissing:" + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    @Override
    protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers,
            HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>("TypeMissMatch:" + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    private String buildMessages(BindingResult result) {
        StringBuilder resultBuilder = new StringBuilder();

        List<ObjectError> errors = result.getAllErrors();
        if (errors != null && errors.size() > 0) {
            for (ObjectError error : errors) {
                if (error instanceof FieldError) {
                    FieldError fieldError = (FieldError) error;
                    String fieldName = fieldError.getField();
                    String fieldErrMsg = fieldError.getDefaultMessage();
                    resultBuilder.append(fieldName).append(" ").append(fieldErrMsg).append(";");
                }
            }
        }
        return resultBuilder.toString();
    }
}

默認狀況下,對於非法的參數輸入,框架會產生 **HTTP_BAD_REQUEST(status=400) ** 錯誤碼, 並輸出友好的提示消息,這對於通常狀況來講已經足夠。

更多的輸入校驗及提示功能應該經過客戶端去完成(服務端僅作同步檢查), 客戶端校驗的用戶體驗更好,而這也符合**富客戶端(rich client)**的發展趨勢。

碼雲同步代碼

參考文檔

springmvc-validation樣例 使用validation api進行操做 hibernate-validation官方文檔 Bean-Validation規範

歡迎繼續關注"美碼師的補習系列-springboot篇" ,期待更多精彩內容^-^

相關文章
相關標籤/搜索