SpringMVC中响应json数据(异步传送)

1、首先导入3个jar包:

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

JSON所需jar包下载(百度云) 密码:bfav

2、在controller中,@RequestMapping注解下添加@ResponseBody注解,自动将数据封装成json

Department有两个属性iddepartmentName;

 1 @Controller
 2 public class JsonController {
 3     @RequestMapping(value="/helloJson")
 4 @ResponseBody
 5     public List<Department> helloJson() throws IOException{
 6         List<Department> departList=new ArrayList<Department>();
 7         departList.add(new Department(2, "财务部"));
 8         departList.add(new Department(3, "人事部"));
 9         departList.add(new Department(5, "技术部"));
10         return departList;
11     }
12 }

3、在jsp页面访问后台方法,并接受json数据

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 2 <!-- 动态获取路径,详情查看web应用路径问题(相对路径,绝对路径,动态获取路径) -->
 3 <%
 4     String path = request.getContextPath();
 5     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 8 <html>
 9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11 <title>Insert title here</title>
12 <script type="text/javascript" src="<%=basePath %>public/js/jquery-3.2.1.min.js"></script>
13 <script type="text/javascript">
14     $(function(){
15         $("#testJson").click(function(){
16             alert();
17             var url="${pageContext.request.contextPath}/helloJson";
18             function callback(data){
19                 for(var i=0;i<data.length;i++){
20                     alert(data[i].id+"-----"+data[i].departmentName);
21                     //2-----财务部
22                     //3-----人事部
23                     //5-----技术部
24                 }
25             }
26             $.post(url,{},callback);
27         });
28     });
29 </script>
30 </head>
31 <body>
32     <button id="testJson">json</button>
33 </body>
34 </html>

 

posted @ 2017-08-23 21:07  bwlu---ed  阅读(545)  评论(0编辑  收藏  举报