1. 程式人生 > >媽媽再也不用擔心我的後端介面校驗

媽媽再也不用擔心我的後端介面校驗

做後端的同學都知道引數校驗實在是太繁瑣的事情,今天我們就藉助於hibernate.validator實現解放我們的雙手,讓校驗變得賞心悅目

手寫的一個工具類

package com.util;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.constraints.*;

import javax.validation.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 物件校驗工具類
 */
public class ValidatorUtil {
    private Validator val;

    private ValidatorUtil(){
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                // 是否快速返回錯誤,false返回全部錯誤,true只返回第一條錯誤
                .addProperty( "hibernate.validator.fail_fast", "false" )
                .buildValidatorFactory();
        val = validatorFactory.getValidator();
    }
    public static ValidatorUtil getIns(){
        return Holder.ins;
    }


    private static class Holder{
        private static ValidatorUtil ins=new ValidatorUtil();
    }



    public  <T> String getMsg(T model){
        Set<ConstraintViolation<T>> violationSet = val.validate(model);
        StringBuilder sb=new StringBuilder();
        for (ConstraintViolation<T> m : violationSet) {
            sb.append(m.getMessage()).append(" ");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Demo d=new Demo();
        d.list=new ArrayList<>();
        d.str="";
        System.out.println(ValidatorUtil.getIns().getMsg(d));
    }
}

/**
 * 常用
 */
class Demo{
    @NotBlank(message = "name空")
    public String name;
    @NotNull(message = "name1空")
    public String name1;
    @NotEmpty(message = "name2空")
    public String name2;
    @NotEmpty(message = "email空")
    @Email(message = "email格式錯誤")
    public String email;
    @NotEmpty(message = "list空")
    public List<String> list;
    @Range(min=1,max=5,message = "不在range")
    public Integer num;

    @Min(value = 1,message = "最低1")
    @NotEmpty(message = "num1空")
    public Integer num1;
    @Max(value =2 ,message = "最大2")
    @NotNull(message = "num2空")
    public Integer num2;

    @Length(min = 1, max = 20, message = "字串過長")
    public String str;

    //級聯
    @Valid
    List<Demo> ds;
}

使用方法見demo與main

spring boot專案中整合

再controller方法中添加註解

@RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData addOrUpdate(@Valid @RequestBody TemplateVo vo) {

vo中屬性加上校驗註解,參考demo類
再新增到異常處理攔截器,這樣當引數校驗失敗時,自動攔截返回自定義訊息物件

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class DefaultExceptionHandler {
@ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object validException(MethodArgumentNotValidException e) {
    	System.out.println(ValidUtil.getErrors(e.getBindingResult())))
        return new Object();
    }
}

ValidUtil


import java.util.Iterator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

public class ValidUtil {
    public ValidUtil() {
    }

    public static String getErrors(BindingResult bindingResult) {
        String errorMesssage = "校驗資訊:\n";
        FieldError fieldError;
        if (bindingResult.hasErrors()) {
            for(Iterator var2 = bindingResult.getFieldErrors().iterator(); var2.hasNext(); errorMesssage = errorMesssage + fieldError.getDefaultMessage() + "\n") {
                fieldError = (FieldError)var2.next();
            }
        }

        return errorMesssage;
    }
}