Skip to content
Advertisement

How to apply the PathPatternParser introduced in Spring 5?

I want to create a GET request that takes a filepath as a path variable.

As described in the Spring documentation found here, this should be possible by using the following: /resources/{*path}.

I am using Spring Boot 2.1.2 which uses Spring 5.

However when I set up my controller method like this, the request doesn’t match the route. An expected matching path would be for example /resources/some/filepath which should lead the PathVariable “path” to be /some/filepath

  @GetMapping("/resources/{*path}")
  public String content(@PathVariable String path) {
    return null;
  }

I didn’t find any information about any configuration that is needed in order to make use of the new PathPattern. The only other piece of information I found about this new feature is a post at Baeldung (https://www.baeldung.com/spring-5-mvc-url-matching) which doesn’t mention anything about configuration. So I expect that it should work out of the box, but it doesn’t.

I cloned the project mentioned in the Baeldung post. The corresponding unit tests run. When I copy the Controller method and the unit test to my project, it fails. So I expect that it has to do with configuration.

Thank you for any help.

Advertisement

Answer

In the Common Application properties in the Spring documentation there’s a property called spring.mvc.pathmatch.matching-strategy, that’s used as “Choice of strategy for matching request paths against registered mappings”.

The default value (up to this date) is ant-path-matcher, and since you want to use PathPattern, you’ll need to write this in the application.properties file:

spring.mvc.pathmatch.matching-strategy=path-pattern-parser

Advertisement