configurePathMatch:
**
/**
* Helps with configuring HandlerMappings path matching options such as trailing slash match,
* suffix registration, path matcher and path helper.
* Configured path matcher and path helper instances are shared for:
* <ul>
* <li>RequestMappings</li>
* <li>ViewControllerMappings</li>
* <li>ResourcesMappings</li>
* </ul>
* @since 4.0.3
*/
default void configurePathMatch(PathMatchConfigurer configurer) {
}
该方法可以人为改变request的url和handler的映射关系。一般的,我们都是通过@Requestmapping注解来定义映射,这种定义的方式,是静态的。而这个方法可以动态的定义或改变映射关系,下面我们看如下代码:
public void configurePathMatch(PathMatchConfigurer configurer) {
// 是否存在尾\\来进行匹配 /user和/user/等效的,同样可以进行匹配
configurer.setUseTrailingSlashMatch(true);
// 这个配置需要传入一个UrlPathHelper对象,UrlPathHelper是一个处理url地址的帮助类,
// 他里面有一些优化url的方法
// 比如:getSanitizedPath,就是将// 换成/ 所以我们在输入地址栏的时候,//也是没有问题的,
// 这里使用springmvc默认的就可以了,如果想要深入了解,那么我们后续在深入
UrlPathHelper urlPathHelper = new UrlPathHelper();
configurer.setUrlPathHelper(urlPathHelper);
// 路径匹配器 PathMatcher是一个接口,springmvc默认使用的是AntPathMatcher
// 这里也就不深入了,使用springmvc默认的就可以,如果想要深入了解,那么我们后续在深入,查看AntPathMatcher的源码
// configurer.setPathMatcher();
// 配置路径前缀
// 下面这样写的意思是:对含有AdminController注解的controller添加/admin地址前缀
configurer.addPathPrefix("admin", c -> c.isAnnotationPresent(AdminController.class));
configurer.addPathPrefix("app", c -> c.isAnnotationPresent(AppController.class));
// 当然这里也不一定非得用注解来实现:也可以用分包:
// configurer.addPathPrefix("app", c -> c.getPackage().getName().contains("com.osy.controller.admin"));
// configurer.addPathPrefix("app", c -> c.getPackage().getName().contains("com.osy.controller.app"));
}


本文介绍如何使用 Spring MVC 中的 configurePathMatch 方法来动态地调整 URL 和 Handler 的映射关系。此方法允许开发者设定尾斜杠匹配、路径前缀及使用特定的路径帮助器,从而更灵活地管理应用的路由。
3316

被折叠的 条评论
为什么被折叠?



