EasyUI-- datagrid分页详解

分页的英文是pagination,记住这个单词,因为会经常遇见。

在EasyUI框架下,datagrid使用分页简单到令人发指,只需要2点:

1,为table启用class=“easyui-datagrid”,这样table就成为了一个数据网格。

2,为table启用pagination=“true”,表示表格启用分页功能。

<table id="userTable" title="用户列表" class="easyui-datagrid" style="width:480px;height:240px"
		url="/EasyuiDemo/GetUsers" pagination="true" singleSelect="true">
	<thead>
		<tr>
			<th field="userId">用户ID</th>
			<th field="userName">用户名</th>
			<th field="userPassword">登录密码</th>
			
		</tr>
	</thead>
	</table>

对应界面如下:
这里写图片描述

可见启用分页后,会自动在下方生成一个页码显示、控制区域,包含每页显示个数、当前页码,第一页、最后一页、上一页、下一页等按钮。

接下来就是最重要的前后端交互了,在url="/EasyuiDemo/GetUsers" 中,网页数据加载请求会抛给/EasyuiDemo/GetUsers,重点是同时,会将每页显示个数和请求页码传给后端。第一次加载的情况,会传10,1给后端,如果在第一页点击下一个页按钮,就会传递10,2给后端,也就是说,后端直接处理请求信息即可,不必再费心客户到底要看第几页,这个逻辑EasyUI已封装了。

好,来看看/EasyuiDemo/GetUsers请求如何处理:

@WebServlet(urlPatterns="/GetUsers")
public class UserServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//请求页码、每页显示行数、偏移、总数
		int page,rows,offset,total;
		//获取
		String input_page=request.getParameter("page");
		page=(input_page==null)?1:Integer.parseInt(input_page);
		String input_rows=request.getParameter("rows");
		rows=(input_rows==null)?10:Integer.parseInt(input_rows);
		offset=(page-1)*rows;
		UserOperation operation=new UserOperation();
		total=operation.selectCount();
		List<User> users=operation.selectPage(offset, rows);
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
        jsonMap.put("total", total);//total键 存放总记录数,必须的  
        jsonMap.put("rows", users);//rows键 存放每页记录 list  
        String result = JSONObject.fromObject(jsonMap).toString();//格式化result   一定要是JSONObject  
		out.print(result);
		out.flush();
		out.close();
	}
}

这里面连接数据库的operation.selectPage(offset, rows);方法如下:

	public List selectPage(int offset,int size) {//注意返回值null和list.size()==0的区别
		MySQLHandler hand=new MySQLHandler();
		ResultSet rs=null;
		ArrayList<User> list=new ArrayList<User>();//返回值
		try {
			rs=hand.query("select user_id,user_name,user_password,role_id,role_name from "
					+"system_user u,system_role r where u.user_role=r.role_id "
					+" order by u.user_id limit "+offset+","+size);
			while(rs.next()){
				User one=new User();//返回值中的一个
				one.setUserId(rs.getInt("User_id"));
				one.setUserName(rs.getString("User_name"));
				one.setUserPassword(rs.getString("user_password"));
				Role role=new Role();
				role.setRoleId(rs.getInt("role_id"));
				role.setRoleName(rs.getString("role_name"));
				one.setUserRole(role);
				list.add(one);//添加到列表
			}
			return list;
		} catch (Exception ex) {
			new MyException(new Date(),ex.getMessage(),"UserOperation.selectPage异常");
			return null;
		}finally{
			hand.sayGoodbye();
		}
	}

OK,运行后效果如下,最后还有一个问题,就是用户角色的显示,因为角色是对应Role表,我们想要显示的话,应该是显示user.getUserRole().getRoleName(),显示角色名称,此时可以采用data-options=“field:‘userRole’,formatter:formatUserRole”,使每一行的该列加载时,调用:formatUserRole进行格式化工作。所以最终网页源码如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>EasyUI分页</title>
    <link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">
	<script type="text/javascript" src="easyui/jquery.min.js"></script>
	<script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>
	<script type="text/javascript">
		function formatUserRole(val,row){  
		    if(val) 
		    	return val.roleName;  
		    else 
		    	return "";  
		} 
	</script>
  </head>
  
  <body>
 	<table id="userTable" title="用户列表" class="easyui-datagrid" style="width:480px;height:240px"
		url="/EasyuiDemo/GetUsers" pagination="true" singleSelect="true">
	<thead>
		<tr>
			<th field="userId">用户ID</th>
			<th field="userName">用户名</th>
			<th field="userPassword">登录密码</th>
			<th data-options="field:'userRole',formatter:formatUserRole" >角色</th>
		</tr>
	</thead>
	</table>
  </body>
