@Constraint、@RestControllerAdvice、@InitBinder、@ExceptionHandler使用

实体类User:

@Getter
@Setter
public class User {

    private Integer id;

    @NotNull(message = "age 必须是数字且不能为空")
    private Integer age;

    private String addr;

    private String name;

    @Name
    private String codeName;

    private String phone;

    private double price;

    private Integer lock;

    private Integer status;

    private Date ctdate;
}

验证类:CtdateValidator:

/**
 * 用于验证@InitBinder中的 binder.addValidators方法
 */
public class CtdateValidator implements Validator {
    @Override
    public boolean supports(Class aClass) {
        return aClass.equals(User.class);
    }

    @Override
    public void validate(Object o, Errors errors) {
        User userDto=(User)o;
        Date date = new Date();
        if( userDto.getCtdate().getTime() > date.getTime()){
            throw new  RuntimeException("Ctdate : 用户传入日期不能大于当前日期");
        }
    }
}

验证注解和注解实现类:Name和NameValidator

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = NameValidator.class)
@Documented
public @interface Name {

    String message() default "格式不正确";

    Class[] groups() default { };

    Class[] payload() default { };
}

public class NameValidator implements ConstraintValidator {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(value == null){
            return true;
        }
        return value.matches("^[a-zA-Z0-9]+[a-zA-Z0-9\\-]*$");
    }
}

@RestControllerAdvice注解的类  @InitBinder   @ExceptionHandler

/**
 * 

* RestControllerAdvice适用于所有@RequestMapping * 1.@InitBinder自定义验证类 * 2.@ModelAttribute * 3.@ExceptionHandler 根据exception类型捕获各种异常 *

*/ @RestControllerAdvice @Slf4j public class GobalExceptionHandler { /** * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 * 1.追加转换器 * 2.追加校验器 * @param binder */ @InitBinder public void initBinder(WebDataBinder binder){ //统一日期处理 binder.addCustomFormatter( new DateFormatter("yyyy年mm月dd日")); //统一处理特定类里面的特定字段,user->ctdate binder.addValidators(new CtdateValidator()); } /** * 捕获所有的异常,并返回异常信息 * @param exception * @return */ @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //非必选 public Reply exceptionHanlder(Exception exception){ return new Reply<>().builder().code(110).msg(exception.getMessage()).build(); } /** * 捕获特定的异常,并处理 * @param exception * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //非必选 public Reply bindExceptionErrorHandler(MethodArgumentNotValidException exception){ List fieldErrors = exception.getBindingResult().getFieldErrors(); if(!CollectionUtils.isEmpty(fieldErrors)){ String filedName = fieldErrors.get(0).getField(); String errMsg = filedName + ": " + fieldErrors.get(0).getDefaultMessage(); return new Reply<>().builder().code(110).msg(errMsg).build(); } return new Reply<>().builder().code(110).msg(exception.getMessage()).build(); } }

controller类调用验证:

@RequestMapping("/test")
@RestController
public class Test {

    @PostMapping(value = "")
    public  Reply test(@Valid @RequestBody User user) {
        System.out.println(JSONObject.toJSONString(user));
        return new Reply(user);
    }
}

Reply工具类:

@Builder
@ToString
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Reply implements Serializable {

    @Getter
    @Setter
    private Integer code = 0;

    @Getter
    @Setter
    private String msg ="ok";


    @Getter
    @Setter
    private T data;

    public Reply(T data) {
        this.data = data;
    }

    public Reply(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

 

你可能感兴趣的:(java)