show_page.html:
script src="js/jquery-1.12.4.min.js">
</script>
<script>
var pageNo=1;
var pageSize=5;
var totalPageCount;
var totalRecordCount;
var str;
function sendAjaxRequest(pageNo,pageSize){
var html;
$.ajax({
url:"AnimalServlet2?method=findbypage",
method:"post",
data:{"pageNo":pageNo,"pageSize":pageSize},
dataType:"json",
success:function (text) {
console.log(text)
str="第"+text.pageNo+"页/共"+text.totalPageCount+"页,总记录数:"+text.totalRecordCount;
if (text.pageNo==1) {
$("#a1").hide();
}else if(text.pageNo==text.totalPageCount){
$("#a2").hide();
}else {
$("#a1").show();
$("#a2").show();
}
$.each(text.data,function (i,n) {
html+="<tr><td>"+n.aid+"</td><td>"+n.aname+"</td><td>"+n.sex+"</td><td>"+n.age+"</td><td>"+n.feetcount+"</td></tr>"
})
$("#td").html(html);
$("#sp").text(str);
}
})
}
$(function () {
sendAjaxRequest(1,5);
$("#a2").click(function () {
pageNo=pageNo+1;
sendAjaxRequest(pageNo,pageSize);
});
$("#a1").click(function () {
pageNo=pageNo-1;
sendAjaxRequest(pageNo,pageSize);
})
})
</script>
<body>
<table>
<tr>
<th>编号</th>
<th>名称</th>
<th>性别</th>
<th>年龄</th>
<th>脚数</th>
</tr>
<tbody id="td">
</tbody>
</table>
<a id="a1" href="#">上一页</a>
<a id="a2" href="#">下一页</a>
<span id="sp"></span>
</body>
</html>
AniamlServlet.java:
@WebServlet("/AnimalServlet2")
public class AnimalServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//中文处理
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//读取method方法
String method = req.getParameter("method");
//执行具体的方法入口
if ("findbypage".equals(method)) {
findByPage(req, resp);
}
}
private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收参数
int pageNo = 1;
int pageSize = 5;
pageNo = Integer.parseInt(req.getParameter("pageNo"));
pageSize = Integer.parseInt(req.getParameter("pageSize"));
//调用方法
AnimalDao dao = new AnimalDaoImpl(QueryRunnerCreator.getRunner());
PageModel<Animal> pm = dao.findByPage(pageNo, pageSize);
//写回数据
resp.getWriter().println(JSON.toJSON(pm));
resp.getWriter().flush();
resp.getWriter().close();
}
}