AJAX設定content-type為:application/json提交引數後臺接收引數的問題
阿新 • • 發佈:2018-12-21
我一直做java的,對前端說不上有多瞭解,以前遇到的前端的開發人員,包括我自己再寫ajax的時候基本上都是以下寫法:
$('#send').click(function(){ $.ajax({ headers:{ Authorization : "Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJVa1p1dEsxQm1PX2p3V09WVDJlbk16Z2piaHljZm1Ld0RiRkV1Q1RhdjY0In0.eyJqdGkiOiI1YzA2ZTk3NS1hNDRjLTRhMzctYmMyNy1hNDlhYzlhODc2MDMiLCJleHAiOjE1NDE1OTExNzMsIm5iZiI6MCwiaWF0IjoxNTQxNTkwMjczLCJpc3MiOiJodHRwczovL2Rldi54dWViYXN0dWR5LmNvbS9hdXRoL3JlYWxtcy9zYXRvIiwiYXVkIjoic2FsZXMtY2xpZW50Iiwic3ViIjoiN2Q0ODIxMDgtM2UzNi00OThmLWEyODAtYjE0YjhmMGJlN2ZkIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoic2FsZXMtY2xpZW50Iiwibm9uY2UiOiJlYzFhNGIxMy04ZWZhLTQ1MTQtODkyZC1mNmU0ODkyZmNmNmYiLCJhdXRoX3RpbWUiOjE1NDE1OTAyNTMsInNlc3Npb25fc3RhdGUiOiIwMDEyNmUzYS1jODcxLTRjZWYtYTg4Ni1hZDY0YTc1YWMyY2MiLCJhY3IiOiIwIiwiY2xpZW50X3Nlc3Npb24iOiI0YTA2NTY0YS04Yzg4LTRkYjgtOTNlOS04OWI4MTBiY2FjODIiLCJhbGxvd2VkLW9yaWdpbnMiOlsiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwiaHR0cDovLzE5Mi4xNjguMC4yIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJTYWxlcyIsIlRlYWNoZXJzIiwiU2FsZUFkbWluIiwiVGVhY2hlckFkbWluIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJzYXRvLW5vdGlmaWNhdGlvbiI6eyJyb2xlcyI6WyJUZWFjaGVycyIsIlNhbGVzIiwiU2FsZUFkbWluIiwiVGVhY2hlckFkbWluIl19LCJzYWxlcy1jcm0iOnsicm9sZXMiOlsiU2FsZXMiLCJTYWxlQWRtaW4iXX0sInNhbGVzLWxlYWRzLWh0dHAiOnsicm9sZXMiOlsiU2FsZXMiXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJ2aWV3LXByb2ZpbGUiXX19LCJuYW1lIjoi6ZSA5ZSuIDAxIiwicHJlZmVycmVkX3VzZXJuYW1lIjoic2FsZXMwMSIsImdpdmVuX25hbWUiOiLplIDllK4iLCJmYW1pbHlfbmFtZSI6IjAxIn0.TyqgUCost9sDy-tE8KAPW_3tBbTnzm6xfgIY2c1FhEYR3-mfLLbh0LLdkqDJEMs9AIvElOyU1jf9YA4laA6imaNqAshPvrRhxh4wIqJ9cCTNJjrou98gxkccRSSaFX19VctxLxRGk1wC_ZlIqdg9rgklVJE1rpDpzOnm1WF-skSwoQI7UZINEeizVZC21T4eIvDLoWUU6Qp9LKW3kcahU0k44S2v1k-lMJzE8dD4rQco7Z1vswXvYOxpk5g-RPKiREo1je-ZGyZLXZiJPdLwIm7mGp1x6qOxIUnbrMZk24VwS48hBhbbKeahBS-lvfEck0vLls3EVL0JMx9gre3Jbg" }, type: "POST", url: "https://dev.xuebastudy.com/crm-cti/userDetail", data: { "id":"4", "customerNumber":"13315863006", "customerId":"test", "salesId":4 }, dataType: "json", success: function(data){ alert(JSON.stringify(data)) } }); });
所以後臺在接收引數的時候也習慣了 request.getParameter(),或者使用@RequestParam的註解的方式。
這樣是沒有問題的,因為這種方式提交的時候他的請求頭如下
但是新公司的前端,喜歡使用使用$.ajax(url,data,callback)的方式發起ajax,並且設定了content-type為 application/json。但是在Post的時候,我後臺居然接受不到引數,瞬間一臉懵逼。
使用POSTMan模擬下情況如下
檢視ajax的請求程式碼如下:
對於這種方式,如果沒有使用框架的情況下,只能採用傳統的流的方式接收:
private String getXmlString(HttpServletRequest request) { BufferedReader reader = null; String line = ""; String xmlString = null; try { reader = request.getReader(); StringBuffer inputString = new StringBuffer(); while ((line = reader.readLine()) != null) { inputString.append(line); } xmlString = inputString.toString(); } catch (Exception e) { // throw new YppException(PayException.xmlParseError); } return xmlString; }
但是在spring boot的中可以使用@RequestBody加上物件接收
@RequestBody ParamUserDetail userDetail
當然如果不願意構造物件的時候可以使用Map<String,String>來接收,對於少量引數建議使用這種方式
@RequestBody Map<String,String> params