前言
- 现在企业中好多项目都用Json传送数据,因为Json在企业开发中已经作为通用的接口参数类型,并且Json数据在页面(客户端)解析很方便。下面是Json的定义形式。
var obj={”name”:”张三”,”age”:12}
Json数据解析形式:obj.name
现在有两种需求:
- 前台Jsp向Handler中传递Json数据,Handler向前台返回Json数据。
- 前台Jsp向Handler中传递键值对形式,Handler返回json数据。
第一种,前台传json,Handler返回的也是Json
Js代码
function requestjson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/requestJson.action',
contentType:'application/json;charset=utf-8',
data:'{"name":"张三","age":12}',
success:function(data){
alert(data.name);
}
});
}
Handler代码
@ResponseBody
@RequestMapping("/requestJson")
public Student requestJson(@RequestBody Student student){
System.out.println(student);
return student;
}
第二种,前台传递键值对,后台返回的是Json
Js代码
function responsejson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/responseJson.action',
data:'name=张三&age=12',
success:function(data){
alert(data.name);
}
});
}
Handler代码
@ResponseBody
@RequestMapping("/responseJson")
public Student responseJson(Student student) throws Exception{
System.out.println(student);
return student;
}
小结
- 这是利用JQuery的Ajax来实现前后台传递Json数据的,再Handler中,如果想接受前台传递过来的Json数据,那么在形参前面加上@RequestBody注解,如果Handler也想返回Json数据,那么可以在方法上加上@ResponseBody注解。