Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write ant path pattern except one path?

Tags:

java

spring

ant

Spring Framework has the AntPathMatcher which is borrowed from Ant.

I have the following path:

  • /api/index
  • /api/test/random
  • /api/test/another
  • /api/other/1
  • /api/other/2

and I will add more paths like /api/other/other, I'd like to ask how can I create an AntPath Pattern to match all path except the /api/index.

I have tried to make some tests, but none of the following works.

  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);
  }
like image 806
einverne Avatar asked Oct 28 '25 13:10

einverne


1 Answers

As stated in the Spring AntPathMatcher Docu you can add a path variable to your pattern where you can specify a Regex this path variable has to match:

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

The above pattern for the path variable accepts any characters but the string "index". If you want to filter out any strings containing the substring "index" you could change it to:

    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;
like image 67
pero_hero Avatar answered Oct 31 '25 04:10

pero_hero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!