springmvc返回json数据

1. 加入json的jar包 

jackson-annotations-2.1.5.jar
jackson-core-2.1.5.jar
jackson-databind-2.1.5.jar

2. 发送ajax请求

注意: 这里涉及到springmvc处理静态资源的问题, 比如js文件, 

处理方法: http://www.cnblogs.com/josephcnblog/articles/6593752.html

index.jsp:

1 <a href="getJson" id="getJson">Get Json</a>
 1 <script type="text/javascript" src="${pageContext.request.contextPath }/script/jquery-1.7.2.min.js"></script>
 2     <script type="text/javascript">
 3         $(function() {
 4             $("#getJson").click(function() {
 5                 // 发送ajax请求
 6                 var url = this.href;
 7                 var args = {"time": new Date()};
 8                 $.post(url, args, function(data) {
 9                     // 获取json数据
10                     for (var i=0; i<data.length; i++) {
11                         var id = data[i].id;
12                         var lastName = data[i].lastName;
13                         alert(id + " : " + lastName);
14                     }
15                 });
16             });
17         });
18     </script>

3. 处理请求, 返回集合

 1 @Controller
 2 public class EmployeeHandler {
 3     
 4     @Autowired
 5     private EmployeeDao employeeDao;
 6     
 7     @ResponseBody
 8     @RequestMapping("/getJson")
 9     public Collection<Employee> getJson() {
10         
11         return employeeDao.getAll();
12     }
13 }

 

posted @ 2017-03-21 12:56  半生戎马,共话桑麻、  阅读(100)  评论(0)    收藏  举报
levels of contents