springboot~HttpPut開啟application/x-www-form-urlencoded


在使用spring框架時,默認情況下@RequestParam注解只到接受Get和Post請求參數 ,而對於Put來說默認是使用@ReqeustBody注解的,如果希望為Put也開啟@RequestParam,需要添加過濾器實現。

@RequestParam

用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容。(Http協議中,如果不指定Content-Type,則默認傳遞的參數就是application/x-www-form-urlencoded類型)
RequestParam可以接受簡單類型的屬性,也可以接受對象類型。
實質是將Request.getParameter() 中的Key-Value參數Map利用Spring的轉化機制ConversionService配置,轉化成參數接收對象或字段。

@RequestBody

處理HttpEntity傳遞過來的數據,一般用來處理非Content-Type: application/x-www-form-urlencoded編碼格式的數據。

  • GET請求中,因為沒有HttpEntity,所以@RequestBody並不適用。
  • POST請求中,通過HttpEntity傳遞的參數,必須要在請求頭中聲明數據的類型Content-Type,SpringMVC通過使用HandlerAdapter 配置的HttpMessageConverters來解析HttpEntity中的數據,然后綁定到相應的bean上。

總結

  • 在GET請求中,不能使用@RequestBody。
  • 在POST請求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,對於參數轉化的配置必須統一。
  • 在Put請求時,默認不支持application/x-www-form-urlencoded的方式提交

實現Put時的application/x-www-form-urlencoded提交

默認情況下會有錯誤

{"timestamp":1579144530724,"status":400,"error":"Bad Request","message":"Required String parameter 'name' is not present"}

添加PutFilter

@Component
@WebFilter(urlPatterns = "/*")
public class PutFilter extends HttpPutFormContentFilter {

}

從新啟動項目,PutFilter bean就被加載了

2020-01-16 11:13:37,358 - Mapping filter: 'tracingFilter' to: [/*]
2020-01-16 11:13:37,358 - Mapping filter: 'exceptionLoggingFilter' to: [/*]
2020-01-16 11:13:37,358 - Mapping filter: 'httpTraceFilter' to: [/*]
2020-01-16 11:13:37,358 - Mapping filter: 'webStatFilter' to urls: [/*]
2020-01-16 11:13:37,358 - Mapping filter: 'putFilter' to: [/*]
2020-01-16 11:13:37,358 - Mapping filter: 'corsFilter' to: [/*]

這時,你的Put請求就支持application/x-www-form-urlencoded提交了,就是來在后台可以用@RequestParam注解來接收了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM