背景:
今天項目上出現一個問題,是前端的GET請求url中帶有路徑參數,這個參數中有/這個特殊字符,在postman的url中已經轉移成了%2F,后端用的是springboot,並沒有收到這個請求,直接返回了400的錯誤
原因:
據說是tomcat默認是不支持轉義的,需要手動設置一下轉化,這個搜索tomcat的設置可以找到,但是這個是springboot,有內置的tomcat,但是在yml中找不到相關的配置。
解決方法:
修改一下啟動類,加一個系統參數,重寫WebMvcConfigurerAdapter的configurePathMatch方法.
@SpringBootApplication public class Application extends WebMvcConfigurerAdapter { public static void main(String[] args) throws Exception {
// step2: System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); SpringApplication.run(Application.class, args); }
// step1: @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setUrlDecode(false); configurer.setUrlPathHelper(urlPathHelper); } }
4. 本地tomcat 中該如何設置呢? (本例是修改SpringBoot 內嵌 的 tomcat 配置)
在tomcat目錄 /conf/catalina.properties 文件末尾添加下列內容
org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
重啟tomcat成功解決問題
5. 其他常用特殊字符的url轉義用法如下:
符號 | URL中轉義結果 | 轉義碼 |
+ | URL 中 + 號表示空格 | %2B |
空格 | URL中的空格可以用+號或者編碼 | %20 |
/ | 分隔目錄和子目錄 | %2F |
? | 分隔實際的URL和參數 | %3F |
% | 指定特殊字符 | %25 |
# | 表示書簽 | %23 |
& | URL中指定的參數間的分隔符 | %26 |
= | URL中指定參數的值 | %3D |