首先是DAO层
根据页数查询所有记录,返回List集合
/**
* 根据页数查询所有记录,返回List集合
* @param page
* @return
*/
public static List<Blog> getBlogsByPage(int page){
List<Blog> list = null;
try {
list = (List) qr.query(conn, "SELECT * FROM blog limit ?,3", new BeanListHandler(Blog.class),(page-1)*3);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return list;
}
返回行数
/**
* 返回行数
* @return
*/
public static int getLimit(){
Map<String, Object> map = null;
try {
map = qr.query(conn, "select count(*) from blog", new MapHandler());
} catch (SQLException e) {
throw new RuntimeException(e);
}
long i = (Long) map.entrySet().iterator().next().getValue();
int limit = (int) i;
return limit;
}
JSP部分
<table>
<thead>
<tr>
<th>用户</th><th>标题</th><th>内容</th><th>发布时间</th>
</tr>
</thead>
<tbody>
<!-- 根据从DAO中查询到的集合遍历记录 -->
<c:forEach items="${requestScope.blogs }" var="blog">
<tr>
<td>${blog.username }</td>
<td>${blog.title }</td>
<td>${blog.content }</td>
<td>${blog.time }</td>
</tr>
</c:forEach>
<tr>
<!-- 请求中带有page参数,代表页数 -->
<td><a href="${pageContext.request.contextPath}/Blogs/blogs?page=1">首页</a></td>
<td><a href="${pageContext.request.contextPath}/Blogs/blogs?page=${page-1}">上一页</a></td>
<td><a href="${pageContext.request.contextPath}/Blogs/blogs?page=${page+1}">下一页</a></td>
<td><a href="${pageContext.request.contextPath}/Blogs/blogs?page=${last}">末页</a></td>
</tr>
</tbody>
</table>
WEB后台处理部分
@Controller
@RequestMapping("Blogs")
public class Blogs {
@RequestMapping("blogs")
public String blogs(HttpServletRequest request , HttpServletResponse response,String page){
int paging;
//末页
int last;
//获取数据库总记录数
int limit = BlogDao.getLimit();
//设置末页
int i = limit%3;
if(i==0){
last = limit/3;
}else{
last = (limit/3)+1;
}
//判断请求参数page(当前页)
if(page==null||"".equals(page)){
//如果是第一次访问,页数设置为第一页
paging = 1;
}else{
//不是第一次访问,获取页数
paging = Integer.parseInt(page);
//如果当前页小于1,页数设置为1
if(paging<=1){
paging = 1;
}
//如果当前页大于末页,页数设置为末页
if(paging>=last){
paging = last;
}
}
//查询记录
List<Blog> list = BlogDao.getBlogsByPage(paging);
//存储记录,当前页,末页
request.setAttribute("blogs", list);
request.setAttribute("page", paging);
request.setAttribute("last", last);
return "jsp/blogs";
}
}