springboot~HttpPut開啟application/x-www-form-urlencoded
在使用spring框架時,默(mo)認情(qing)況下(xia)@RequestParam注(zhu)解(jie)只到(dao)接受Get和Post請求參數 ,而對(dui)于Put來(lai)說默(mo)認是使用@ReqeustBody注(zhu)解(jie)的,如果希望為Put也開啟@RequestParam,需要(yao)添加過濾器實(shi)現。
@RequestParam
用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容。(Http協議中,如果不指定Content-Type,則默認傳遞的參數就是application/x-www-form-urlencoded類型)
RequestParam可以接受簡單類型的屬性,也可以接受對象類型。
實質(zhi)是將Request.getParameter() 中的(de)Key-Value參數Map利用Spring的(de)轉(zhuan)化(hua)機制ConversionService配置,轉(zhuan)化(hua)成參數接收對(dui)象或字段(duan)。
@RequestBody
處理(li)HttpEntity傳遞過來的數據,一般用(yong)來處理(li)非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"}
添(tian)加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: [/*]
這(zhe)時,你的(de)Put請(qing)求就(jiu)支持application/x-www-form-urlencoded提交(jiao)了,就(jiu)是來在后臺可(ke)以用@RequestParam注解(jie)來接收了!