天天看點

@RequestParam無法獲得參數

 關于 application/x-www-form-urlencoded還是 application/json

今天使用postman模拟一次ajax請求結果背景用@RequestParam怎麼也取不到參數,一直報錯400

@RequestMapping(value = "deleteAssetManage", method = RequestMethod.POST)
	public @ResponseBody
	Object deleteAssetManage(@RequestParam String assetId) {
		Asset asset = new Asset();
		Gson gson = new Gson();
		//删除資産資訊
		assetManageService.deleteAssetById(assetId);
		Map<String, Object> hMap = new HashMap<String, Object>();
		hMap.put("flag", true);
		return gson.toJson(hMap);
	}
	
           

然後用頁面發送一次ajax請求,發現又能傳遞進參數,點開控制台對比才發現問題所在

Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Content-Length: 40
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: JSESSIONID=CA52D4C0735DB463377A10E3BB8CBE9A; _ga=GA1.1.547674177.1522566736
Host: localhost:8080
Origin: http://localhost:8080
Referer: http://localhost:8080/assetManager/background/toHello.action
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
X-Requested-With: XMLHttpRequest
           

這裡顯示header裡面Content-Type是application/x-www-form-urlencoded,而不是像我想的application/json

postman把傳遞資料類型修改便可以獲得參數

application/x-www-form-urlencoded是以表格的形式請求,而application/json則将資料序列化後才進行傳遞,如果使用了@RequestParam會在Content裡面查找對應的資料,結果因為傳遞的資料已經被序列化是以不能找到,是以當要使用@RequestParam注解時候應當使用application/x-www-form-urlencoded,而如果想要使用application/json則應當使用@RequestBody擷取被序列化的參數

繼續閱讀