Exploring the Spring 5 WebFlux URL Matching

1. Overview

Spring 5 brought a new PathPatternParser for parsing URI template patternsThis is an alternative to the previously used AntPathMatcher.

The AntPathMatcher was an implementation of Ant-style path pattern matching. PathPatternParser breaks the path into a linked list of PathElements. This chain of PathElements is taken by the PathPattern class for quick matching of patterns.

With the PathPatternParser, support for a new URI variable syntax was also introduced.

In this article, we’ll go through the new/updated URL pattern matchers introduced in Spring 5.0 WebFlux and also the ones that have been there since older versions of Spring.

2. New URL Pattern Matchers in Spring 5.0

The Spring 5.0 release added a very easy to use URI variable syntax: {*foo} to capture any number of path segments at the end of the pattern.

2.1. URI Variable Syntax {*foo} Using a Handler Method

Let’s see an example of the URI variable pattern {*foo} another example using @GetMapping and a handler method. Whatever we give in the path after “/spring5” will be stored in the path variable “id”:

@GetMapping("/spring5/{*id}")
public String URIVariableHandler(@PathVariable String id) {
    return id;
}
@Test
public void whenMultipleURIVariablePattern_thenGotPathVariable() {
        
    client.get()
      .uri("/spring5/maixuanviet/tutorial")
      .exchange()
      .expectStatus()
      .is2xxSuccessful()
      .expectBody()
      .equals("/maixuanviet/tutorial");

    client.get()
      .uri("/spring5/maixuanviet")
      .exchange()
      .expectStatus()
      .is2xxSuccessful()
      .expectBody()
      .equals("/maixuanviet");
}

2.2. URI Variable Syntax {*foo} Using RouterFunction

Let’s see an example of the new URI variable path pattern using RouterFunction:

private RouterFunction<ServerResponse> routingFunction() {
    return route(GET("/test/{*id}"), 
      serverRequest -> ok().body(fromValue(serverRequest.pathVariable("id"))));
}

In this case, whatever path we write after “/test” will be captured in the path variable “id”. So the test case for it could be:

@Test
public void whenMultipleURIVariablePattern_thenGotPathVariable() 
  throws Exception {
 
    client.get()
      .uri("/test/ab/cd")
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody(String.class)
      .isEqualTo("/ab/cd");
}

2.3. Use of URI Variable Syntax {*foo} to Access Resources

If we want to access resources, then we’ll need to write the similar path pattern as we wrote in the previous example.

So let’s say our pattern is: “/files/{*filepaths}”. In this case, if the path is /files/hello.txt, the value of path variable “filepaths” will be “/hello.txt”, whereas, if the path is /files/test/test.txt, the value of “filepaths” = “/test/test.txt”.

Our routing function for accessing file resources under the /files/ directory:

private RouterFunction<ServerResponse> routingFunction() { 
    return RouterFunctions.resources(
      "/files/{*filepaths}", 
      new ClassPathResource("files/"))); 
}

Let’s assume that our text files hello.txt and test.txt contain “hello” and “test” respectively. This can be demonstrated with a JUnit test case:

@Test 
public void whenMultipleURIVariablePattern_thenGotPathVariable() 
  throws Exception { 
      client.get() 
        .uri("/files/test/test.txt") 
        .exchange() 
        .expectStatus() 
        .isOk() 
        .expectBody(String.class) 
        .isEqualTo("test");
 
      client.get() 
        .uri("/files/hello.txt") 
        .exchange() 
        .expectStatus() 
        .isOk() 
        .expectBody(String.class) 
        .isEqualTo("hello"); 
}

3. Existing URL Patterns from Previous Versions

Let’s now take a peek into all the other URL pattern matchers that have been supported by older versions of Spring. All these patterns work with both RouterFunction and Handler methods with @GetMapping.

3.1. ‘?’ Matches Exactly One Character

If we specify the path pattern as: “/t?st“, this will match paths like: “/test” and “/tast”, but not “/tst” and “/teest”.

