接收PUT、PATCH、DELETE方法的form data參數

問題描述:

場景:

在將原有的系統改造爲springboot項目時,打算將原有的get、post請求改爲get、post、put、delete請求,使用了mybatis-plus的自動生成基礎代碼。

問題:

但是,在使用@PutMapping時,後端接收不到傳遞過來的參數。

 

查找解決方案:

1. HttpPutFormContentFilter

在網上搜索之後發現,有一個 HttpPutFormContentFilter 類,可以解決這個問題。類註釋中有這麼一段話:

The Servlet spec requires form data to be available for HTTP POST but not for HTTP PUT or PATCH requests. This filter intercepts HTTP PUT and PATCH requests where content type is {@code 'application/x-www-form-urlencoded'}, reads form encoded content from the body of the request, and wraps the ServletRequest in order to make the form data available as request parameters just like it is for HTTP POST requests.

翻譯如下(湊合着看吧):

Servlet規範要求POST請求的from data必須是可用的,但並沒有要求PUT、PATCH也如此。這個過濾器攔截那些內容類型是'application/x-www-form-urlencoded'(譯者注:對應發送的數據就是form data)的PUT和PATCH請求,並讀取請求體中加密的內容,最後將form data封裝到ServletRequest,從而像POST請求一樣,從request的parameter中就可以有效的獲取到from data的各個參數。

2. FormContentFilter類

由於該類是廢棄類,所以源碼中推薦了另外一個類,FormContentFilter,這個類的註釋:

Filter that parses form data for HTTP PUT, PATCH, and DELETE requests and exposes it as Servlet request parameters. By default the Servlet spec only requires this for HTTP POST.

翻譯如下:

將HTTP的PUT、PATCH、DELETE請求中的form data轉化,並暴露給Servlet的“請求參數”。默認情況下,Servlet規範僅僅要求POST請求轉化form data。

注意:

FormContentFilter類和HttpPutFormContentFilter類的區別,前者比後者多處理了DELETE請求。

 

結論:

從註釋中,就很好懂了,默認情況下,Servlet規範是不支持PUT、PATCH、DELETE的,只支持POST,因此,在springboot的啓動類或者任意的配置類上導入FormContentFilter即可。如果不需要處理DELETE請求,HttpPutFormContentFilter也可以,但是已廢棄。

解決方法:

@SpringBootApplication
@Import( FormContentFilter.class )
public class SpringApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringApplication.class, args);
	}
}

或者:

@Configuration
@Import( FormContentFilter.class )
public class FormContentConfig {
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章