Skip to content

路径匹配

在响应式栈中查看等效项

您可以自定义与路径匹配和 URL 处理相关的选项。有关各个选项的详细信息,请参阅 PathMatchConfigurer 的 Javadoc。

以下示例显示了如何自定义路径匹配:

java
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public void configurePathMatch(PathMatchConfigurer configurer) {
		configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));
	}

	private PathPatternParser patternParser() {
		PathPatternParser pathPatternParser = new PathPatternParser();
		// ...
		return pathPatternParser;
	}
}
kotlin
@Configuration
class WebConfiguration : WebMvcConfigurer {

	override fun configurePathMatch(configurer: PathMatchConfigurer) {
		configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController::class.java))
	}

	fun patternParser(): PathPatternParser {
		val pathPatternParser = PathPatternParser()
		//...
		return pathPatternParser
	}
}
xml
<mvc:annotation-driven>
	<mvc:path-matching
			path-helper="pathHelper"
			path-matcher="pathMatcher"/>
</mvc:annotation-driven>

<bean id="pathHelper" class="org.example.app.MyPathHelper"/>
<bean id="pathMatcher" class="org.example.app.MyPathMatcher"/>

补充教学

1. 统一路径前缀

configurer.addPathPrefix("/api", ...) 是一个非常有用的特性。它允许你通过代码批量为特定的控制器(如所有带 @RestController 注解的类)添加统一的 URL 前缀,避免在每个 @RequestMapping 里重复写 /api

2. PathPatternParser vs AntPathMatcher

  • PathPatternParser (新):更高效,专门为 Web 优化,支持更精确的语法。它是现代 Spring 应用的默认选择。
  • AntPathMatcher (旧):基于传统的 Ant 风格匹配,灵活性较高但性能稍逊,常用于复杂的权限校验场景。

3. 常见的自定义项

PathMatchConfigurer 中,你还可以控制是否匹配尾部斜杠(Trailing Slash)。例如,配置后可以决定请求 /users/users/ 是否视作同一个资源。

Based on Spring Framework.