【发布时间】:2013-11-25 16:11:14
【问题描述】:
我正在尝试使用休眠验证器验证验证码(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:
这需要一个远程IP地址作为第一个参数。但在我的验证器中,我似乎无法访问 HttpServletRequest 对象。
如何在验证器中获取客户端的 IP 地址?或者有没有更好的方法来实现这一点?
【问题讨论】:
标签: java bean-validation hibernate-validator