后台部分
page类
public class Page<E> {
private int pageNum;
private int pageSize;
private int startRow;
private int endRow;
private long total;
private int pages;
private List<E> result;
public Page(int pageNum, int pageSize) {
this.pageNum = pageNum;
this.pageSize = pageSize;
this.startRow = pageNum > 0 ? (pageNum - 1) * pageSize : 0;
this.endRow = pageNum * pageSize;
}
public List<E> getResult() {
return result;
}
public void setResult(List<E> result) {
this.result = result;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getEndRow() {
return endRow;
}
public void setEndRow(int endRow) {
this.endRow = endRow;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
@Override
public String toString() {
return "Page{" +
"pageNum=" + pageNum +
", pageSize=" + pageSize +
", startRow=" + startRow +
", endRow=" + endRow +
", total=" + total +
", pages=" + pages +
'}';
}
}
分页拦截器
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class}),
@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class PageHelper implements Interceptor {
private static final Logger logger = Logger.getLogger(PageHelper.class);
public static final ThreadLocal<Page> localPage = new ThreadLocal<Page>();
/**
* 开始分页
* @param pageNum
* @param pageSize
*/
public static void startPage(int pageNum, int pageSize) {
localPage.set(new Page(pageNum, pageSize));
}
/**
* 结束分页并返回结果,该方法必须被调用,否则localPage会一直保存下去,直到下一次startPage
* @return
*/
public static Page endPage() {
Page page = localPage.get();
localPage.remove();
return page;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
if (localPage.get() == null) {
return invocation.proceed();
}
if (invocation.getTarget() instanceof StatementHandler) {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
// 分离代理对象链(由于目标类可能被多个拦截器拦截,从而形成多次代理,通过下面的两次循环
// 可以分离出最原始的的目标类)
while (metaStatementHandler.hasGetter("h")) {
Object object = metaStatementHandler.getValue("h");
metaStatementHandler = SystemMetaObject.forObject(object);
}
// 分离最后一个代理对象的目标类
while (metaStatementHandler.hasGetter("target")) {
Object object = metaStatementHandler.getValue("target");
metaStatementHandler = SystemMetaObject.forObject(object);
}
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
//分页信息if (localPage.get() != null) {
Page page = localPage.get();
BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
// 分页参数作为参数对象parameterObject的一个属性
String sql = boundSql.getSql();
// 重写sql
String pageSql = buildPageSql(sql, page);
//重写分页sql
metaStatementHandler.setValue("delegate.boundSql.sql", pageSql);
Connection connection = (Connection) invocation.getArgs()[0];
// 重设分页参数里的总页数等
setPageParameter(sql, connection, mappedStatement, boundSql, page);
// 将执行权交给下一个拦截器
return invocation.proceed();
} else if (invocation.getTarget() instanceof ResultSetHandler) {
Object result = invocation.proceed();
Page page = localPage.get();
page.setResult((List) result);
return result;
}
return null;
}
/**
* 只拦截这两种类型的
* <br>StatementHandler
* <br>ResultSetHandler
* @param target
* @return
*/
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler || target instanceof ResultSetHandler) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
/**
* 修改原SQL为分页SQL
* @param sql
* @param page
* @return
*/
private String buildPageSql(String sql, Page page) {
StringBuilder pageSql = new StringBuilder(200);
pageSql.append("select * from ( select temp.*, rownum row_id from ( ");
pageSql.append(sql);
pageSql.append(" ) temp where rownum <= ").append(page.getEndRow());
pageSql.append(") where row_id > ").append(page.getStartRow());
return pageSql.toString();
}
/**
* 获取总记录数
* @param sql
* @param connection
* @param mappedStatement
* @param boundSql
* @param page
*/
private void setPageParameter(String sql, Connection connection, MappedStatement mappedStatement,
BoundSql boundSql, Page page) {
// 记录总记录数
String countSql = "select count(0) from (" + sql + ")";
PreparedStatement countStmt = null;
ResultSet rs = null;
try {
countStmt = connection.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
setParameters(countStmt, mappedStatement, countBS, boundSql.getParameterObject());
rs = countStmt.executeQuery();
int totalCount = 0;
if (rs.next()) {
totalCount = rs.getInt(1);
}
page.setTotal(totalCount);
int totalPage = totalCount / page.getPageSize() + ((totalCount % page.getPageSize() == 0) ? 0 : 1);
page.setPages(totalPage);
} catch (SQLException e) {
logger.error("Ignore this exception", e);
} finally {
try {
rs.close();
} catch (SQLException e) {
logger.error("Ignore this exception", e);
}
try {
countStmt.close();
} catch (SQLException e) {
logger.error("Ignore this exception", e);
}
}
}
/**
* 代入参数值
* @param ps
* @param mappedStatement
* @param boundSql
* @param parameterObject
* @throws SQLException
*/
private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
Object parameterObject) throws SQLException {
ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler.setParameters(ps);
}
}
Service层查询方法
头尾加上拦截器的方法
public Page<Object> getxxx(object obj,int pageNumber,
int pageSize){
PageHelper.startPage(pageNumber,pageSize);
//调用dao查询方法
return PageHelper.endPage();
}
mybaits-config.xml中配置拦截器。加在setting的下面
<plugins>
<plugin interceptor="com.itssky.transport.pageHelper.PageHelper"></plugin>
</plugins>
control层方法
@RequestMapping("/getDate")
@ResponseBody
public String getDate(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "pageSize", defaultValue = "10") int pagesize) {
Page<Object> pageBean = roadOwnerService.getAll(page, pagesize);
String str = new Gson().toJson(pageBean);
return str;
}
前台部分
使用laypage插件,详细参数配置等见http://laypage.layui.com/
前台代码
后台json数据传到前台,样式为bootstrap
<html>
<head>
<script src="${base}laypage/laypage.js"></script>
<script type="text/javascript">
$(function (){
demo();
});
function demo(curr){
var pageSize = 2;
$.getJSON('后台请求地址', {
page: curr || 1,
pageSize: pageSize,
date: new Date()
},
function (res){
laypage({
cont: 'page1', //容器。值支持id名、原生dom对象,jquery对象。【如该容器为】:<div id="page1"></div>
pages: res.pages, //通过后台拿到的总页数
curr: curr || 1,
skin: 'molv', //皮肤
skip: true, //是否开启跳页
//first: '首页', //若不显示,设置false即可
//last: '尾页', //若不显示,设置false即可
//prev: '<', //若不显示,设置false即可
//next: '>', //若不显示,设置false即可
jump: function (obj,first) { //触发分页后的回调
if(!first){ //点击跳页触发函数自身,并传递当前页:obj.curr
demo(obj.curr);
}
}
});
$('#tbody').html(PackagData(res));
$('#total').html(res.total);
});
}
function PackagData(res){
var content="";
for(var i=0;i<res.result.length;i++){
content+="<tr><td>";
content+=res.result[i].code;
content+="</td><td>";
content+=res.result[i].codeName;
content+="</td><td>";
content+="<button class='btn btn-warning' οnclick=\"edit('" + res.result[i].code + "');\">修改</button>";
content+="<button class='btn btn-warning' οnclick=\"del('" + res.result[i].code + "');\">删除</button>";
content+="</td></tr>";
}
return content;
}
</script>
</head>
<body>
<table id="Result" class="table table-hover">
<tr>
<th>id</th>
<th>名称</th>
<th>操作</th>
</tr>
<tbody id="tbody">
</tbody>
</table>
<div id="con1" style="float:left ">总共<span id="total"></span>条记录</div>
<div id="page1" style="float:right "></div>
<br><br>
<button type="button" class="btn btn-info" id="add">新增</button>
</body>
</html>
效果如下