如何将JSR-303 / JSR-349 bean验证与自己的org.springframework.validation.Validator验证相结合?

时间:2015-10-04 10:12:53

标签: java spring validation

我需要手动进行验证(因为我需要使用a, a:hover { text-decoration:none; } ,因为这个解析器我不能在方法参数中使用HandlerMethodArgumentResolver)在POJO类中使用BindingResult中的自定义验证。请看我的代码。

控制器类

org.springframework.validation.Validator

POJO 类:

@RequestMapping(value = "/authorize", method = {RequestMethod.GET, RequestMethod.POST})
    public String authorize(@Valid AuthorizationRequest authorizationRequest) {

        // JSR-303/JSR-349 bean validation
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<AuthorizationRequest>> violations = validator.validate(authorizationRequest);

        // Own org.springframework.validation.Validator
        BindingResult result = new BeanPropertyBindingResult(authorizationRequest, "request");
        AuthorizationRequestValidator validator2 = new AuthorizationRequestValidator();
        validator2.validate(authorizationRequest, result);
}

public class AuthorizationRequest { @NotEmpty @JsonProperty("response_type") private String responseType; @NotEmpty @JsonProperty("client_id") private String clientId; @NotEmpty @JsonProperty("redirect_uri") private String redirectUri; //getter, setters omitted } 验证者

org.springframework.validation.Validator

问题

我想在同一时间进行两次验证,并在Spring中组合这两种验证的输出。有没有办法如何组合它或我必须手动完成它?

解析器类(仅供澄清):

@Component
public class AuthorizationRequestValidator implements Validator {

    private static Logger LOG = Logger.getLogger(AuthorizationRequestValidator.class);

    public boolean supports(Class clazz) {
        return AuthorizationRequest.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        AuthorizationRequest request = (AuthorizationRequest) obj;
        if ("foobar".equals(request.getClientId())) {
            e.rejectValue("clientId", "nomatch");
        }
    }

}

0 个答案:

没有答案