</html>

Ok,最终效果如下:
这里写图片描述


如有问题请扫码联系我
在这里插入图片描述

已标记关键词 清除标记
var columns = [[ { field:'ck',checkbox:true }, {field:'productcode',title:'商品代码',width:70,align:'left',sortable:true}, {field:'productdesc',title:'商品名称',width:70,align:'left',sortable:true}, {field:'barcode',title:'条形码',width:70,align:'left',sortable:true}, {field:'isWeight',title:'称重商品',width:70,align:'left',sortable:true,formatter:function(value){ if(value==1){ return "是"; } (value==0) { return "否"; } }}, {field:'retailprice',title:'零售价',width:50,align:'left',sortable:true}, {field:'tradeprice',title:'进货价',width:50,align:'left',sortable:true,hidden:true}, {field:'miniUnit',title:'最小单位',width:70,align:'left',sortable:true}, {field:'remarka',title:'拼音首字母',width:70,align:'left',sortable:true}, {field:'remarkb',title:'特殊类型',width:70,align:'left',sortable:true}, {field:'supplierid',title:'供应商',width:70,align:'left',sortable:true}, {field:'picUrl',title:'图片地址',width:70,align:'left' , formatter: function (value, rec) { if(value==null||value==""){ return "无图片"; }else{} return "<img width=30px heigth=30 src=<%=basePath %>allfields/allfieldsProductInfo/getProductPhoto.do?productcode="+rec.productcode+" ></img>"; }}, {field:'httpurl',title:'httpurl',width:70,align:'left'}, {field:'orderprice',title:'订货价格',width:70,align:'left',sortable:true}, {field:'quant',title:'商品上限',width:70,align:'left',sortable:true}, {field:'orderunit',title:'订货单位',width:70,align:'left',sortable:true}, {field:'synchrodata',title:'是否同步',width:70,align:'left',sortable:true}, {field:'productSpec',title:'商品规格',width:70,align:'left',sortable:true}, {field:'productType',title:'商品类型',width:70,align:'left',sortable:true}, {field:'packageBarcode',title:'整件条形码',width:70,align:'left',sortable:true}, {field:'packagePrice',title:'整件价格',width:70,align:'left',sortable:true}, {field:'packageUnit',title:'整件单位',width:70,align:'left',sortable:true}, {field:'packageNumber',title:'整件数量',width:70,align:'left',sortable:true}, {field:'operator',title:'操作人',width:50,align:'left',sortable:true}, {field:'operateTime',title:'操作时间',width:70,align:'left',sortable:true,formatter:function(value){ if(value!=null){ return value.substring(0, 19); }else{ return null; } }}, ]]; $('#tablegrid').datagrid({ singleSelect:false, selectOnCheck: true, checkOnSelect: true, url:'<%=basePath %>allfields/allfieldsProductInfo/findProductInfoPage.do', pagination:true, pageSize:50, idField:"productcode", columns:columns, striped:true, rownumbers:true, fit:true, toolbar:'#tb', pagination:true ,//这里添加页控件 onSortColumn:function(sort,order){ //alert(sort+","+order); var queryParams = { sort:sort, order:order, productdesc:$.trim($("#productdesc").val()), hiddenSupplierid_s:$("#hiddenSupplierid_s").val(), productcode:$.trim($("#productcode").val()), barcode:$.trim($("#barcode").val()), startDate:$('#startDate').datebox("getValue"), remarkb:$("#remarkb").combobox('getValue'), endDate:$('#endDate').datebox("getValue") }; $("#tablegrid").datagrid( "load" , queryParams ); $("#tablegrid").datagrid('unselectAll'); } });
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页