SpringMVC中controller接收Json数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hhc0917/article/details/81388534

1.jsp页面发送ajax的post请求:
function postJson(){
var json = {“username” : “imp”, “password” : “123456”};
$.ajax({
type : “post”,
url : “<%=basePath %>ajaxRequest”,
contentType : “application/json;charset=utf-8”,
dataType : “json”,
data: JSON.stringify(json),
success : function(data){
alert(“username:”+data.username+” id:”+data.id);
},
error : function(){
alert(“请求失败”);
}
})
}
注意:

1.在发送数据时,data键的值一定要写成JSON.stringify(json),将数据转换成json格式,否则会抛出异常
2.basePath是项目根目录:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
%>

2.controller接收请求:
@ResponseBody
@RequestMapping(value=”/ajaxRequest”,method=RequestMethod.POST)
public User ajaxRequest(@RequestBody User user){
System.out.println(user);
return user;
}
注意:
1.@RequestBody修饰目标方法的入参,可以将ajax发送的json对象赋值给入参。当然这里的入参user是我们自定义的实体类型。不这样写后端接收不到在用jpa保存的时候会报错[User{userId=null, username=’null’, password=’null’, salt=’null’, email=’null’, mobile=’null’, status=null, deptId=null, createTime=null}]
2.@ResponseBody修饰的方法返回的数据,springmvc将其自动转换成json格式,然后返回给前端
3.最后将user返回,springmvc自动将其转换成json返回给前端

猜你喜欢

转载自blog.csdn.net/Hhc0917/article/details/81388534