Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Exploring the Spring 5 MVC URL Matching Improvements

$
0
0

1. Overview

Spring 5 will bring 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 will go through the new/updated URL pattern matchers introduced in Spring 5.0 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 M5 release added a very easy to use URI variable syntax: {*foo} to capture any number of path segments at the end of the pattern.

Keep in mind that this pattern will be available to use with handler methods, starting with Spring 5.0 RC2.

We would need the Spring v5.0.0.RC2 version for this new URL pattern to work. This can be used along with SpringBoot v2.0.0.M2, by just overriding the spring.version property in pom.xml:

<spring.version>5.0.0.RC2</spring.version>

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/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(fromObject(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(fromObject("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 : “/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(fromObject("/baeldung/*Id path was accessed"))); }

@Test
public void 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 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 path variable. So if our pattern is like “/{baeldung:[a-z]+}”, the value of path variable “baeldung” will be any path segment that matches the gives regex:

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

@Test
public void 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 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(fromObject( serverRequest.pathVariable("var1") + " , " 
        + serverRequest.pathVariable("var2"))));
 }

@Test
public void 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 pattern matchers in Spring5, as well as the ones that are available from older versions of Spring. Here is the PathPattern documentation of Spring5 which lists these patterns in brief.

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


Viewing all articles
Browse latest Browse all 4535

Trending Articles