前言
由于没有在网上没有找到比较详细的 PathPattern
说明,于是一路查代码找到官方文档。
本文是官方文档的翻译文档,个人觉得还是写的比较清晰的,提供给大家参考,有助于精确的路径匹配。
中文文档
PathPattern使用以下规则匹配URL路径:
-
?匹配一个字符
-
*在一个路径段中匹配零个或多个字符
-
**匹配零个或多个路径段,直到路径结束
-
{spring}匹配一个路径段,并将其捕获为一个名为“spring”的变量
-
{spring:[a-z]+}匹配regexp [a-z]+作为名为“spring”的路径变量
-
{*spring}匹配零个或多个路径段,直到路径结束,并将其捕获为名为“spring”的变量
注意:与org.springframework.util.AntPathMatcher相比,**只支持在模式的末尾。
例如/pages/{**}是有效的,但是/pages/{**}/details是无效的。这同样适用于捕获变量{*spring}。目的是在比较模式的特异性时消除歧义。
例如
-
/pages/t?st.html -匹配/pages/test.html,也匹配/pages/tXst.html,但不匹配/pages/toast.html
-
/resources/*.png -匹配resources目录下所有的png文件
-
/resources/** -匹配/resources/路径下的所有文件,包括/resources/image.png和/resources/css/spring.css
-
/resources/{*path} -匹配/resources/和/resources下的所有文件,并在一个名为path的变量中捕获它们的相对路径;/resources/image.png将匹配path→/image.png, /resources/css/spring.css将匹配path→"/css/spring.css"
-
/resources/{filename:\w+}.dat将匹配/resources/spring.dat并将值"spring"赋给文件名变量
以下取自官方文档
Representation of a parsed path pattern. Includes a chain of path elements for fast matching and accumulates computed state for quick comparison of patterns.
PathPattern matches URL paths using the following rules:
- ? matches one character
- * matches zero or more characters within a path segment
- ** matches zero or more path segments until the end of the path
- {spring} matches a path segment and captures it as a variable named “spring”
- {spring:[a-z]+} matches the regexp [a-z]+ as a path variable named “spring”
- {*spring} matches zero or more path segments until the end of the path and captures it as a variable named “spring”
Note: In contrast to org.springframework.util.AntPathMatcher, ** is supported only at the end of a pattern. For example /pages/{} is valid but /pages/{}/details is not. The same applies also to the capturing variant {*spring}. The aim is to eliminate ambiguity when comparing patterns for specificity.
Examples
- /pages/t?st.html — matches /pages/test.html as well as /pages/tXst.html but not /pages/toast.html
- /resources/*.png — matches all .png files in the resources directory
- /resources/** — matches all files underneath the /resources/ path, including /resources/image.png and /resources/css/spring.css
- /resources/{*path} — matches all files underneath the /resources/, as well as /resources, and captures their relative path in a variable named “path”; /resources/image.png will match with “path” → “/image.png”, and /resources/css/spring.css will match with “path” → “/css/spring.css”
- /resources/{filename:\w+}.dat will match /resources/spring.dat and assign the value “spring” to the filename variable