springmvc完成post请求接口的方法:
第一种形式:
前端使用ajax调用:
<script type="text/javascript">
$(document).ready(function () {
$("#postClick").click(function () {
var role = {
"id": 1,
"roleName": "lxij",
"note": "test for post"
}
$.ajax({
url: "/role/testPost.do",
type: 'post',
async: false,
data: role,
contentType: "application/x-www-form-urlencoded",
success: function (result) {
console.log(result);
alert(result);
},
error: function (e) {
alert("服务器错误:" + e);
}
});
});
});
</script>
后台controller接受:
@RequestMapping(value = "/testPost",method = RequestMethod.POST)
@ResponseBody
public CustomReturnType test(Role role, ModelAndView mv){
//...
return new CustomReturnType();
}
重点:ajax参数data: role, contentType: “application/x-www-form-urlencoded”,
如果用JSON.stringify(role)就不行了;如果这样设置,那么传到后台的request就会有一个参数parameter,参数的key是{“id”:1,“roleName”:“lxij”,“note”:“test for post”},value为空,并没有达到确切目的,
所以当设置为contentType: "application/x-www-form-urlencoded"时,data直接给定js对象即可("application/x-www-form-urlencoded"为默认,可以不设置);
第二种形式:
前端:
<script type="text/javascript">
$(document).ready(function () {
$("#postClick").click(function () {
var role = {
"id": 1,
"roleName": "lxij",
"note": "test for post"
}
$.ajax({
url: "/role/testPost.do",
type: 'post',
async: false,
data: JSON.stringify(role),
contentType: "application/json",
// contentType: "application/x-www-form-urlencoded",
success: function (result) {
console.log(result);
alert(result);
},
error: function (e) {
alert("服务器错误:" + e);
}
});
});
});
</script>
后端:
@RequestMapping(value = "/testPost",method = RequestMethod.POST)
@ResponseBody
public CustomReturnType test(@RequestBody Role role, ModelAndView mv){
//...
return new CustomReturnType();
}
这种形式就可以前后端直接以json串的形式传递了,
前端:data: JSON.stringify(role) + contentType: “application/json”,
后端:对参数家注解 @RequestBody
springmvc就会自动解析请求的json串并填充包装到参数中
注意:必须声明contentType: “application/json”,否则默认会以"application/x-www-form-urlencoded"的形式传递
总结
1、当contentType为"application/x-www-form-urlencoded"时,data对应js对象,不需要转成json串,对应后台不需要特殊处理,request请求中会自动设定parameter
2、当前后端需要以json串形式传递时,必须声明contentType: “application/json”,且data必须JSON.stringify(…)将对象转成串;对应后台需要使用@RequestBody注解要包装的形参