17-EasyUI尚硅谷 - treegrid(依赖于datagrid)
类似于tree
效果:
增:
改:
删:
实现:
数据表:
CREATE TABLE `org` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `iconCls` varchar(20) DEFAULT NULL, `principal` varchar(10) DEFAULT NULL, `count` int(11) DEFAULT NULL, `description` varchar(100) DEFAULT NULL, `state` varchar(20) DEFAULT NULL, `parent_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
OrgServlet.java:
package sxt.easyui.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; 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 net.sf.json.JSONArray; import sxt.easyui.model.Org; import sxt.easyui.util.DBHelper; @SuppressWarnings("serial") public class OrgServlet 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 { try { String method = req.getParameter("method"); if ("getOrgListByParentId".equals(method)) { List<Org> orgList = this.getOrgListByParentId(req, resp); resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(JSONArray.fromObject(orgList).toString()); } else if ("save".equals(method)) { this.save(req, resp); } else if ("update".equals(method)) { this.update(req, resp); } else if ("delete".equals(method)) { this.deleteOrgsById(req, resp); } else { throw new Exception("请求失败!"); } } catch (Exception e) { e.printStackTrace(); } } // 删除 @SuppressWarnings("unused") private void delete(HttpServletRequest req, HttpServletResponse resp) throws Exception { int id = Integer.parseInt(req.getParameter("id")); String sql = "DELETE FROM org WHERE id=?"; Connection conn = DBHelper.getConn(); PreparedStatement ps = DBHelper.prepare(conn, sql); ps.setInt(1, id); int sum = ps.executeUpdate(); String result = "{\"status\":\"操作失败!\"}"; // {"status":"操作失败!"} if (sum == 1) { result = "{\"status\":\"操作成功!\"}"; } resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(result); DBHelper.close(ps); DBHelper.close(conn); } // 根据id删除node private void deleteOrgsById(HttpServletRequest req, HttpServletResponse resp) throws Exception { // 要删除的节点id String id = req.getParameter("id"); int nodeId = id==null ? -1 : Integer.parseInt(id); if (nodeId > 0) { deleteOrgById(req, resp, nodeId); // 输出 String result = "{\"status\":\"操作成功!\"}"; resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(result); } else { // 删除失败 String result = "{\"status\":\"操作失败!\"}"; resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(result); } } // 递归删除所有子节点 public void deleteOrgById(HttpServletRequest req, HttpServletResponse resp, int id) throws Exception { List<Org> orgs = this.getChildrenByParentId(id); for (Org cNode : orgs) { int cid = cNode.getId(); this.delete(cid); // 删了当前的孩子 // 继续查看当前被删的孩子还有没有孩子,有就继续删除 deleteOrgById(req, resp, cid); } this.delete(id); // 没有孩子,就把它自己删了 } // 执行删除操作 public void delete(int id) throws Exception { String sql = "DELETE FROM org WHERE id=?"; Connection conn = DBHelper.getConn(); PreparedStatement ps = DBHelper.prepare(conn, sql); ps.setInt(1, id); ps.executeUpdate(); } // 编辑 private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception { int id = Integer.parseInt(req.getParameter("id")); String name = req.getParameter("name"); int count = Integer.parseInt(req.getParameter("count")); String principal = req.getParameter("principal"); String description = req.getParameter("description"); String sql = "UPDATE org SET name=?,count=?,principal=?,description=? WHERE id=?"; Connection conn = DBHelper.getConn(); PreparedStatement ps = DBHelper.prepare(conn, sql); ps.setString(1, name); ps.setInt(2, count); ps.setString(3, principal); ps.setString(4, description); ps.setInt(5, id); int sum = ps.executeUpdate(); String result = "{\"status\":\"操作失败!\"}"; // {"status":"操作失败!"} if (sum == 1) { result = "{\"status\":\"操作成功!\"}"; } resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(result); DBHelper.close(ps); DBHelper.close(conn); } // 保存 private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception { int parentId = Integer.parseInt(req.getParameter("parentId")); String name = req.getParameter("name"); int count = Integer.parseInt(req.getParameter("count")); String principal = req.getParameter("principal"); String description = req.getParameter("description"); String sql = "INSERT INTO org(name,principal,count,description,parent_id) VALUES(?,?,?,?,?)"; Connection conn = DBHelper.getConn(); PreparedStatement ps = DBHelper.prepare(conn, sql); ps.setString(1, name); ps.setString(2, principal); ps.setInt(3, count); ps.setString(4, description); ps.setInt(5, parentId); int sum = ps.executeUpdate(); String result = "{\"status\":\"操作失败!\"}"; // {"status":"操作失败!"} if (sum == 1) { result = "{\"status\":\"操作成功!\"}"; } resp.setContentType("text/html;charset=utf-8"); resp.getWriter().write(result); DBHelper.close(ps); DBHelper.close(conn); } // 获取列表 private List<Org> getOrgListByParentId(HttpServletRequest req, HttpServletResponse resp) throws Exception { String parentId = req.getParameter("id"); if (parentId == null || "".equals(parentId)) { parentId = "999999"; } String sql = "SELECT * FROM org WHERE parent_id=?"; Connection conn = DBHelper.getConn(); PreparedStatement ps = DBHelper.prepare(conn, sql); ps.setString(1, parentId); ResultSet rs = ps.executeQuery(); List<Org> orgList = new ArrayList<Org>(); while (rs.next()) { Org org = new Org(); org.setId(rs.getInt("id")); org.setName(rs.getString("name")); org.setIconCls(rs.getString("iconCls")); org.setPrincipal(rs.getString("principal")); org.setCount(rs.getInt("count")); org.setDescription(rs.getString("description")); // 有孩子节点就收缩closed,否则就保持默认值open List<Org> orgs = this.getChildrenByParentId(org.getId()); if (orgs.size() > 0) { org.setState("closed"); } orgList.add(org); } DBHelper.close(rs); DBHelper.close(ps); DBHelper.close(conn); return orgList; } // 根据父id获取孩子节点列表 private List<Org> getChildrenByParentId(Integer id) throws Exception { String sql = "SELECT * FROM org WHERE parent_id=?"; Connection conn = DBHelper.getConn(); PreparedStatement ps = DBHelper.prepare(conn, sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); List<Org> orgList = new ArrayList<Org>(); while (rs.next()) { Org org = new Org(); org.setId(rs.getInt("id")); org.setName(rs.getString("name")); org.setIconCls(rs.getString("iconCls")); org.setPrincipal(rs.getString("principal")); org.setCount(rs.getInt("count")); org.setDescription(rs.getString("description")); //org.setState("closed"); orgList.add(org); } return orgList; } /* private int getChildrenByParentId(Integer id) throws Exception { String sql = "SELECT COUNT(*) FROM org WHERE parent_id=?"; conn = DBHelper.getConn(); ps = DBHelper.prepare(conn, sql); ps.setInt(1, id); rs = ps.executeQuery(); int count = 0; if (rs.next()) { count = rs.getInt(1); } return count; } */ }
016_treegrid.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>Treegrid</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"> var flag ; //判断走的是保存还是修改方法 $(function() { $('#tree_org').treegrid({ title:'组织机构列表', iconCls:'icon-ok', width:1000, height:400, nowrap: false, rownumbers: true, collapsible:true, url:'OrgServlet?method=getOrgListByParentId', idField:'id', //数据表格要有主键 treeField:'name', //treegrid 树形结构主键 text fitColumns:true , columns:[[ {field:'name',title:'机构名称',width:200} , {field:'count',title:'机构人数',width:120} , {field:'principal',title:'机构负责人',width:120} , {field:'description',title:'机构描述',width:120} ]], onContextMenu: function(e,row){ e.preventDefault(); //屏蔽浏览器的菜单 $(this).treegrid('unselectAll'); //清除所有选中项 $(this).treegrid('select', row.id); //选中状态 $('#mm').menu('show', { left: e.pageX, top: e.pageY }); } }); $('#btn1').click(function(){ if(flag == 'add'){ //保存方法 //1 前台保存 注意: 没有保存id, 应该刷新节点(从后台reload一遍) var node = $('#tree_org').treegrid('getSelected'); $('#tree_org').treegrid('append',{ parent:node.id , data:[{ name:$('#myform').find('input[name=name]').val(), count:$('#myform').find('input[name=count]').val(), principal:$('#myform').find('input[name=principal]').val(), description:$('#myform').find('textarea[name=description]').val() }] }); //2 后台保存 $.ajax({ type: 'post', url: 'OrgServlet?method=save', cache: false , dataType: 'text', data:{ parentId: node.id , name: $('#myform').find('input[name=name]').val(), count: $('#myform').find('input[name=count]').val(), principal: $('#myform').find('input[name=principal]').val(), description: $('#myform').find('textarea[name=description]').val() }, success:function(result){ var jsonObj = $.parseJSON(result); $.messager.show({ title: '提示信息' , msg: jsonObj.status }); // 刷新节点 : 刷新当前选中节点 $('#tree_org').treegrid('reload',node.id); } }); //3关闭窗口 $('#div1').dialog('close'); } else { $.ajax({ type:'post', url:'OrgServlet?method=update', cache:false , dataType:'text', data:{ id: $('#myform').find('input[name=id]').val() , name: $('#myform').find('input[name=name]').val(), count: $('#myform').find('input[name=count]').val(), principal: $('#myform').find('input[name=principal]').val(), description: $('#myform').find('textarea[name=description]').val() } , success:function(result){ var jsonObj = $.parseJSON(result); $.messager.show({ title: '提示信息' , msg: jsonObj.status }); //刷新节点 :如果当前选中的节点是叶子节点的话,刷新该节点的父亲 ,如果不是叶子节点,刷新当前选中节点即可 var node = $('#tree_org').treegrid('getSelected'); var parent = $('#tree_org').treegrid('getParent' , node.id); $('#tree_org').treegrid('reload' , parent.id); } }); //3关闭窗口 $('#div1').dialog('close'); } }); //关闭窗口 $('#btn2').click(function(){ $('#div1').dialog('close'); }); }); function append(){ flag='add'; //1清空表单数据 $('#myform').form('clear'); //2打开窗口 $('#div1').dialog('open'); } function update(){ flag='edit'; //1清空表单数据 $('#myform').form('clear'); //2填充表单回显数据 var node = $('#tree_org').treegrid('getSelected'); $('#myform').form('load',{ id: node.id , name: node.name , principal: node.principal, count: node.count , description: node.description }); //3打开窗口 $('#div1').dialog('open'); } function remove(){ $.messager.confirm("提示信息", "确认删除?", function(r){ if(r){ // 1前台删除 var node = $('#tree_org').treegrid('getSelected'); $('#tree_org').treegrid('remove',node.id); // 2后台删除 var url = "OrgServlet?method=delete"; var args = {"time": new Date(), "id": node.id}; $.post(url, args, function(result){ var jsonObj = $.parseJSON(result); $.messager.show({ title: '提示信息' , msg: jsonObj.status }); // 刷新 $('#tree_org').treegrid('unselectAll'); $('#tree_org').treegrid('reload'); }); } else { return; } }); } </script> </head> <body> <table id="tree_org"></table> <div id="div1" title="组合机构" class="easyui-dialog" style="width:400px;" closed=true modal=true > <form id="myform" method="post"> <input type="hidden" name="id"/> <table> <tr> <td align="right">新机构名称:</td> <td><input name="name"/></td> </tr> <tr> <td align="right">负责人:</td> <td><input name="principal"/></td> </tr> <tr> <td align="right">机构人数:</td> <td><input name="count"/></td> </tr> <tr> <td align="right">机构描述:</td> <td><textarea name="description" cols="30" rows="5"></textarea></td> </tr> <tr align="right"> <td colspan="2"> <a id="btn1" class="easyui-linkbutton">确定</a> <a id="btn2" class="easyui-linkbutton">取消</a> </td> </tr> </table> </form> </div> <div id="mm" class="easyui-menu" style="width:120px;"> <div onclick="append()" iconCls="icon-add">新增组织机构</div> <div onclick="update()" iconCls="icon-edit">修改组织机构</div> <div onclick="remove()" iconCls="icon-remove">删除组织机构</div> </div> </body> </html>