/**
* 测试自定义AJAX JSON
*/
@RequestMapping("/testJson")
public void testJson(HttpServletResponse response) throws Exception{
User user = new User();
user.setName("zhanghw");
user.setRealName("zhanghongwei");
JSONObject json = JSONObject.fromObject(user);
PrintWriter out = response.getWriter();
out.print(json.toString());
}
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script type="text/javascript">
$(function() {//测试ajax json
$.ajax({
type : "post",
url : "${pageContext.request.contextPath}/testJson.action",
success : function(data) {
alert(data);
console.log(data);
},
dataType : "json"
});
});
</script>
•SpringMVC中,可以使用@ResponseBody注解,快速生成json数据;但需要jackson类库支持。
•配置要求:
•<context:annotation-config />
•<mvc:annotation-driven /> //加载转换器,并支持对象与JSON间的数据转换
•生成JSON字符串:
@RequestMapping("/getJson")
public @ResponseBody User getJson(){
User user = new User("zhanghw", "123456");
return user;
}
- /**
- * 测试AJAX JSON
- */
- @RequestMapping("/testJson2")
- public @ResponseBody List<User> testJson2(){
- List<User> list = new ArrayList<User>();
- User user = new User();
- user.setName("Hello");
- user.setRealName("Hello World!");
- list.add(user);
- return list;
- }