springmvc json 简单例子
1.控制器层:
1 @RequestMapping("/json.do") 2 @ResponseBody 3 //将会把返回值 转换为json对象 4 public List<User> json(){ 5 List<User> list = new ArrayList<User>(); 6 list.add(new User(1,"zhansan",22)); 7 list.add(new User(2,"wangwu",21)); 8 list.add(new User(3,"zhaosi",33)); 9 list.add(new User(4,"wangdana",14)); 10 return list; 11 }
2.jsp页面:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> 22 <script type="text/javascript"> 23 $(function(){ 24 $('#btn').click(function(){ 25 $.post("json.do",function(data){ 26 var html=""; 27 for(var i=0;i<data.length;i++){ 28 html+="<tr><td>"+data[i].id+"</td><td>"+data[i].name+"</td><td>"+data[i].age+"</td></tr>" 29 } 30 $('#content').html(html); 31 }); 32 }); 33 }); 34 </script> 35 36 </head> 37 38 <body> 39 <input type="button" id="btn" value="获取数据"/><br> 40 <table width="80%" align="center"> 41 <tr> 42 <td>编号</td> 43 <td>姓名</td> 44 <td>年龄</td> 45 </tr> 46 <tbody id="content"></tbody> 47 </table> 48 </body> 49 </html>