2020-07-01

Spring PathPattern Example

That lead to the creation of the parsed PathPattern matched against the parsed PathContainer representing the URL path.

Patterns are parsed on startup and re-used at runtime for efficient URL matching. How much more efficient? It’s hard to give numbers without a concrete use case but our jmh benchmark shows 6-8 times the throughput and 30-40% reduction in allocation rate. You can tailor the benchmark to get numbers that are more accurate for your application.

PathPattern is compatible with AntPathMatcher syntax except for the following:



  • Support for additional syntax to match and capture 0 or more path segments at the end, e.g. "{*spring}". This is useful as a catch-all pattern in REST APIs with access to the captured path segments through a @PathVariable.
  • Support for "**" for multi-segment matching is only allowed at the end of a pattern. This helps to eliminate most causes of ambiguity when choosing the closest match for a given request.
  • PathContainer helps to address the remaining issues. For example it never decodes the full path but rather breaks it down and decodes path segments individually, also removing path parameters, with the resulting decoded and normalized values matched one at a time. Therefore encoded "/" and ";" cannot alter the structure of the path, and path parameters can still be kept available. That means there is no need to configure how the request path is parsed and there are no trade-offs to consider.

Spring MVC and PathPattern

Starting in Spring Framework 5.3 the use of PathPattern is supported in Spring MVC with all HandlerMapping implementations exposing a property to set a PathPatternParser as an alternative to using AntPathMatcher. The easiest way to enable this is to configure a PathPatternParser in the path matching options of the MVC config.
In turn if the DispatcherServlet detects any HandlerMapping with parsed patterns enabled, it parses the URL path at runtime and makes it available under a well-known request attribute. The same can also be done earlier with ServletRequestPathFilter in which case the DispatcherServlet will refrain from parsing it.

No comments:

Post a Comment