1. 程式人生 > >Spring對物件屬性的校驗

Spring對物件屬性的校驗

場景:對物件的引數進行校驗,如果不通過丟擲異常

1.編寫需要被校驗的物件

public class Pet {

    @NotEmpty(message = "不能為空")
    private String name;
    @Range(min = 0, max = 150, message = "範圍在0—150之間")
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.定義異常體系
public class BaseException extends RuntimeException {

    private int code;

    BaseException(ExceptionDesception e){
        super(e.getMsg());
        this.code=e.getCode();
    }

    BaseException(int code,String msg){
        super(msg);
        this.code=code;
    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

2.1 定義引數異常類

public class ParamInvalidException extends BaseException {

    public ParamInvalidException(ExceptionDesception e) {
        super(e);
    }

    public ParamInvalidException(int code, String msg) {
        super(code, msg);
    }
}
2.2定義異常描述類
public enum  ExceptionDesception {

    NO_PERMISSION(-1,"無許可權"),
    PARAM_INVALID(-2,"引數錯誤");

    private int code;
    private String msg;

    ExceptionDesception(int code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}
2.3定義異常處理
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler({WebApiException.class})
    @ResponseBody
    public Object expHandler(WebApiException e) {
        return createResult(e);
    }

    public JSONObject createResult(BaseException e) {
        return createResult(e.getCode(), e.getMessage());
    }

    public JSONObject createResult(int code, String msg) {
        JSONObject result = new JSONObject();
        result.put("code", code);
        result.put("msg", msg);
        return result;
    }

    @ExceptionHandler({ParamInvalidException.class})
    @ResponseBody
    public Object expValidHandler(ParamInvalidException e) {
        return createResult(e);
    }

}

3.定義校驗規則
public class ValidationUtils {

    private static final Validator VALIDATOR;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        VALIDATOR = factory.getValidator();
    }

    private ValidationUtils() {
    }

    public static <T> void validate(T entity, Class<?>... groups) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(entity, groups);
        if (constraintViolations.isEmpty()) {
            return;
        }
        ConstraintViolation<T> first = constraintViolations.iterator().next();
        throw new ParamInvalidException(ExceptionDesception.PARAM_INVALID.getCode(),first.getMessage());
    }

}
4.編寫測試controller
@Controller
@RequestMapping("h1")
public class TestController {

    @RequestMapping(value = "h2")
    public @ResponseBody
    Object testHeaderContext(@RequestBody Pet pet) {
        ValidationUtils.validate(pet);
        return pet.getName();
    }
}