【问题标题】:How to write ant path pattern except one path?除了一条路径,如何编写蚂蚁路径模式?
【发布时间】:2021-08-04 10:45:56
【问题描述】:

Spring Framework 的AntPathMatcher 是从 Ant 借来的。

我有以下路径:

  • /api/索引
  • /api/test/随机
  • /api/test/另一个
  • /api/other/1
  • /api/other/2

我将添加更多路径,例如/api/other/other,我想问一下如何创建一个 AntPath 模式来匹配除/api/index 之外的所有路径。

我已尝试进行一些测试,但以下都不起作用。

  private static final String PATTERN = "/api/*/**";

  @Test
  public void test() {
    AntPathMatcher pathMatcher = new AntPathMatcher();
    boolean match = pathMatcher.match(PATTERN, "/api/index");
    System.out.println(match);
    match = pathMatcher.match(PATTERN, "/api/test/test");
    System.out.println(match);
  }

【问题讨论】:

    标签: java spring ant


    【解决方案1】:

    Spring AntPathMatcher Docu 中所述,您可以将路径变量添加到您的模式中,您可以在其中指定此路径变量必须匹配的正则表达式:

        String PATTERN = "/api/{path:^(?!(index)$).*$}/**";
    

    path 变量的上述模式接受除字符串 "index" 之外的任何字符。如果要过滤掉包含子字符串"index" 的任何字符串,可以将其更改为:

        String PATTERN = "/api/{path:^(?!(index)).*$}/**";
    
    
        AntPathMatcher pathMatcher = new AntPathMatcher();
        boolean match = pathMatcher.match(PATTERN, "/api/index");
        assert match == false;
        match = pathMatcher.match(PATTERN, "/api/index/sec");
        assert match == false;
        match = pathMatcher.match(PATTERN, "/api/index4");
        assert match == false;
        match = pathMatcher.match(PATTERN, "/api/test/random");
        assert match == true;
        match = pathMatcher.match(PATTERN, "/api/test/another");
        assert match == true;
        match = pathMatcher.match(PATTERN, "/api/other/1");
        assert match == true;
        match = pathMatcher.match(PATTERN, "/api/other/2");
        assert match == true;
        match = pathMatcher.match(PATTERN, "/api/other/index");
        assert match == true;
    

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      相关资源
      最近更新 更多