编写一个页面,点击按钮实现学生信息的异步加载,并展示到页面表格中
一、写一个名字为student.java的类;
public class Student { private Integer id; private String name; private Integer age; //指定对象以json格式传递时,显示的日期格式 ,优先级高于全局配置 @JsonFormat(pattern = "yyyy-MM-dd") private Date birthday; public Student(){ } public Student(Integer id, String name, Integer age, Date birthday) { this.id = id; this.name = name; this.age = age; this.birthday = birthday; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
二、在控制层中写一个StudentController的类;
@Controller public class StudentController { //@RequestBody:接收json数据,并封装到对象中 @ResponseBody//返回json数据 @RequestMapping("/list2") public List<Student> list2(@RequestBody(required = false) Student student){ System.out.println("获取到数据:"+student); ArrayList<Student> students=new ArrayList<>(); students.add(new Student(1,"乔丹",18,new Date())); students.add(new Student(1,"科比",19,new Date())); students.add(new Student(1,"詹姆斯",20,new Date())); return students; } }
三、编写一个jsp文件,用来展示学生信息;
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>学生列表页面</title> </head> <body> <form id="queryForm"> 姓名:<input type="text" name="name"/><br/> 年龄:<input type="text" name="age"/><br/> <input type="button" id="queryBtn" value="异步查询"/> </form> <table> <thead> <tr> <td>ID</td> <td>姓名</td> <td>年龄</td> <td>生日</td> </tr> </thead> <tbody id="dataTable1"> </tbody> </table> <%--js-404错误; 1)路径写错 2)没有编译到==>查看target目录是否有该目录的文件,maven==>clearn 3)springmvc没有配置default-servlet-handler 4)拦截器拦截 --%> <script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script> <script> $(function ($) { $("#queryBtn").click(function () { var obj={"name":$("input[name='name']").val(), "age":$("input[name='age']").val() }; $.ajax({ url:"${pageContext.request.contextPath}/list2", type:"post", date:JSON.stringify(obj),//$("#queryForm).serialize()==>name=xxx && age=xxx,contentType没有指定json时使用 dataType:"json", contentType:"application/json",//以json字符串的方法传递数据 success:function (result) { alert("查询成功"); console.log(result); var html=""; for (var i=0;i<result.length;i++){ html+="<tr>\n" + " <td>"+result[i].id+"</td>\n" + " <td>"+result[i].name+"</td>\n" + " <td>"+result[i].age+"</td>\n" + " <td>"+result[i].birthday+"</td>\n" + " </tr>" } console.log(html); $("#dataTable1").html(html);//替换tbody标签的html内容 } }) }) }) </script> </body> </html>