@ResponseBody和@RequestBody
springmvc对json的前后台传输做了很好封装,避免了重复编码的过程,下面来看看常用的@ResponseBody和@RequestBody注解
- 添加依赖springmvc对json的处理依赖jackson
- <mvc:annotation-driven />//不要忘了命名空间配置
- 如果传输的是单层json对象,可以直接用 @RequestParam接收
//前台
$.ajax({
type : "post",
dataType : "json",
url : "/testRequestBody",
data:{
name:"韦德",
age:35
},
success : function(result) {
}
//后台
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestParam Map<String, Object> map) {
System.out.println(map);// {name=韦德, age=35}
return "index";
}
- 如果传输的是多层嵌套json对象,使用@ResponseBody,否则会出现数据丢失问题
$.ajax({
type : "post",
dataType : "json",
url : "/testRequestBody",
contentType:"application/json",
data:JSON.stringify({
name:"韦德",
win:[2006,2012,2013],
age:35
}),
success : function(result) {
}
//后台
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody Map<String, Object> map) {
System.out.println(map);//{name=韦德, win=[2006, 2012, 2013], age=35}
return "index";
- @ResponseBody:返回json格式数据给前台
@RequestMapping("/testResponseBody")
@ResponseBody
public Map<String, Object> testRequestBody() {
Map<String, Object> result = new HashMap<String, Object>();
result.put("name", "韦德");
result.put("age", 35);
return result;
}