如果Content-Type設置為“application/x-www-form-urlencoded;charset=UTF-8”無論是POST請求還是GET請求都是可以通過這種方式成功獲取參數,但是如果前端POST請求中的body是Json對象的話,會報上述錯誤。
請求中傳JSON時設置的Content-Type 如果是application/json或者text/json時,JAVA中request.getParameter("")怎么也接收不到數據。這是因為,Tomcat的HttpServletRequest類的實現類為org.apache.catalina.connector.Request(實際上是org.apache.coyote.Request)。
問題點2:
當前端請求的Content-Type是Json時,可以用@RequestBody這個注解來解決。@RequestParam 底層是通過request.getParameter方式獲得參數的,換句話說,@RequestParam 和request.getParameter是同一回事。因為使用request.getParameter()方式獲取參數,可以處理get 方式中queryString的值,也可以處理post方式中 body data的值。所以,@RequestParam可以處理get 方式中queryString的值,也可以處理post方式中 body data的值。@RequestParam用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容,提交方式GET、POST。
@RequestBody接受的是一個json對象的字符串,而不是Json對象,在請求時往往都是Json對象,用JSON.stringify(data)的方式就能將對象變成json字符串。
總結:
前端請求傳Json對象則后端使用@RequestParam;
前端請求傳Json對象的字符串則后端使用@RequestBody。
前后端數據交互出現json數據類型不符合
此種情況為前端與后端json格式不統一導致
1.json 分為兩種類型;
(1) json 對象類型,即前端定義的Content type 為 application/x-www-form-urlencoded等
(2) json字符串類型,即前端定義的Content type 為 application/json
var params1 = { department_id: this.dataForm.deptId, date_type: this.dataForm.dateType, time: this.dataForm.dateTime } var params = JSON.stringify(params1) console.log(params); this.$http.post('/train/target/getReportDeptTarget', params,{ headers: { 'content-type': 'application/json ' }}).then(({ data: res }) => {})