java端使用註解接收引數時,ajax請求注意
阿新 • • 發佈:2019-01-09
springMVC專案中,後臺Java方法使用註解獲取引數,ajax請求時分兩種情況 {
1:後臺使用@requestParam
2:後臺使用@requestBody時
}
1:後臺使用@RequestBody時 需要注意的是:
1》:ajax中引數需要將json物件轉成json格式的字串
2》:contentType需要設定成 application/json;
function testAjax() { var url = "/agentmobileApp/test/testRequestBody"; var reqPara = JSON.stringify({'did': '55', 'name': 'jack', 'age': 15}); $.ajax({ async: false, url: url, type: 'POST', timeout: '30000', data: reqPara, contentType: 'application/json;charset=utf-8', dataType: 'json', success: function (rep) { alert(rep.result + " ;" + rep.message + " ;" + rep.data.resp.name); }, error: function (rep) { alert("請檢查網路是否連線" + rep); } }); }
java端程式碼: @RequestMapping("/testRequestBody") //@RequestMapping(value = "/testRequestBody",method = {RequestMethod.POST}) @ResponseBody public ResultJson testResponseBody(@RequestBody BodyVO bodyVO) { ResultJson resultJson = new ResultJson(); TestVO testVO = new TestVO(); String did = bodyVO.getDid(); String name = bodyVO.getName(); int age = bodyVO.getAge(); logger.info("獲取前端的引數did :" + did + " name: " + name + " age: " + age); // 簡單組裝引數 testVO.setAge(20); testVO.setName(did); testVO.setAddress(did + "66666"); resultJson.setResult("0000"); resultJson.setMessage("成功了啊"); resultJson.getData().put("resp", testVO); return resultJson; }
2:後臺使用@requestParam時
需要注意的是:
1》:引數為json物件
2》:contentType 選項需要註釋掉
function testAjax1() { var url = "/agentmobileApp/test1/testResponseBody"; var reqPara = {'did': '555', 'name': 'jack', 'age': 15}; $.ajax({ async: false, url: url, type: 'POST', timeout: '30000', data: reqPara, //contentType: 'application/json;charset=utf-8', dataType: 'json', success: function (rep) { alert(rep.result + " ;" + rep.message + " ;" + rep.data.resp.name); }, error: function (rep) { alert("請檢查網路是否連線" + rep); } }); }
JAVA端:
@RequestMapping("/testResponseBody")
@ResponseBody
public ResultJson testResponseBody(@RequestParam String did, @RequestParam String name, @RequestParam int age) {
ResultJson resultJson = new ResultJson();
TestVO testVO = new TestVO();
testVO.setAge(20);
testVO.setName(did);
testVO.setAddress(did + "66666");
resultJson.setResult("0000");
resultJson.setMessage("成功了");
resultJson.getData().put("resp", testVO);
return resultJson;
}