使用蚂蚁模式匹配路径变量
Using ant patterns to match on path variable
我有几个不同的控制器,配置了如下端点。其中 {id}
是一个数字 @PathVariable
.
@RequestMapping(value = "/noun1/noun2/{id}/verb1")
@RequestMapping(value = "/noun1/noun2/{id}/verb2")
@RequestMapping(value = "/noun1/noun2/{id}/verb3/verb4")
@RequestMapping(value = "/noun1/noun2/noun3/verb5")
使用 HttpSecurity
,我想围绕所有具有 {id}
的端点实施安全性。所以我创建了一个这样的蚂蚁模式:
"/noun1/noun2/{id}/**"
蚂蚁模式在端点上正确匹配 {id}
。但是,蚂蚁模式也在最后一个端点匹配,设置 id = noun3
。蚂蚁模式有没有办法只匹配包含 {id}
?
的端点
你的蚂蚁模式应该如何取决于{id}
可以是什么。蚂蚁匹配器中的 {id}
与 RequestMapping
注释中的 {id}
没有直接关系。
Spring 安全性只是使用 ant 匹配器检查路径是否与提供的模式匹配。在你的情况下 {id}
匹配任何字符串并将匹配的值存储在名为 id
的 URI template variable
中供以后使用。
要指定被视为 {id}
的内容,您可以提供正则表达式。如果您的 ID 由数字组成,您的匹配器可能是 "/noun1/noun2/{regex:\d+}/**"
:
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.util.AntPathMatcher;
class AntMatcherTest {
@Test
void antMatcher() {
AntPathMatcher antPathMatcher = new AntPathMatcher();
String pattern = "/noun1/noun2/{id:\d+}/**";
assertFalse(antPathMatcher.match(pattern, "/noun1/noun2/noun3/verb5"));
assertTrue(antPathMatcher.match(pattern, "/noun1/noun2/1/verb1"));
assertTrue(antPathMatcher.match(pattern, "/noun1/noun2/2/verb2"));
assertTrue(antPathMatcher.match(pattern, "/noun1/noun2/3/verb3/verb4"));
}
}
我有几个不同的控制器,配置了如下端点。其中 {id}
是一个数字 @PathVariable
.
@RequestMapping(value = "/noun1/noun2/{id}/verb1")
@RequestMapping(value = "/noun1/noun2/{id}/verb2")
@RequestMapping(value = "/noun1/noun2/{id}/verb3/verb4")
@RequestMapping(value = "/noun1/noun2/noun3/verb5")
使用 HttpSecurity
,我想围绕所有具有 {id}
的端点实施安全性。所以我创建了一个这样的蚂蚁模式:
"/noun1/noun2/{id}/**"
蚂蚁模式在端点上正确匹配 {id}
。但是,蚂蚁模式也在最后一个端点匹配,设置 id = noun3
。蚂蚁模式有没有办法只匹配包含 {id}
?
你的蚂蚁模式应该如何取决于{id}
可以是什么。蚂蚁匹配器中的 {id}
与 RequestMapping
注释中的 {id}
没有直接关系。
Spring 安全性只是使用 ant 匹配器检查路径是否与提供的模式匹配。在你的情况下 {id}
匹配任何字符串并将匹配的值存储在名为 id
的 URI template variable
中供以后使用。
要指定被视为 {id}
的内容,您可以提供正则表达式。如果您的 ID 由数字组成,您的匹配器可能是 "/noun1/noun2/{regex:\d+}/**"
:
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.util.AntPathMatcher;
class AntMatcherTest {
@Test
void antMatcher() {
AntPathMatcher antPathMatcher = new AntPathMatcher();
String pattern = "/noun1/noun2/{id:\d+}/**";
assertFalse(antPathMatcher.match(pattern, "/noun1/noun2/noun3/verb5"));
assertTrue(antPathMatcher.match(pattern, "/noun1/noun2/1/verb1"));
assertTrue(antPathMatcher.match(pattern, "/noun1/noun2/2/verb2"));
assertTrue(antPathMatcher.match(pattern, "/noun1/noun2/3/verb3/verb4"));
}
}