- laypage 分页实例
1.1 Controller 层代码
@RequestMapping(value = "pager",method = RequestMethod.GET)
public Map<String,Object> select(@RequestParam("pageIndex")int pageIndex,
@RequestParam("pageSize")int pageSize){
System.out.println(pageIndex+pageSize);
Map<String,Object> data=new HashMap<>();
List<Fundtype> fundtypes=fundtypeService.selectAll((pageIndex-1)*pageSize,pageSize);
int totalCount=fundtypeService.selectCount();
//总记录条数
data.put("totalCount",totalCount);
//总页数
data.put("total",(totalCount-1)/pageSize+1);
//当前页码
data.put("pageIndex",pageIndex);
//查询出来的记录
data.put("data",fundtypes);
return data;
}
在持久层分页查询出需要的数据和总记录条数,按以上代码封装数据传回前台。
1.2 前台代码
<table>
<tr>
<th>id</th>
<th>name</th>
</tr>
<tbody id="tbody"></tbody>
</table>
</div>
<div id="pager"></div>
pager是存放分页信息的容器,js中的ajax请求如下:
function load(pageIndex,pageSize) {
$.ajax({
type:"get",
url:"http://127.0.0.1:8087/api/pager?pageIndex="+pageIndex+"&pageSize="+pageSize,
dataType:"json",
success:function (data) {
console.log(data);
//分页
laypage({
//展示页码等信息的div的id
cont:"pager",
//总页数
pages:data.total,
//是否显示上一页(<为样式)
prev:"<",
//是否显示下一页
next:">",
//连续显示的分页数
groups:3,
//当前页码
curr:data.pageIndex,
//是否显示跳页
skip:true,
//主题
skin:"molv",
jump:function (obj,first) {
if(!first){
load(obj.curr,pageSize)
}
}
});
//展示数据
var htmlText="";
$.each(data.data,(index,obj)=>{
htmlText+=`
<tr>
<td>${obj.id}</td>
<td>${obj.name}</td>
</tr>
`
})
$("#tbody").empty();
$("#tbody").append(htmlText);
}
})
}
将当前页码 pageIndex 和页大小 pageSize 作为参数传入后台,并在 laypage 的 jump 回调中重复调用该 load 方法,即可完成分页。
页面展示效果如下:
2.lay-table 表格实例(自带分页)
2.1 lay-table使用起来比laypage要方便得多,controller层数据按如下方式封装:
@RequestMapping(value = "table",method = RequestMethod.GET)
public Map<String,Object> select2(@RequestParam("page")int pageIndex,
@RequestParam("limit")int pageSize){
Map<String,Object> data=new HashMap<>();
List<Fundtype> fundtypes=fundtypeService.selectAll((pageIndex-1)*pageSize,pageSize);
int totalCount=fundtypeService.selectCount();
data.put("code",0);
data.put("msg","");
//总记录条数
data.put("count",totalCount);
//查询出来的记录
data.put("data",fundtypes);
return data;
}
注意msg的值最好就用"",不然可能会出错。
2.2 前台代码如下:
<table id="layTable">
</table>
就一个空表格,没什么好说的。
2.3 js 代码如下:
layui.use('table', function(){
var table = layui.table;
table.render({
//对象表格的id
elem: '#layTable'
//请求路径
,url:'http://127.0.0.1:8087/api/table'
//数据
,cols: [[
{field:'id', width:80, title: 'ID', sort: true}
,{field:'name', width:80, title: '用户名'}
]]
//开启分页
,page: true
});
});
需要注意的是,开启分页后,url 中默认会向后台传两个参数,?page=1&limit=10。故上文中的controller层使用RequestParam注解可以获取这两个参数。page为当前页页码,limit为页大小。
另外若在数据注释下的field为后台封装的集合里对象的属性,title为表格中的表头。若有sort:true属性,则表格中相应的字段自带排序。
页面效果如下:
当改变右下角的页大小时,传入后台的limit参数会自动改变,非常方便。