SpringBoot 3调用带尾斜杠的API端点返回404,如何兼容?
解决SpringBoot 3.x中带尾斜杠的API端点404问题
问题原因
SpringBoot 3.x 默认使用 PathPatternParser 作为路径匹配器,它默认不自动忽略URL末尾的斜杠;而SpringBoot 2.x 采用的 AntPathMatcher 默认会忽略尾斜杠,这就是升级后带尾斜杠的请求返回404的核心原因。
解决方案
方案1:切换回AntPathMatcher匹配策略
在配置文件(application.properties 或 application.yml)中添加以下配置,恢复和SpringBoot 2.x一致的路径匹配行为:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
yaml格式配置:
spring: mvc: pathmatch: matching-strategy: ant_path_matcher
方案2:修改@RequestMapping的路径规则
直接在API路径上添加可选尾斜杠的语法,让路径同时匹配带/不带尾斜杠的请求:
@RequestMapping(value = "upload/config_data{/}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA) public String uploadConfigData(@RequestParam("inFile") MultipartFile inFile, @RequestParam("rowData") String rowData) throws ServiceException, DAOException { return extConfigApiService.uploadConfigData(inFile, rowData); }
这里的{/}是PathPatternParser支持的语法,表示末尾的斜杠是可选的。
方案3:全局配置PathPatternParser忽略尾斜杠
通过自定义WebMvc配置类,全局开启尾斜杠匹配:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.util.pattern.PathPatternParser; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { PathPatternParser parser = new PathPatternParser(); // 开启尾斜杠匹配 parser.setTrailingSlashMatch(true); configurer.setPatternParser(parser); } }
内容的提问来源于stack exchange,提问作者manjosh
相关产品推荐
相关产品推荐

