SpringMvc+Maven框架下简单分页实现
分页是开发中最基本但必不可少的部分,之前在学校也没有那么多数据,一直以来对分页也没怎么重视,都是用别人现成的,最近自己尝试着写了个分页模块,顺便记录下方便之后使用。具体实现主要从以下几个部分实现:
1.分页实体类
首先我们需要一个工具类,如下内容所示:
package com.cn.hnust.pojo;
import java.io.Serializable;
/**
* 分页
*/
public class Page implements Serializable {
private static final long serialVersionUID = -3198048449643774660L;
private int pageNow = 1; // 当前页数
private int pageSize = 4; // 每页显示记录的条数
private int totalCount; // 总的记录条数
private int totalPageCount; // 总的页数
@SuppressWarnings("unused")
private int startPos; // 开始位置,从0开始
@SuppressWarnings("unused")
private boolean hasFirst;// 是否有首页
@SuppressWarnings("unused")
private boolean hasPre;// 是否有前一页
@SuppressWarnings("unused")
private boolean hasNext;// 是否有下一页
@SuppressWarnings("unused")
private boolean hasLast;// 是否有最后一页
/**
* 通过构造函数 传入 总记录数 和 当前页
* @param totalCount
* @param pageNow
*/
public Page(int totalCount, int pageNow) {
this.totalCount = totalCount;
this.pageNow = pageNow;
}
/**
* 取得总页数,总页数=总记录数/总页数
* @return
*/
public int getTotalPageCount() {
totalPageCount = getTotalCount() / getPageSize();
return (totalCount % pageSize == 0) ? totalPageCount: totalPageCount + 1;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public int getPageNow() {
return pageNow;
}
public void setPageNow(int pageNow) {
this.pageNow = pageNow;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
/**
* 取得选择记录的初始位置
* @return
*/
public int getStartPos() {
return (pageNow - 1) * pageSize;
}
public void setStartPos(int startPos) {
this.startPos = startPos;
}
/**
* 是否是第一页
* @return
*/
public boolean isHasFirst() {
return (pageNow == 1) ? false : true;
}
public void setHasFirst(boolean hasFirst) {
this.hasFirst = hasFirst;
}
/**
* 是否有首页
* @return
*/
public boolean isHasPre() {
// 如果有首页就有前一页,因为有首页就不是第一页
return isHasFirst() ? true : false;
}
public void setHasPre(boolean hasPre) {
this.hasPre = hasPre;
}
/**
* 是否有下一页
* @return
*/
public boolean isHasNext() {
// 如果有尾页就有下一页,因为有尾页表明不是最后一页
return isHasLast() ? true : false;
}
public void setHasNext(boolean hasNext) {
this.hasNext = hasNext;
}
/**
* 是否有尾页
* @return
*/
public boolean isHasLast() {
// 如果不是最后一页就有尾页
return (pageNow == getTotalCount()) ? false : true;
}
public void setHasLast(boolean hasLast) {
this.hasLast = hasLast;
}
}
2.Mybatis xml 文件配置
在有了上述分页实体之后,接下来就需要在Mybatis XXmapper.xml文件中配置查询语句,具体思路是:
a. 查询出所有符合条件的结果总数
b.将查到的结果总数通过分页实体的构造函数传入,然后计算出分页参数
c.根据分页参数查询结果集返回
- 查询所有符合条件的记录条数
<select id="getCounts" resultType="int" parameterType="java.util.Map">
SELECT COUNT(*) FROM book
WHERE XX=查询条件
</select>
- 根据分页参数查询符合条件的list
<select id="getBookByPage" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from book WHERE (1=1
<include refid="bookParams" /> 这里自己的查询条件)
order by Id DESC
limit #{startPos--起始下标},#{pageSize--每页数量}
</select>
3.Controller –Service–Dao 层调用代码
- Controller 层代码
@RequestMapping("/getBookByPage")
public String getBookByPage(HttpServletRequest request, Model model,Book book, HttpSession session, Type type, Subtype sub) {
List<Book> bookList = new ArrayList<Book>();
int counts;// 分页记录总数
String pageNow = request.getParameter("pageNow");
String countString = request.getParameter("allcount");
Page page = null;
// 判断分页参数
Book bookParams = (Book) session.getAttribute("bookParams");
if (countString != null) {
counts = Integer.parseInt(countString);
book = bookParams;
} else {
counts = bookService.getCounts(book);
}
// 添加查询条件id name author publish type subtype
// System.out.println(book.getName() + "|" + book.getAuthor() + "|"
// + book.getPublish() + "|" + book.getType() + "|"
// + book.getSubtype());
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("id", book.getId());
condition.put("name", book.getName());
condition.put("publish", book.getPublish());
condition.put("type", book.getType());
condition.put("subtype", book.getSubtype());
if (pageNow != null && pageNow != "") {
page = new Page(counts, Integer.parseInt(pageNow));
} else {
page = new Page(counts, 1);
}
condition.put("startPos", page.getStartPos());
condition.put("pageSize", page.getPageSize());
bookList = this.bookService.getBookByPage(condition);
// System.out.println("list.size():" + bookList.size());
model.addAttribute("bookList", bookList);
model.addAttribute("page", page);
model.addAttribute("bookParams", book);
session.setAttribute("bookParams", book);
model.addAttribute("url", "/book/getBookByPage");
// 下面判断是否从删除页面跳转过来
String deleted = (String) session.getAttribute("bookDeleted");
// System.out.println(deleted);
if (deleted != null) {
model.addAttribute("bookDeleted", deleted);
session.removeAttribute("bookDeleted");
}
model.addAttribute("subList", subList);
return "book/list";
}
- Service 层代码
@Resource
private BookDao bookDao;
public int getCounts(Book book) {
// TODO Auto-generated method stub
return bookDao.getCounts(book);
}
public List<Book> getBookByPage(Map condition) {
// TODO Auto-generated method stub
return bookDao.getBookByPage(condition);
}
- Dao 层代码
int getCounts(Book book);
List <Book> getBookByPage(Map condition);
4.前端jsp页面代码
前端页面page,公用jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form action='<c:url value="${url}"></c:url>' method="post" id="pageTurnForm">
<c:if test="${page != null && page.totalPageCount >= 1}">
<tr >
<td colspan="11">
<div class="fr" style="margin-bottom:10px;">
<button type="button" id="sub" class="btn btn-default" onclick="javascript:jumpToPage();" style="float:right">跳转<!-- 跳转 --></button>
<input type="text" id="jump" class="form-control input-mini input-inline " maxlenght="5" style=" float:right;text-align:center; margin: 0px 6px 0px 0px;">
<div class="btn-group" style="float:right">
<c:choose>
<c:when test="${page.pageNow == 1}">
<button type="button" class="btn btn-default" disabled="disabled"> <i class="fa fa-angle-double-left"></i></button>
</c:when>
<c:otherwise>
<button type="button" class="btn btn-default" onclick="javascript:prevousPage();"> <i class="fa fa-angle-double-left"></i></button>
</c:otherwise>
</c:choose>
<button type="button" class="btn btn-default" disabled="disabled" onclick="javascript:jumpToPage();">第 ${page.pageNow} / ${page.totalPageCount} 页</button>
<c:choose>
<c:when test="${page.pageNow == page.totalPageCount}">
<button type="button" class="btn btn-default" disabled="disabled" > <i class="fa fa-angle-double-right"></i></button>
</c:when>
<c:otherwise>
<button type="button" class="btn btn-default" onclick="javascript:nextPage();"> <i class="fa fa-angle-double-right"></i></button>
</c:otherwise>
</c:choose>
</div>
</div>
</td>
</tr>
</c:if>
<c:if test="${page == null || page.totalCount == 0}">
<tr>
<td colspan="11" class="alert-danger"><i class="fa fa-info-circle"></i> 无相关查询结果!
</tr>
</c:if>
<input type="hidden" id="pageNow" name="pageNow"/>
<input type="hidden" id="allcount" name="allcount" value="${page.totalCount}"/>
</form>
<script type="text/javascript">
function jumpToPage(){
var jump=$("#jump").val();
var pageNow=${page.pageNow};
var pageTotal=${page.totalPageCount};
if(jump==""||jump>pageTotal||jump<1||isNaN(jump)){
showAlertModel("提示信息","请输入正确的页码!",null);
return false;
}else{
$("#pageNow").val(jump);
$("#pageTurnForm").submit();
}
}
function nextPage(){
var pageNow=${page.pageNow};
var pageTotal=${page.totalCount};
$("#pageNow").val(parseInt(pageNow)+1);
$("#pageTurnForm").submit();
}
function prevousPage(){
var pageNow=${page.pageNow};
var pageTotal=${page.totalCount};
$("#pageNow").val(parseInt(pageNow)-1);
$("#pageTurnForm").submit();
}
/*处理回车事件*/
jQuery(document).ready(function() {
$("#jump").keydown(function(event){
if(event.keyCode == 13){
$("#sub").click();
return false;
}else{
}
});
});
</script>
至此,分页功能已经完成,效果图如下: