查询功能
1.新建查询listStudent.jsp页面
将index.jsp中的浏览学生的标签变为超链接连接到listStudent.jsp,在webapp目录下新建listStudent.jsp的文件
<%--
Created by IntelliJ IDEA.
User: Hou
Date: 2021/8/19
Time: 16:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme()+"://"+
request.getServerName()+":"+request.getServerPort()+
request.getContextPath()+"/";
%>
<html>
<head>
<title>查询学生ajax</title>
<base href="<%=basePath%>"/>
<script type="text/javascript" src="./js/jquery-3.6.0.js"></script>
<script type="text/javascript"></script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
</div>
</body>
</html>
2.编写Controller层
在StudentController中编写
//处理查询 json数据
@RequestMapping(value = "/queryStudent.do")
@ResponseBody
public List<Student> queryStudent(){
//参数检查,简单的数据处理
List<Student> students = service.findStudents();
return students;
}
调用service中的findStudents()方法。
在此时可以直接在浏览器中直接访问Controller中的地址查看是否有返回 的json数据
然后编写jsp
在使用js的时候是静态资源所以需要zaispringmvc的配置文件中加入
<mvc:default-servlet-handler />
<%--
Created by IntelliJ IDEA.
User: Hou
Date: 2021/8/19
Time: 16:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme()+"://"+
request.getServerName()+":"+request.getServerPort()+
request.getContextPath()+"/";
%>
<html>
<head>
<title>查询学生ajax</title>
<base href="<%=basePath%>"/>
<script type="text/javascript" src="./js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function(){
loadStudentData();
$("#btnLoader").click(function (){
loadStudentData()
})
})
function loadStudentData(){
$.ajax({
url:"student/queryStudent.do",
type:"get",
dataType:"json",
success:function (data){
//清除旧数据
$("#info").html("");
//增加新的数据
$.each(data,function (i,n){
$("#info")
.append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.name+"</td>")
.append("<td>"+n.age+"</td>")
.append("</tr>")
})
}
})
}
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
<tr>
<td></td>
</tr>
</tbody>
</table>
<input type="button" id="btnLoader" value="查询数据">
</div>
</body>
</html>