①导jar包
jackson-annotations-2.9.8.jar
jackson-core-2.9.8.jar
jackson-databind-2.9.8.jar
注意:这三个包版本要统一。
②编写请求处理方法,并返回数组或集合类型
请求处理类:SecondSpringDemo.java
@Controller
@RequestMapping(value = "/SecondSpringDemo")
public class SecondSpringDemo {
@ResponseBody
@RequestMapping("/testJson")
public List<Student> testJson(){
Student student1 = new Student(1, "aa", 11);
Student student2 = new Student(2, "bb", 22);
Student student3 = new Student(3, "cc", 33);
ArrayList<Student> students = new ArrayList<Student>();
students.add(student1);
students.add(student2);
students.add(student3);
return students;
}
}
注意,要想使返回的集合或数组在前端以JSON的形式被接收,就必须在请求处理方法前加入@ResponseBody
注解。
③测试
使用AJAX发送请求,并把响应结果以JSON的形式进行处理,如下:
index.jsp
<script type="text/javascript" src="js/jquery-3.2.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#testJson").click(function(){
$.post(
"SecondSpringDemo/testJson",
function(result){
$.each(result,function(i,item){
console.log(item.no+"-"+item.name+"-"+item.age)
});
}
);
});
});
</script>
<body>
ajax 的json测试!<br>
<input type="button" value="测试" id="testJson">
</body>
执行index.jsp中的测试按钮,运行结果如下
可以发现,SpringMVC能通过@ResponseBody
将返回的数组或集合转为JSON格式的数据供前端处理。