SpringMVC如何返回JSON数据
工具/原料
SpringMVC
eclipse
方法/步骤
1、在index.jsp首页添加一个返回JSON的超链接。<html>&l隋茚粟胫t;scripttype="text/jav锾攒揉敫ascript"src="scripts/jquery-1.9.1.min.js"></script><scripttype="text/javascript">$(function(){$("#testJson").click(function(){varurl=this.href;varargs={};$.post(url,args,function(data){for(vari=0;i<data.length;i++){varid=data[i].id;varlastName=data[i].lastName;alert(id+":"+lastName);}});});})</script><body><h2><ahref="springmvc/testJson"id="testJson">TestJSON</a></h2></body>
2、在SpringMVC控制层返回JSON数据。packagecom.gwolf.s圬桦孰礅pringmvc.handlers;import惺绅寨瞀java.util.Collection;importjava.util.Map;importjavax.validation.Valid;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.validation.BindingResult;importorg.springframework.validation.FieldError;importorg.springframework.web.bind.annotation.ModelAttribute;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importcom.gwolf.springmvc.dao.DepartmentDao;importcom.gwolf.springmvc.dao.EmployeeDao;importcom.gwolf.springmvc.domain.Employee;@ControllerpublicclassEmployeeHandler{@AutowiredprivateEmployeeDaoemployeeDao;@AutowiredprivateDepartmentDaodepartmentDao;@RequestMapping("/springmvc/testJson")@ResponseBodypublicCollection<Employee>testJson(){returnthis.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数据的结果。