Validator

简要描述:

  • 请求参数校验,在校验规则较复杂,无法通过@NotNull 等简单校验方式时,可以利用此方式将校验与具体业务逻辑切割

example1:

 biz-ins-MiniApp项目中,对于所有请求,如果用户一定要实名后才能访问接口,这时有两种方式:
    1.利用spring-security,对请求uri进行区分校验
    2.利用argumentResorver,在参数解析时如果接口需要user属性并且添加@Valid特定自定义注解时进行校验


1.实现自定义校验器:
public class MemberIdValidator implements Validator {

    @Override
    public boolean supports(Class clazz) {
        return WebAuthUser.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        if (target != null) {
            WebAuthUser user = (WebAuthUser) target;
            if (StringUtil.isBlank(user.getMemberId())) {
                errors.reject("0003", "memberId not found");
            }
        } else {
            errors.reject("0003", "memberId not found");
        }

    }

}

2-1.方式1:在ArgumentResolver中初始化校验器
public class WebAuthUserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return WebAuthUser.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        WebAuthUser user = (WebAuthUser) webRequest.getAttribute(ReqAttributes.USER_INFO,
                RequestAttributes.SCOPE_REQUEST);
        final String name = Conventions.getVariableNameForParameter(parameter);
        WebDataBinder binder = binderFactory.createBinder(webRequest, user, name);
        binder.addValidators(new MemberIdValidator());
        if (user != null) {
            WebUtils.validate(binder, parameter);
        }
        mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
        return user;
    }

}

2-2.方式2:在具体controller中初始化校验器
@InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        // 添加一个日期类型编辑器,也就是需要日期类型的时候,怎么把字符串转化为日期类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        dataBinder.registerCustomEditor(String.class, new EmptyStrConverter());
        
        dataBinder.addValidators(new MemberIdValidator());
        
    }

你可能感兴趣的:(Validator)