我正在尝试使用Hibernate Validator的方法验证。
我编写了我能想象到的最简单的EJB,并在其上注释了约束。
但是,它不适用于我的自定义注释。
public String checkString(@NotNull @NotBlank @Characters(invalidCharacters = { '1' }) String string);
最后一个注释检查String是否包含字符集的某些字符(具有默认值)并且是自定义约束。这适用于普通的Validator环境。
但是在我的测试中,只有标准注释有效,我的自定义注释没有。
this.parameterValidation.checkString(null); // Throws Exception
this.parameterValidation.checkString(""); // Throws Exception
this.parameterValidation.checkString("123"); // Does NOT throw Exception - why?
我还测试了另一个自定义注释,并且它仍然处于非活动状态。
我做错了什么?
以下是自定义注释的代码:
/**
* Checks if a String contains only characters from the given character set. Note that this sets a parameter
* {@code positions} with a comma-separated list of the positions of invalid characters (based on 1, not 0!).
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Constraint(validatedBy = CharactersCheck.class)
public @interface Characters {
/**
* The I18N key of the error message.
*/
public static final String I18N_KEY = "ipi.msg.validation.characters";
/**
* Error message.
*/
String message() default LEFT_CURLY_BRACKET + I18N_KEY + RIGHT_CURLY_BRACKET;
/**
* The associated violation groups.
*/
Class<?>[] groups() default {};
/**
* The payload.
*/
Class<? extends Payload>[] payload() default {};
/**
* The character set to which the text must conform.
*/
CharacterSet characterSet() default CharacterSet.ISO_8859_15;
/**
* Additional characters which must not be found in the text.
*/
char[] invalidCharacters() default {};
/**
* If this is {@code true}, carriage returns and line feeds are allowed in the text, making it a multi-line text.
*/
boolean carriageReturnAllowed() default false;
/**
* Defines several {@link Characters} annotations on the same element.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@interface List {
/**
* The {@link Characters} annotations.
*/
Characters[] value();
}
}
以下是实施:
public class CharactersCheck implements ConstraintValidator<Characters, CharSequence>, MessageAttributeModifier {
/**
* The character set to check.
*/
private CharacterSet characterSet;
/**
* Additional invalid characters.
*/
private char[] invalidCharacters;
/**
* If this is {@code true}, carriage returns and line feeds are allowed in the text, making it a multi-line text.
*/
private boolean carriageReturnAllowed;
private SortedSet<Integer> invalidCharacterPositions;
/**
* {@inheritDoc}
*/
@Override
public void initialize(final Characters constraintAnnotation) {
this.characterSet = constraintAnnotation.characterSet();
this.carriageReturnAllowed = constraintAnnotation.carriageReturnAllowed();
if (this.carriageReturnAllowed) {
this.invalidCharacters = constraintAnnotation.invalidCharacters();
} else {
final int invalidCharactersLength = constraintAnnotation.invalidCharacters().length;
this.invalidCharacters = Arrays.copyOf(constraintAnnotation.invalidCharacters(), invalidCharactersLength + 2);
this.invalidCharacters[invalidCharactersLength] = '\r';
this.invalidCharacters[invalidCharactersLength + 1] = '\n';
}
this.invalidCharacterPositions = new TreeSet<>();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(final CharSequence value, final ConstraintValidatorContext context) {
if (value == null) {
return true;
} else {
setInvalidCharacterPositions(value);
return this.invalidCharacterPositions.isEmpty();
}
}
private void setInvalidCharacterPositions(final CharSequence value) {
this.invalidCharacterPositions = CharacterChecker.checkCharacters(String.valueOf(value), this.characterSet,
this.invalidCharacters);
}
/**
* {@inheritDoc}
*/
@Override
public void modifyAttributes(final Map<String, Object> attributes, final Context context) {
setInvalidCharacterPositions((CharSequence) context.getValidatedValue());
if (!this.invalidCharacterPositions.isEmpty()) {
attributes.put(MessageVariables.POSITIONS, StringUtils.join(this.invalidCharacterPositions, ", "));
}
}
}
请注意,我创建了一个自定义消息插补器,它允许检查将消息变量添加到给定的Map。为此,我在消息插补器中创建了一个新的检查实例,并使用此接口调用它:
/**
* Modifies attributes within a validation message.
*/
public interface MessageAttributeModifier {
/**
* Modifies the attributes within the validation message.
* @param attributes The existing attributes, which can be modified; the attributes already contain the values from
* the annotation and additionally also {@link MessageVariables#VALIDATED_VALUE}
* @param context The validation context
*/
public void modifyAttributes(Map<String, Object> attributes, final Context context);
}