Domanda

I'm trying to validate a captcha (recaptcha) using hibernate validator, i've written the annotation:

@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();
    }
}

My validator:

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);

The problem lies in the call 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

This one requires as first parameter a remote ip address. But in my validator i don't seem to have access to the HttpServletRequest object.

How can i get the ip address of the client in my validator? Or is there maybe a better way to accomplish this?

È stato utile?

Soluzione

When working with Bean Validation 1.1 you could create a CDI bean which provides access to the servlet request object and inject this bean into the validator. Also when using Bean Validation with Spring, there is support for dependency injection into constraint validators which should be helpful here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top