有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java验证请求正文不等于模式

在验证请求参数时,我正在进行非空检查,但现在我想阻止某些类型的模式

@Prototype
public class MyObj {
    @NotBlank(message="Error: id cannot be null")
    @JsonProperty("id")
    private String id;
}

现在我必须阻止id与以下任何模式匹配的请求

(\*\s+(\w+)\s+\*)

((\w+)\:(\d+)\/(\d+))

我知道我可以包含一个@Pattern(regexp = 来允许特定的模式,但不确定如何阻止特定的模式。还可以执行多个模式验证


共 (2) 个答案

  1. # 1 楼答案

    您可以在@Pattern注释中使用negative lookahead来排除两个指定的模式

    ^(?!(\*\s+(\w+)\s+\*)$)(?!((\w+)\:(\d+)\/(\d+))$).*
    
  2. # 2 楼答案

    如果您仍然计划通过注释来实现,您可以创建自己的注释。 此处使用micronaut作为样本:

    
    @Prototype
    public class MyObj {
        @NotAllowedPattern(values={onePattern, secondPattern})
        @JsonProperty("id")
        private String id;
    }
    
    
    
    @Singleton
    ConstraintValidator<NotAllowedPattern, String> notAllowedPattern() {
       return (value, annotationMetadata, context) -> {
      
          // patterns should be mandatory as per annotation
          Optional<String[]> annotationPatterns = annotationMetadata.stringValue("values");
          String[] patterns = annotationPatterns.get();
    
          // if a single pattern from the not allowed matches this should return false 
          // and raise a <code>ConstraintViolationException</code> which results into error message.
          return doesNotMatchAllPatterns(value, patterns);
       };
    }