The example code using RouterFunction and its JUnit test case:

private RouterFunction<ServerResponse> routingFunction() { 
    return route(GET("/t?st"), 
      serverRequest -> ok().body(fromValue("Path /t?st is accessed"))); 
}

@Test
public void whenGetPathWithSingleCharWildcard_thenGotPathPattern()   
  throws Exception {
 
      client.get()
        .uri("/test")
        .exchange()
        .expectStatus()
        .isOk()
        .expectBody(String.class)
        .isEqualTo("Path /t?st is accessed");
}

3.2. ‘*’ Matches 0 or More Characters Within a Path Segment

If we specify the path pattern as : “/maixuanviet/*Id”, this will match path patterns like:”/maixuanviet/Id”, “/maixuanviet/tutorialId”, “/maixuanviet/articleId”, etc:

private RouterFunction<ServerResponse> routingFunction() { 
    returnroute(
      GET("/maixuanviet/*Id"), 
      serverRequest -> ok().body(fromValue("/maixuanviet/*Id path was accessed"))); }

@Test
public void whenGetMultipleCharWildcard_thenGotPathPattern() 
  throws Exception {
      client.get()
        .uri("/maixuanviet/tutorialId")
        .exchange()
        .expectStatus()
        .isOk()
        .expectBody(String.class)
        .isEqualTo("/maixuanviet/*Id path was accessed");
}

3.3. ‘**’ Matches 0 or More Path Segments Until the End of the Path

In this case, the pattern matching is not limited to a single path segment. If we specify the pattern as “/resources/**”, it will match all paths to any number of path segments after “/resources/”:

private RouterFunction<ServerResponse> routingFunction() { 
    return RouterFunctions.resources(
      "/resources/**", 
      new ClassPathResource("resources/"))); 
}

@Test
public void whenAccess_thenGot() throws Exception {
    client.get()
      .uri("/resources/test/test.txt")
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody(String.class)
      .isEqualTo("content of file test.txt");
}

3.4. ‘{maixuanviet:[a-z]+}’ Regex in Path Variable

We can also specify a regex for the value of path variable. So if our pattern is like “/{maixuanviet:[a-z]+}”, the value of path variable “maixuanviet” will be any path segment that matches the gives regex:

private RouterFunction<ServerResponse> routingFunction() { 
    return route(GET("/{maixuanviet:[a-z]+}"), 
      serverRequest ->  ok()
        .body(fromValue("/{maixuanviet:[a-z]+} was accessed and "
        + "maixuanviet=" + serverRequest.pathVariable("maixuanviet")))); 
}

@Test
public void whenGetRegexInPathVarible_thenGotPathVariable() 
  throws Exception {
 
      client.get()
        .uri("/abcd")
        .exchange()
        .expectStatus()
        .isOk()
        .expectBody(String.class)
        .isEqualTo("/{maixuanviet:[a-z]+} was accessed and "
          + "maixuanviet=abcd");
}

Spring 5 made sure that multiple path variables will be allowed in a single path segment only when separated by a delimiter. Only then can Spring distinguish between the two different path variables:

private RouterFunction<ServerResponse> routingFunction() { 
 
    return route(
      GET("/{var1}_{var2}"),
      serverRequest -> ok()
        .body(fromValue( serverRequest.pathVariable("var1") + " , " 
        + serverRequest.pathVariable("var2"))));
 }

@Test
public void whenGetMultiplePathVaribleInSameSegment_thenGotPathVariables() 
  throws Exception {
      client.get()
        .uri("/maixuanviet_tutorial")
        .exchange()
        .expectStatus()
        .isOk()
        .expectBody(String.class)
        .isEqualTo("maixuanviet , tutorial");
}

4. Conclusion

In this article, we went through the new URL matchers in Spring 5, as well as the ones that are available in older versions of Spring.

As always, the implementation of all the examples we discussed can be found over on GitHub.