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;
}