关于
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获取被序列化的参数