springmvc 默认使用jackson作为json类库,不需要修改applicationContext-servlet.xml任何配置,只需引入以下类库springmvc就可以处理json数据:
<!--spring-json依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
@RequestBody:作用是接收前端ajax传递给后端的json字符串,并将json格式的数据转为java对象
@ResponseBody:作用是将java对象转为json格式的数据传递给前台ajax
@RequestMapping("saveAccount3")
@ResponseBody
public Map saveAccount3(@RequestBody Account account){//@RequestBody:java--->json
HashMap<String,Object> map=new HashMap<>();
try {
map.put("status",200);
map.put("msgs", account);
} catch (Exception e) {
e.printStackTrace();
map.put("status",500);
map.put("msgs", "错误");
}
return map;
}
//引入js库文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
//添加按钮
<input type="button" value="测试ajax请求json和响应json" id="testJson"/>
//ajax代码
<script type="text/javascript">
$(function(){
$("#testJson").click(function(){
$.ajax({
type:"post",
url:"/account/saveAccount3",
contentType:"application/json;charset=UTF-8",
data:'{"id":1,"name":"张二狗","money":999.0}',
success:function(data){
if(data.status == 200){
alert(data.msgs.name);
}else {
alert(data.msgs)
}
}
})
});
})
</script>
?