05-EasyUI尚硅谷-datagrid
注:以下代码只用于测试演示,在实际开发中不会使用!
jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Datagrid</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.2.6/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.2.6/themes/icon.css"> <script type="text/javascript" src="js/jquery-easyui-1.2.6/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="js/jquery-easyui-1.2.6/jquery.easyui.min.js"></script> <script type="text/javascript" src="js/jquery-easyui-1.2.6/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript"> $(function() { // 2.使用datagrid(), 发起请求并展示列表 $("#userList").datagrid({ title: "用户列表", width: 1000, height: "auto", url: "UserServlet?method=findUserList", // 异步请求的地址 fitColumns: true, // 自适应列宽 // 表格的列,是个二维数组,数组中是一个个对象,field的value值要和POJO中的属性值一致 columns: [[ { field: "username", title: "用户名", width: 100 },{ field: "sex", title: "性别", width: 50 },{ field: "age", title: "年龄", width: 50 },{ field: "birthday", title: "生日", width: 150 },{ field: "city", title: "所属城市", width: 100 },{ field: "salary", title: "薪水", width: 100 },{ field: "starttime", title: "开始时间", width: 150 },{ field: "endtime", title: "结束时间", width: 150 },{ field: "description", title: "个人描述", width: 150 } ]] }); }); </script> </head> <body> <!-- 1.定义一个用户table --> <table id="userList"></table> </body> </html>
package sxt.easyui.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sxt.easyui.model.User; import sxt.easyui.util.DBHelper; import sxt.easyui.util.JsonUtil; import com.mysql.jdbc.PreparedStatement; @SuppressWarnings("serial") public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if ("saveUser".equals(method)) { //this.saveUser(req, resp); } else if ("findUserList".equals(method)) { // 查询用户列表 List<User> userList = this.findUserList(req, resp); if (userList != null && userList.size() > 0) { // 将userList转换成json字串数组 try { // 把List转换成JSON字串数组 String jsonStr = JsonUtil.Object2JsonStr(userList); // {"total":239,"rows":[{"":"","":""},{},{}]} String result = "{\"total\":"+userList.size()+",\"rows\":"+jsonStr+"}"; resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(result); } catch (Exception e) { e.printStackTrace(); } } } else { try { throw new Exception("请求失败!"); } catch (Exception e) { e.printStackTrace(); } } } // 获取用户列表 private List<User> findUserList(HttpServletRequest req, HttpServletResponse resp) { Connection conn = DBHelper.getConn(); String sql = "SELECT * FROM user"; PreparedStatement ps = (PreparedStatement) DBHelper.prepare(conn, sql); // 查询用户列表 List<User> userList = new ArrayList<User>(); try { ResultSet rs = ps.executeQuery(); while (rs.next()) { String username = rs.getString("username"); String sex = rs.getString("sex"); String age = String.valueOf(rs.getInt("age")); String birthday = rs.getString("birthday"); String city = rs.getString("city"); String salary = rs.getString("salary"); String starttime = rs.getString("starttime"); String endtime = rs.getString("endtime"); String description = rs.getString("description"); User user = new User(username, sex, age, birthday, city, salary, starttime, endtime, description); userList.add(user); } return userList; } catch (SQLException e) { e.printStackTrace(); } return null; } }
JsonUtil.java:
package sxt.easyui.util; import java.util.List; import net.sf.json.JSONArray; // json工具类 public class JsonUtil { // 把List转换成json字串数组 public static String Object2JsonStr(List<?> list) throws Exception { String jsonStr = null; if (list != null && list.size() > 0) { jsonStr = JSONArray.fromObject(list).toString(); } return jsonStr; } }
效果:
datagrid的其他属性:
如:frozenColumns、striped、nowrap、idField、loadMsg、rownumbers、singleSelect、sortName、sortOrder、remoteSort、rowStyler
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Datagrid</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.2.6/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.2.6/themes/icon.css"> <script type="text/javascript" src="js/jquery-easyui-1.2.6/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="js/jquery-easyui-1.2.6/jquery.easyui.min.js"></script> <script type="text/javascript" src="js/jquery-easyui-1.2.6/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript"> $(function() { // 2.使用datagrid(), 发起请求并展示列表 $("#userList").datagrid({ idField: "id", // 标识字段,只要创建数据表格,就要配置这一项 title: "用户列表", width: 800, height: 300, url: "UserServlet?method=findUserList", // 异步请求的地址 striped: true, // 隔行变色 nowrap: true, // 默认情况下,当数据在同一行放不下,会折行放很多行显示,设置为true,不管多长的数据都显示在一行 loadMsg: "正在加载,请稍等...", rownumbers: true, // 行号 singleSelect: true, // 只允许选择表格中的一行 // 字段排序 remoteSort: false, // 1.取消本地排序,本地排序,即后台json数据是什么顺序,将来在页面就按什么顺序展示 sortName: "salary", // 2.指定排序的列字段名称 sortOrder: "asc", // 3.指定是按升序还是降序排序,默认是asc,即升序 // 满足条件的行记录,改变其样式,如:年龄>22的行记录背景颜色改成:#FF83FA rowStyler: function(index, recode) { if (recode.age > 22) { return "background:#FF83FA"; } }, //fitColumns: true, // 自适应列宽 // 表格的列,是个二维数组,数组中是一个个对象,field的value值要和POJO中的属性值一致 frozenColumns: [[ // 冻结列特性(用于列比较多的情况)不能和fitColumns属性一起使用,否则看不到效果 { field: "username", title: "用户名", width: 100 } ]], columns: [[ { field: "sex", title: "性别", width: 50 },{ field: "age", title: "年龄", width: 50 },{ field: "birthday", title: "生日", width: 150 },{ field: "city", title: "所属城市", width: 100 },{ field: "salary", title: "薪水", width: 100 },{ field: "starttime", title: "开始时间", width: 150 },{ field: "endtime", title: "结束时间", width: 150 },{ field: "description", title: "个人描述", width: 150 } ]] }); }); </script> </head> <body> <!-- 1.定义一个用户table --> <table id="userList"></table> </body> </html>
效果:
datagrid的分页特性:
查看easyui的源码,后台查询列表返回的数据必须是以下格式:
{"total":28,"rows":[ {"productid":"FI-SW-01","unitcost":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"}, {"productid":"K9-DL-01","unitcost":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"}, {"productid":"RP-SN-01","unitcost":12.00,"status":"P","listprice":28.50,"attr1":"Venomless","itemid":"EST-11"}, {"productid":"RP-SN-01","unitcost":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"}, {"productid":"RP-LI-02","unitcost":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"}, {"productid":"FL-DSH-01","unitcost":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"}, {"productid":"FL-DSH-01","unitcost":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"}, {"productid":"FL-DLH-02","unitcost":12.00,"status":"P","listprice":63.50,"attr1":"Adult Female","itemid":"EST-16"}, {"productid":"FL-DLH-02","unitcost":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"}, {"productid":"AV-CB-01","unitcost":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"} ]}
包含了total合rows两个key,total表示总记录数,rows表示列表的json数组
006_datagrid.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Datagrid</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.2.6/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="js/jquery-easyui-1.2.6/themes/icon.css"> <script type="text/javascript" src="js/jquery-easyui-1.2.6/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="js/jquery-easyui-1.2.6/jquery.easyui.min.js"></script> <script type="text/javascript" src="js/jquery-easyui-1.2.6/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript"> $(function() { // 2.使用datagrid(), 发起请求并展示列表 $("#userList").datagrid({ idField: "id", // 标识字段,只要创建数据表格,就要配置这一项 title: "用户列表", width: 1000, height: 400, url: "UserServlet?method=findUserList", // 异步请求的地址 striped: true, // 隔行变色 nowrap: true, // 默认情况下,当数据在同一行放不下,会折行放很多行显示,设置为true,不管多长的数据都显示在一行 loadMsg: "正在加载,请稍等...", rownumbers: true, // 行号 singleSelect: true, // 只允许选择表格中的一行 // 字段排序 remoteSort: false, // 1.取消本地排序,本地排序,即后台json数据是什么顺序,将来在页面就按什么顺序展示 sortName: "salary", // 2.指定排序的列字段名称 sortOrder: "asc", // 3.指定是按升序还是降序排序,默认是asc,即升序 // 满足条件的行记录,改变其样式,如:年龄>22的行记录背景颜色改成:#FF83FA /* rowStyler: function(index, recode) { if (recode.age > 22) { return "background:#FF83FA"; } }, */ // ========================================================= // 分页 pagination: true, // 表示打开分页特性 pageList: [5,10,15,20,30,50], // 每页显示多少条记录,自定义 pageSize: 10, // 设置初始化一页显示的记录数 // ========================================================= fitColumns: true, // 自适应列宽 // 表格的列,是个二维数组,数组中是一个个对象,field的value值要和POJO中的属性值一致 frozenColumns: [[ // 冻结列特性(用于列比较多的情况)不能和fitColumns属性一起使用,否则看不到效果 { field: "username", title: "用户名", width: 100 } ]], columns: [[ { field: "sex", title: "性别", width: 50 },{ field: "age", title: "年龄", width: 50 },{ field: "birthday", title: "生日", width: 150 },{ field: "city", title: "所属城市", width: 100 },{ field: "salary", title: "薪水", width: 100 },{ field: "starttime", title: "开始时间", width: 150 },{ field: "endtime", title: "结束时间", width: 150 },{ field: "description", title: "个人描述", width: 150 } ]] }); }); </script> </head> <body> <!-- 1.定义一个用户table --> <table id="userList"></table> </body> </html>
UserServlet.java:【这里只是写上核心代码,其他的比如连接数据库,工具类请看之前的笔记】
查看浏览器后台:page和rows是前台自动发给后台的参数(page是当前页,rows是每页显示多少条记录,后台拿到这两个参数就可以实现分页),
当前台选择不同的分页操作时,这两个参数也会跟着改变,每一次改变都会发送一次请求来实现分页。这里的请求时datagrid中的url路径。
package sxt.easyui.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sxt.easyui.model.User; import sxt.easyui.util.DBHelper; import sxt.easyui.util.JsonUtil; import com.mysql.jdbc.PreparedStatement; @SuppressWarnings("serial") public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if ("saveUser".equals(method)) { this.saveUser(req, resp); } else if ("findUserList".equals(method)) { // 查询用户列表 List<User> userList = this.findUserList(req, resp); if (userList != null && userList.size() > 0) { // 将userList转换成json字串数组 try { // 把List转换成JSON字串数组 String jsonStr = JsonUtil.Object2JsonStr(userList); // {"total":239,"rows":[{"":"","":""},{},{}]} int total = this.getTotal(req, resp); String result = "{\"total\":"+total+",\"rows\":"+jsonStr+"}"; resp.setContentType("text/html;charset=utf-8"); //Thread.sleep(2000); // 测试用 resp.getWriter().write(result); } catch (Exception e) { e.printStackTrace(); } } } else { try { throw new Exception("请求失败!"); } catch (Exception e) { e.printStackTrace(); } } } // 获取总记录数 private int getTotal(HttpServletRequest req, HttpServletResponse resp) { Connection conn = DBHelper.getConn(); String sql = "SELECT COUNT(*) FROM user"; PreparedStatement ps = (PreparedStatement) DBHelper.prepare(conn, sql); int count = 0; ResultSet rs = null; try { rs = ps.executeQuery(); if (rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { DBHelper.close(rs); DBHelper.close(ps); DBHelper.close(conn); } return count; } // 获取用户列表 private List<User> findUserList(HttpServletRequest req, HttpServletResponse resp) { // 接收分页参数 int currentPage = Integer.parseInt(req.getParameter("page")); int pageSize = Integer.parseInt(req.getParameter("rows")); if (currentPage < 0 || pageSize < 0) { currentPage = 1; pageSize = 10; } Connection conn = DBHelper.getConn(); String sql = "SELECT * FROM user LIMIT ?,?"; PreparedStatement ps = (PreparedStatement) DBHelper.prepare(conn, sql); try { ps.setInt(1, (currentPage-1)*pageSize); ps.setInt(2, pageSize); } catch (SQLException e1) { e1.printStackTrace(); } // 查询用户列表 List<User> userList = new ArrayList<User>(); try { ResultSet rs = ps.executeQuery(); while (rs.next()) { String username = rs.getString("username"); String sex = rs.getString("sex"); String age = String.valueOf(rs.getInt("age")); String birthday = rs.getString("birthday"); String city = rs.getString("city"); String salary = rs.getString("salary"); String starttime = rs.getString("starttime"); String endtime = rs.getString("endtime"); String description = rs.getString("description"); User user = new User(username, sex, age, birthday, city, salary, starttime, endtime, description); userList.add(user); } return userList; } catch (SQLException e) { e.printStackTrace(); } return null; } // 新增用户 private void saveUser(HttpServletRequest req, HttpServletResponse resp) { // 接收表单数据 String username = req.getParameter("username"); String password = req.getParameter("password"); String sex = req.getParameter("sex"); String age = req.getParameter("age"); String birthday = req.getParameter("birthday"); String city = req.getParameter("city"); String salary = req.getParameter("salary"); String starttime = req.getParameter("starttime"); String endtime = req.getParameter("endtime"); String description = ""; try { description = new String(req.getParameter("description").getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 构建User对象 /*User user = new User(id, username, password, sex, age, birthday, city, salary, starttime, endtime, description);*/ // 插入记录 Connection conn = DBHelper.getConn(); String sql = "INSERT INTO user(username, password, sex, age, birthday, city, salary, starttime, endtime, description) " + "VALUES('"+username+"','"+password+"','"+sex+"','"+age+"','"+birthday+"','"+city+"','"+salary+"','"+starttime +"','"+endtime+"','"+description+"')"; PreparedStatement ps = (PreparedStatement) DBHelper.prepare(conn, sql); resp.setContentType("text/html;charset=utf-8"); String str = ""; try { // int a = 1/0; // 操作失败演示 int count = ps.executeUpdate(); // 用户添加成功后返回:{"status":"ok","message":"操作成功!"},失败返回:// 用户添加成功后返回:{"status":"error","message":"操作失败!"} if (count == 1) { str = "{\"status\":\"ok\",\"message\":\"操作成功!\"}"; } else { str = "{\"status\":\"error\",\"message\":\"操作失败!\"}"; } } catch (Exception e) { str = "{\"status\":\"error\",\"message\":\"操作失败!\"}"; e.printStackTrace(); } finally { // 不管操作成功或者失败,都会执行这里的代码 try { resp.getWriter().write(str); } catch (IOException e) { e.printStackTrace(); } DBHelper.close(ps); DBHelper.close(conn); } } }
效果: