EasyUI之DataGrid分页
第一步创建分页DataGrid
<table id="dg"> <thead> <tr> <th data-options="field:'username',width:100">username</th> <th data-options="field:'password',width:100,editor:'textbox'">password</th> </tr> </thead> </table> <script type="text/javascript"> $(document).ready(function() { $("#dg").datagrid({ title : "用户管理", singleSelect : true, url : '${pageContext.request.contextPath}/manager_userData', toolbar : "#tb", width : "100%", height : "100%", pagination : true, //开启分页 onClickCell : onClickCell, }); $("#dg").datagrid("getPager").pagination({ pageSize : 3, //设置页面大小 pageList : [3, 10, 15, 20], //用户自定义页面大小数组 beforePageText : '第', afterPageText : '共{pages}页', displayMsg : '当前显示 {from} 到 {to} ,共{total}记录', }); }); </script>
DataGrid自带属性
1、pages:共有多少页
2、from:当前页面第一条记录
to:当前页面最后一条记录
3、total:总共多少条记录
4、rows:记录
DataGrid控件会根据后台传过来的JSON数据,自行设置这些属性
{"total":6,"pages":1,"rows":[{"addr":"","code":"","email":"","name":"","password":"aaa","phone":"","sex":"","state":0,"uid":2,"username":"aaa"},{"addr":"","code":"","email":"","name":"","password":"22","phone":"","sex":"","state":0,"uid":3,"username":"22"}]}
第二步后台操作
1、Hibernate获取分页数据(dao)
public List<User> findPagerUser() { Criteria criteria = this.getSession().createCriteria(User.class); criteria.setFirstResult(1); criteria.setMaxResults(2); List<User> list = criteria.list(); if (list != null && list.size() > 0) { return list; } return null; }
2、分页数据封装
import java.util.List; /** * 定义一个分页对象 */ public class Pager { private int page;// 当前页码 private int pageTotal;// 总页码 private int rows;// 每页显示条数 private int rowsTotal;// 总条数 private List<?> list;// 返回的数据集合 public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPageTotal() { return pageTotal; } public void setPageTotal(int pageTotal) { this.pageTotal = pageTotal; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getRowsTotal() { return rowsTotal; } public void setRowsTotal(int rowsTotal) { this.rowsTotal = rowsTotal; } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } @Override public String toString() { return "Pager [list=" + list + ", page=" + page + ", pageTotal=" + pageTotal + ", rows=" + rows + ", rowsTotal=" + rowsTotal + "]"; } }
3、构造JSON数据传给客户端(action)
public String getData() throws IOException { HttpServletResponse response = ServletActionContext.getResponse(); Pager pager = userService.findPagerUser(page, rows); if (pager.getList().size() > 0) { JsonConfig config = new JsonConfig(); config.setExcludes(new String[] { "comments" }); JSONArray json = JSONArray.fromObject(pager.getList(), config); JSONObject jsonObject = new JSONObject(); jsonObject.put("total", pager.getRowsTotal()); jsonObject.put("pages", pager.getPageTotal()); jsonObject.put("rows", json); response.getWriter().append(jsonObject.toString()); } return null; }
JSON参考:JSON入门