如何使用MvcUriComponentsBuilder生成带参数的命名路由URL?
解决Spring Boot命名路由生成带路径参数的URL问题
问题分析
你当前使用MvcUriComponentsBuilder.fromMappingName生成URL时,路径参数{token}无法被替换,核心原因是没有正确将参数值绑定到命名路由的参数模板中。
解决方案
方案1:通过withArgs()绑定参数
在fromMappingName之后调用withArgs()方法传入路径参数值,Spring会自动匹配并替换路由中的{token}占位符:
String url = MvcUriComponentsBuilder.fromMappingName("auth#passwordChange") .withArgs("token1234") .build() .toString();
方案2:使用方法引用(更直观)
通过fromMethodCall直接调用控制器方法的引用,Spring会自动解析方法参数并生成正确URL,无需依赖命名路由的字符串标识:
String url = MvcUriComponentsBuilder.fromMethodCall( MvcUriComponentsBuilder.on(AuthenticationController.class).passwordChange("token1234") ).build().toString();
原方式失效原因
buildAndExpand适用于已明确包含模板变量的UriComponents实例,但fromMappingName返回的是未绑定参数的映射元信息,必须先通过withArgs()完成参数与模板的关联,再执行build()才能生成带参数的URL。直接调用buildAndExpand无法正确关联命名路由的参数模板。
内容的提问来源于stack exchange,提问作者Mr. Kenneth
相关产品推荐
相关产品推荐

