修改HeroListServlet
由于HeroDAO中提供的list方法有两种,一种是无参数的,即显示全部数据的,一种是有参数的,即显示有限数据的,所以此时我们使用第二种带有参数的方法实现数据页面的分页。
代码如下:
package servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Hero;
import dao.HeroDAO;
/**
* Servlet implementation class HeroListServlet
*/
@WebServlet("/HeroListServlet")
public class HeroListServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从零开始计数
int start = 0, count = 5;
try {
//获取网页传来的start参数,用于进行start的记录
start = Integer.parseInt(request.getParameter("start"));
} catch (NumberFormatException e) {
// TODO: handle exception
e.printStackTrace();
}
//下一页
int next = start + count;
//上一页
int pre = start - count;
总共有多少个数据
int total = new HeroDAO().getTotal();
//专门用来存储最后一页的start值
int last;
//如果 总数%每页的数量==0,那么最后一页的start=total-count
if (total % count == 0)
last = total - count;
else
//否则的话,最后一页的start就等于total-(total % count)
last = total - total % count;
//首页
pre = pre < 0 ? 0 : pre;
next = next > last ? last : next;
//设置属性,以便在jsp页面中可以取到值
request.setAttribute("pre", pre);
request.setAttribute("next", next);
request.setAttribute("last", last);
//有限制地查询数据
List<Hero> heros = new HeroDAO().list(start, count);
request.setAttribute("heros", heros);
request.getRequestDispatcher("listHero.jsp").forward(request, response);
}
}
在jsp页面中,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html>
<script src="https://how2j.cn/study/js/jquery/2.0.0/jquery.min.js"></script>
<link href="https://how2j.cn/study/css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
<script src="https://how2j.cn/study/js/bootstrap/3.3.6/bootstrap.min.js"></script>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<script>
$(function(){
$("a").addClass("btn btn-default btn-xs");
});
</script>
<table style="width:500px; margin:44px auto" class="table table-striped table-bordered table-hover table-condensed" align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
<td>hp</td>
<td>damage</td>
<td>edit</td>
<td>delete</td>
</tr>
<c:forEach items="${heros}" var="hero" varStatus="st">
<tr>
<td>${hero.id}</td>
<td>${hero.name}</td>
<td>${hero.hp}</td>
<td>${hero.damage}</td>
<td><a href="editHero?id=${hero.id}">编辑</a></td>
<td><a href="deleteHero?id=${hero.id}">删除</a></td>
</tr>
</c:forEach>
</table>
<nav>
<ul class="pager">
<li><a href="?start=0">首 页</a></li>
<li><a href="?start=${pre}">上一页</a></li>
<li><a href="?start=${next}">下一页</a></li>
<li><a href="?start=${last}">末 页</a></li>
</ul>
</nav>
这样就实现了数据的简单分页了。