验证码验证器; hibernate自定义验证器中的客户端IP地址?

时间:2013-11-24 14:26:32

标签: java bean-validation hibernate-validator

我正在尝试使用hibernate验证器验证验证码(recaptcha),我已经编写了注释:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CaptchaCheckValidator.class)
@Documented
public @interface CaptchaCheck {
    String message() default "{constraints.captchacheck}";

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

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

    /**
     * @return The first field
     */
    String challenge();

    /**
     * @return The second field
     */
    String response();

    /**
     * Defines several <code>@FieldMatch</code> annotations on the same element
     * 
     * @see FieldMatch
     */
    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        FieldMatch[] value();
    }
}

我的验证员:

public class CaptchaCheckValidator implements ConstraintValidator<CaptchaCheck, Object> {
    private String challengeFieldName;
    private String responseFieldName;

    @Override
    public void initialize(final CaptchaCheck constraintAnnotation) {
        challengeFieldName = constraintAnnotation.challenge();
        responseFieldName = constraintAnnotation.response();
    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context) {
        try {
            final String challenge = BeanUtils.getProperty(value, challengeFieldName);
            final String response = BeanUtils.getProperty(value, responseFieldName);

checkAnswer(ip, callenge, response);

问题出在呼叫checkAnswer:

http://recaptcha4j.googlecode.com/svn-history/r3/trunk/apidocs/net/tanesha/recaptcha/ReCaptchaImpl.html#checkAnswer%28java.lang.String,%20java.lang.String,%20java.lang.String%29

这个需要第一个参数作为远程IP地址。但是在我的验证器中,我似乎无法访问HttpServletRequest对象。

如何在验证器中获取客户端的IP地址?或者有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

使用Bean Validation 1.1时,您可以创建一个CDI bean,它提供对servlet请求对象的访问,并将此bean注入验证器。此外,当对Spring使用Bean Validation时,支持依赖注入约束验证器,这在这里应该是有用的。