JSP代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%-- ${pageContext.request.contextPath}用于解决使用相对路径时出现的问题,它的作用是取出所部署项目的名字。 --%>
<script type="text/javascript" src="${pageContext.servletContext.contextPath }/js/jquery-1.8.2.min.js">
</script>
<script type="text/javascript">
$(function(){
$(".btn").click(function(){
$.ajax({
url:"testJson",
type:"POST",
data:{},
dataType:"json",
success:function(msg){
$("body").append("<table border='1' style = 'text-align: center'></table>");
$("table").append("<tr><th>id</th><th>lastName</th><th>email</th><th>gender</th><th>departmentName</th></tr>");
for (var i in msg) {
var emp = msg[i];
$("table").append("<tr><td>"+emp.id+"</td><td>"+emp.lasrName+"</td><td>"+emp.email+"</td><td>"+emp.gender+"</td><td>"+emp.departmentName+"</td></tr>");
}
}
});
});
});
</script>
</head>
<body>
<input class="btn" type="button" value="测试ajax" />
<a href="testJson">测试JSON</a>
</body>
</html>
Controller层代码
package com.blh.test;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.blh.bean.Employee;
import com.blh.dao.EmployeeDao;
@Controller
public class TestJsonController {
@Autowired
private EmployeeDao employeeDao;
@RequestMapping(value = "/testJson")
@ResponseBody
public Collection<Employee> trstJson() {
Collection<Employee> emps = employeeDao.getAll();
return emps;
}
}