Spring对对象属性的校验

来源:互联网 发布:js正则匹配字符串 编辑:程序博客网 时间:2024/05/21 21:41

场景:对对象的参数进行校验,如果不通过抛出异常

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定义异常处理

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









原创粉丝点击