您的位置:首页 > 编程语言 > Java开发

java端使用注解接收参数时,ajax请求注意

2017-10-19 16:22 447 查看
springMVC项目中,后台Java方法使用注解获取参数,ajax请求时分两种情况  {1:后台使用@requestParam  2:后台使用@requestBody时}

前端:
1:后台使用@requestParam时
需要注意的是:
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);
}
});
}
2:后台使用@requestBody时
需要注意的是:
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端

/**
* 测试responseBody注解返回接送数据*/
@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;
}
/**
* 测试responseBody注解返回接送数据*/
@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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