Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate validator 为什么方法验证不能与自定义Hibernate验证程序注释一起使用?_Hibernate Validator - Fatal编程技术网

Hibernate validator 为什么方法验证不能与自定义Hibernate验证程序注释一起使用?

Hibernate validator 为什么方法验证不能与自定义Hibernate验证程序注释一起使用?,hibernate-validator,Hibernate Validator,我正在试验Hibernate Validator的方法验证 我已经编写了我能想象到的最简单的EJB,并对其上的约束进行了注释 但是,它不适用于我的自定义注释 public String checkString(@NotNull @NotBlank @Characters(invalidCharacters = { '1' }) String string); 最后一个注释检查字符串是否包含字符集的某些字符(默认值)以及是否为自定义约束。这在正常的验证器环境中工作 然而,在我的测试中,只有标准注

我正在试验Hibernate Validator的方法验证

我已经编写了我能想象到的最简单的EJB,并对其上的约束进行了注释

但是,它不适用于我的自定义注释

public String checkString(@NotNull @NotBlank @Characters(invalidCharacters = { '1' }) String string);
最后一个注释检查字符串是否包含字符集的某些字符(默认值)以及是否为自定义约束。这在正常的验证器环境中工作

然而,在我的测试中,只有标准注释起作用,而我的自定义注释不起作用

  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();
  }
}
/**
*检查字符串是否仅包含给定字符集中的字符。请注意,这将设置一个参数
*{@code positions}使用逗号分隔的无效字符位置列表(基于1,而不是0!)。
*/
@记录
@保留(RetentionPolicy.RUNTIME)
@目标({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD,ElementType.ANNOTATION_TYPE})
@约束(validatedBy=CharactersCheck.class)
公共@接口字符{
/**
*错误消息的I18N键。
*/
公共静态最终字符串I18N_KEY=“ipi.msg.validation.characters”;
/**
*错误消息。
*/
字符串消息()默认左括号+I18N键+右括号;
/**
*关联的冲突组。
*/
类[]组()默认值{};
/**
*有效载荷。
*/

类您可以发布自定义约束(注释和验证程序实现)的代码吗?另外,您的自定义约束是否被调用?还是被完全忽略?日志文件中的任何内容?您使用的是哪个版本的Hibernate Validator?自定义约束被完全忽略。我使用的是Hibernate Validator 4.2-您指的是什么日志文件?如果您指的是JBoss服务器日志:我可以找到MethodConst的堆栈跟踪因为我记录了它,所以这里没有ViolationException。但这只是在我使用标准约束时。
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, ", "));
    }
  }
}
/**
 * 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);
}