JSR303 参数校验 自定义注解

1.导入spring boot 相关的jar包

 <!--jsr 303 参数校验框架-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-data-starter-validation</artifactId>
 </dependency>

2.在controller里接受的参数上加@valid注解

@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/tologin")
    @ResponseBody
    public Result tologin(@Valid LoginVo loginVo){
        Result result = loginService.toLogin(loginVo);
        return result;
    }

}

3. LoginVo 实体类

@Data
public class LoginVo {
    @NotNull
    @IsMobile //自定义注解
    private String telephone;
    @NotNull
    @length(min=12)  //长度最小为12    
    private String password;
}

4.自定义注解实现

(1)增加IsMobile注解

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { IsMobileValidate.class})  //此处填写注解的实现
public @interface IsMobile {

    //是否必填,此处为true,必填
    boolean required() default true;

    //校验不通过的提示信息
    String message() default "手机号码格式有误";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

  (2)IsMobileValidate 类   此类需要实现ConstraintValidator接口

public class IsMobileValidate implements ConstraintValidator<IsMobile,String> {  //IsMobile :注解名字  String :返回值类型

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required(); //获取是否必填的true 或 false
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(required){
            return ValidateUtil.IsMobile(value);  //正则验证
        } else {
            if(StringUtils.isEmpty(value)){
                return true;
            } else {
                return ValidateUtil.IsMobile(value);  //正则验证
            }
        }
    }
}

5. 正则验证 

/**
* 正则验证工具类
*/
public
class ValidateUtil {    //验证是否为手机号码 public static boolean IsMobile(String telephone){ String regin = "1\\d{10}"; Pattern pattern = Pattern.compile(regin); Matcher matcher = pattern.matcher(telephone); return matcher.matches(); } }

6.异常捕获

@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobeExceptionHandle {

    @ExceptionHandler
    public Result<String> exceptionHandle(HttpServletRequest request ,Exception e){

        if(e instanceof BindException){
            BindException ex = (BindException) e;
            List<ObjectError> exceptionList= ex.getAllErrors();
            String message = exceptionList.get(0).getDefaultMessage();
            return Result.error(ExceptionEnum.VALITDATE_ERROR.getCode(),message);
        } else {
            return Result.error(ExceptionEnum.PROCESS_ERROR);
        }
    }

}

 

posted @ 2018-08-18 19:30  qqq齐  阅读(121)  评论(0)    收藏  举报