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>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/saveAccount2")
@ResponseBody
public Map saveAccount2(@RequestBody Account account){
Map<String, Object> map = new HashMap<String, Object>();
map.put("status",200);
map.put("msg",account);
return map;
}
}
在index.jsp里面定义ajax请求
添加按钮
<input type="button" value="测试ajax请求json和响应json" id="testJson"/>
引入js库文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
编写ajax代码
<script type="text/javascript">
$(function(){
$("#testJson").click(function(){
$.ajax({
type:"post",
url:"/account/saveAccount2",
contentType:"application/json;charset=UTF-8",
data:'{"id":1,"name":"张二狗","money":999.0}',
success:function(data){
if(data.status == 200){
alert(data.msg.name);
alert(data.msg.money);
}
}
})
});
})
</script>
测试