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();
    }
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值