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

来源:互联网 发布:知乎 人体工程学椅子 编辑:程序博客网 时间:2024/05/15 01:36
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})@ResponseBodypublic 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")@ResponseBodypublic 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;}
原创粉丝点击