- 导入所需的jar包
jackson-annotations.jar
jackson-core.jar
jackson-databind.jar
导入的jar
Controller层面
package com.johnny.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.johnny.entity.Student;
@Controller
public class JsonController {
@ResponseBody //@ResponseBody告知SpringMVC这不是一个视图 而是一个Json数据
@RequestMapping("testJson")
public List<Student> testJson() {
Student stu1 = new Student(1,"zs",23);
Student stu2 = new Student(2,"ls",24);
Student stu3 = new Student(3,"ww",25);
List<Student> students = new ArrayList<>();
students.add(stu1) ;
students.add(stu2) ;
students.add(stu3) ;
return students;
}
}
测试页面
<%@ 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>
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$.post(
"testJson",
function(result){
for(var i = 0; i < result.length; i++)
alert(result[i].id+"-"+result[i].name+"-"+result[i].age)
}
);
});
});
</script>
</head>
<body>
<button type="button" id="btn" >提交</button>
</body>
</html>