1. Overview
Spring 5 brought a new PathPatternParser for parsing URI template patterns*.* This 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 givenHandlerMethod_whenMultipleURIVariablePattern_then200() {
client.get()
.uri("/spring5/baeldung/tutorial")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/baeldung/tutorial");
client.get()
.uri("/spring5/baeldung")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/baeldung");
}
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"))));
}
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 givenRouter_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, we’ll need to write a similar path pattern as 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 the 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 givenResources_whenAccess_thenGot()
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 givenRouter_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: “/baeldung/*Id”, this will match path patterns like:”/baeldung/Id”, “/baeldung/tutorialId”, “/baeldung/articleId”, etc:
private RouterFunction<ServerResponse> routingFunction() {
returnroute(
GET("/baeldung/*Id"),
serverRequest -> ok().body(fromValue("/baeldung/*Id path was accessed"))); }
@Test
public void givenRouter_whenGetMultipleCharWildcard_thenGotPathPattern()
throws Exception {
client.get()
.uri("/baeldung/tutorialId")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("/baeldung/*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 givenRouter_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. ‘{baeldung:[a-z]+}’ Regex in Path Variable
We can also specify a regex for the value of the path variable. So if our pattern is like “/{baeldung:[a-z]+}”, the value of the path variable “baeldung” will be any path segment that matches the given regex:
private RouterFunction<ServerResponse> routingFunction() {
return route(GET("/{baeldung:[a-z]+}"),
serverRequest -> ok()
.body(fromValue("/{baeldung:[a-z]+} was accessed and "
+ "baeldung=" + serverRequest.pathVariable("baeldung"))));
}
@Test
public void givenRouter_whenGetRegexInPathVarible_thenGotPathVariable()
throws Exception {
client.get()
.uri("/abcd")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("/{baeldung:[a-z]+} was accessed and "
+ "baeldung=abcd");
}
3.5. ‘/{var1}_{var2}’ Multiple Path Variables in Same Path Segment
Spring 5 ensured that multiple path variables would only be allowed in a single path segment 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 givenRouter_whenGetMultiplePathVaribleInSameSegment_thenGotPathVariables()
throws Exception {
client.get()
.uri("/baeldung_tutorial")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("baeldung , 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 on GitHub.