创建User
package com.po;
public class User {
private String userName;
private String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "User [userName=" + userName + ", passWord=" + passWord + "]";
}
}
创建testJson.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试json</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testResponseBody();
});
function testResponseBody(){
$.post("${pageContext.request.contextPath}/getJson",null,
function(data){
$.each(data,function(){
var tr = $("<tr align='center'/>");
$("<td/>").html(this.userName).appendTo(tr);
$("<td/>").html(this.passWord).appendTo(tr);
$("#table").append(tr);
})
},"json");
}
</script>
</head>
<body>
<table id="table" border="1" style="border-collapse: collapse;">
<tr align="center">
<th>用户名</th>
<th>密码</th>
</tr>
</table>
</body>
</html>
创建UserController
package com.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.po.User;
@Controller
public class UserController {
@RequestMapping("/getJson")
@ResponseBody
public Object getJson() {
List<User> users=new ArrayList<User>();
User us1=new User();
us1.setUserName("zhangshan");
us1.setPassWord("zhsjd12");
users.add(us1);
User us2=new User();
us2.setUserName("lishi");
us2.setPassWord("dexx52");
users.add(us2);
return users;
}
}
启动Tomcat并访问testJson.jsp