Java 验证码验证器;hibernate自定义验证程序中的客户端ip地址?

Java 验证码验证器;hibernate自定义验证程序中的客户端ip地址?,java,bean-validation,hibernate-validator,Java,Bean Validation,Hibernate Validator,我正在尝试使用hibernate validator验证验证码(recaptcha),我已经编写了注释: @Target({ TYPE, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = CaptchaCheckValidator.class) @Documented public @interface CaptchaCheck { String message() default "{constraints

我正在尝试使用hibernate validator验证验证码(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);
公共类CAPTCHACHECKVALIDATER实现ConstraintValidator{
私有字符串challengeFieldName;
私有字符串responseFieldName;
@凌驾
公共无效初始化(最终CaptchaCheck CONSTRAINTANOTATION){
challengeFieldName=ConstraintAnotation.challenge();
responseFieldName=ConstraintAnotation.response();
}
@凌驾
公共布尔值有效(最终对象值、最终约束验证或上下文上下文){
试一试{
最后一个字符串质询=BeanUtils.getProperty(值,challengeFieldName);
最终字符串响应=BeanUtils.getProperty(值,responseFieldName);
检查应答(ip、呼叫、应答);
问题在于呼叫检查应答:

这个参数需要一个远程ip地址作为第一个参数,但在我的验证器中,我似乎没有访问HttpServletRequest对象的权限


如何在我的验证器中获取客户端的ip地址?或者是否有更好的方法来实现这一点?

在使用Bean Validation 1.1时,您可以创建一个CDI Bean,它提供对servlet请求对象的访问,并将此Bean注入验证器。另外,在使用Spring的Bean Validation时,还支持dependency注入到约束验证器中,这在这里应该很有帮助。

使用cdi bean框架插入httpservletrequest工作得很好。我正在使用tomcat 7的weld。配置有点困难,但一旦我在pom.xml中排除了javax.el,它就可以毫无问题地工作。现在我可以简单地使用@Inject httpservletrequest request、 获取请求对象。谢谢!