SpringMVC框架

第8章 处理JSON
8.1 返回JSON
1) 加入 jar 包:

http://wiki.fasterxml.com/JacksonDownload/   下载地址

jackson-annotations-2.1.5.jar

jackson-core-2.1.5.jar

jackson-databind-2.1.5.jar

2) 编写目标方法,使其返回 JSON 对应的对象或集合

@ResponseBody  //SpringMVC对JSON的支持

@RequestMapping("/testJSON")

public Collection<Employee> testJSON(){

return employeeDao.getAll();

}
3) 增加页面代码:index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

 "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>

<script type="text/javascript">

$(function(){ 

$("#testJSON").click(function(){

var url = this.href ;

var args = {};

$.post(url,args,function(data){

for(var i=0; i<data.length; i++){

var id = data[i].id;

var lastName = data[i].lastName ;

alert(id+" - " + lastName);

}

});

return false ;

});                

});

</script>

</head>

<body>

<a href="empList">To Employee List</a>

<br><br>

<a id="testJSON" href="testJSON">testJSON</a>

</body>

</html>
4) 测试