SpringMVC如何返回JSON数据
1、在index.jsp首页添加一个返回JSON的超链接。
<html>
<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);
}
});
});
})
</script>
<body>
<h2>
<a href="springmvc/testJson" id="testJson">Test JSON</a>
</h2>
</body>
2、在SpringMVC控制层返回JSON数据。
package com.gwolf.springmvc.handlers;
import java.util.Collection;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gwolf.springmvc.dao.DepartmentDao;
import com.gwolf.springmvc.dao.EmployeeDao;
import com.gwolf.springmvc.domain.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
@RequestMapping("/springmvc/testJson")
@ResponseBody
public Collection<Employee> testJson() {
return this.employeeDao.getAll();
}
}
3、在pom.xml配置文件中加入跟SpringMVC返回JSON数据绑定相关的依赖包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
4、运行tomcat,查看json数据是否调用成功。
5、我们打开谷歌开发者工具栏,查看JSON数据的返回情况。
6、在开发者工具栏查看json数据的结果。