彻底解决Springboot中路径参数带/(%2F)的问题
背景
前两天突然出现了一个线上问题,有同事反应我提供的接口报400的错误。接口路径如下 PATCH /v1/basic/owners/{owner_code}/skus/{sku}
,经过排查发现是sku参数中有/
因此springboot转义后直接报错了。由于已经有很多团队对接了相关接口,且有很多的其他接口都使用了类似的传参方式,因此需要考虑怎么在系统中不让springboot自动解码
解决方案
我先列出可用的解决方案,然后在列出网上常见错误方案
- 在项目中添加环境变量
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
- 关闭spring自动decode url的开关
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setUrlDecode(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
- 开启Spring security中允许url中存在/的功能(如果项目中没有用到Spring security 可跳过此配置)
@Order(