前段时间,实习时候接到一个任务,将原有后台处理留言的的所有的一级分类改版成一级分类二级分类,在试验了大半个月之后,终于用treetable勉强的实现了,上面的一章节已经说过了,但是项目经理说我那个实现的不能拖动排序,哎,人为刀俎,我为鱼肉,没办法,硬着头皮换,幸好组里有一个项目经理的帮忙实现了easyUI treegrid 现在将流程大致的步骤记录在案,以防遗忘。公司的项目是ssh三层框架,现在我对这个业务流程还是不太熟悉,准备这几天系统的看看怎么样实现的这个框架,然后再结合实际的案例做一个简单的demo,时间过的太快了,马上研究生就要开题了,我现在什么都没准备,要看看自然语言处理的一些方面的内容了,现在真是会的东西太少,要学的东西太多 首先我们改动的是后台处理分类的catalogAction 代码如下
/* * CatalogAction.java created on Apr 10, 2014 3:05:43 AM by Martin */ package com.trs.space.comment.web.action.admin; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import org.junit.runners.Parameterized.Parameters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.trs.space.comment.ThreadContext; import com.trs.space.comment.domain.AdminUser; import com.trs.space.comment.domain.Catalog; import com.trs.space.comment.domain.CatalogFilter; import com.trs.space.comment.domain.Template; import com.trs.space.comment.manager.CatalogManager; import com.trs.space.comment.service.RightException; import com.trs.space.comment.service.RightService; import com.trs.space.comment.service.RightService.Right; import com.trs.space.comment.util.RequestUtil; /** * 总理留言分类管理 * * @author Martin */ @Controller public class CatalogAction { RightService rightService; CatalogManager catalogManager; @Autowired public void setRightService(RightService rightService) { this.rightService = rightService; } @Autowired public void setCatalogManager(CatalogManager catalogManager) { this.catalogManager = catalogManager; } @RequestMapping(value = "/catalogList",method = RequestMethod.GET) public ModelAndView view() throws RightException { rightService.assertRight(Right.SUGGEST_ADMIN); ModelAndView mav = new ModelAndView("catalogList");//取得所有留言分类的视图层 return mav; } @RequestMapping(value = "/catalogListItem",method = {RequestMethod.POST,RequestMethod.GET}) @ResponseBody //得到所有的分类集合 public String catalogList( HttpServletRequest request,HttpServletResponse response) throws RightException { rightService.assertRight(Right.SUGGEST_ADMIN); CatalogFilter filter = new CatalogFilter(); filter.setLevel(0); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); filter.sortBySortid(false); List<Catalog> list = catalogManager.listCatalog(filter); // int sum=list.size(); // System.out.println(sum); for (Catalog catalog : list) { catalog.setCreatedTime(sdf.format(catalog.getCreateTime()));//将时间格式化 catalog.setCreateTime(null);//原有的时间转化成json时设置为null } for (Catalog catalog : list) { if(catalog.getParentId()==null){ // 得到所有的父类节点 CatalogFilter filter1 = new CatalogFilter(); filter1.setParentId(catalog.getId()); //System.out.println(catalog.getId()); filter1.sortBySortid(false); List<Catalog> childrenlist = catalogManager.listCatalog(filter1);//根据父类节点得到所有的子类节点 if(childrenlist.size()>0){ for (Catalog catalog1 : childrenlist) { catalog1.setCreatedTime(sdf.format(catalog1.getCreateTime())); catalog1.setCreateTime(null); } catalog.setState("closed");//与前台的easyUI一致性保持 } else { catalog.setState("open"); } catalog.setChildren(childrenlist); } } List<Catalog> result=new ArrayList<Catalog>(); for (Catalog catalog : list) { if(catalog.getParentId()==null){ result.add(catalog); } } // Map<String, Object> jsonResult = new HashMap<String, Object>(); // jsonResult.put("total", sum); // jsonResult.put("rows", result); // Map<String, Object> foot = new HashMap<String, Object>(){ // { // put("name","Total Persons:"); // put("persons",7); // put("iconCls","icon-sum"); // } // }; // jsonResult.put("footer",foot); JSONArray jsonArray= JSONArray.fromObject(result);//将父类节点全部转换成json格式的 response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(jsonArray); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping(value = "/catalogGet", method = RequestMethod.POST) @ResponseBody public String Getcatalog(@RequestParam(value = "id", required = true) Long id,HttpServletResponse response) throws RightException { rightService.assertRight(Right.SUGGEST_ADMIN); Catalog catalog = null; if (id != null) { catalog = catalogManager.getCatalog(id); } else { catalog = new Catalog(); } try { response.getWriter().print(JSONArray.fromObject(catalog).toString());//子类节点转换成json格式的 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping(value = "/catalogEdit", method = RequestMethod.POST) @ResponseBody public String catalogEdit( @RequestParam(value = "title" ,required =true) String title, @RequestParam(value = "sortid", required = true) String sortid, @RequestParam(value = "id", required = false) Long id, @RequestParam(value = "parentId",required=false) Long parentId, HttpServletRequest request) throws RightException { rightService.assertRight(Right.SUGGEST_ADMIN); Catalog catalog = null; //catalog = catalogManager.getCatalog(id); if (id != null && id.longValue() > 0) { catalog = catalogManager.getCatalog(id); } else { AdminUser adminUser = ThreadContext.getUser().getAdminUser(); catalog = new Catalog(); //catalog.setParentId(parentId); if (parentId != -1 && parentId.longValue() > 0) { catalog.setLevel(Integer.valueOf(1)); catalog.setParentId(parentId); } else { catalog.setLevel(Integer.valueOf(0)); } catalog.setCreateTime(new Date()); catalog.setCreatorNick(adminUser.getNickName()); catalog.setCreatorId(adminUser.getId()); catalog.setStatus(Template.STATUS_NORMAL); } //System.out.println(title+","+id+","+sortid); catalog.setTitle(title); Integer sortId = RequestUtil.getParameterAsInt(request, "sortid", Integer.MIN_VALUE); if (Integer.MIN_VALUE == sortId) { sortId = getSecondFrom2014(); } catalog.setSortid(sortId); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 catalog.setModifyTime(new Date()); try { catalogManager.saveCatalog(catalog); return "{\"result\": \"true\"}"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "{\"result\": \"true\"}"; } /* 删除节点*/ @RequestMapping(value = "/catalogDelete",method=RequestMethod.POST) @ResponseBody public String catalogDelete(@RequestParam(value = "id", required = true) Long id) throws RightException { rightService.assertRight(Right.SUGGEST_ADMIN); CatalogFilter filter = new CatalogFilter(); if (id != null) { filter.setParentId(id); //SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); filter.sortBySortid(false); List<Catalog> list = catalogManager.listCatalog(filter); //System.out.println(","+list.get(0).getId()); if(list.size()>0){ long[] ids= new long[list.size()]; ids[list.size()-1] = id; for (int i=0;i<list.size();i++) {//就是这里 ids[i]=list.get(i).getId(); } catalogManager.deleteCatalog(ids); } else{ long[] ids= new long[1]; ids[0]=id; catalogManager.deleteCatalog(ids); } return "{\"result\": \"true\"}"; } else return "{\"result\": \"true\"}"; } /* 更新排序*/ @RequestMapping(value = "/updateCatalogList",method=RequestMethod.POST) @ResponseBody public String updateCatalogList(@RequestParam(value="srcId",required=true) Long srcId, @RequestParam(value="destId",required=true) Long destId) throws RightException { rightService.assertRight(Right.SUGGEST_ADMIN); System.out.println(srcId+","+destId); Catalog Begin = catalogManager.getCatalog(srcId); Catalog End = catalogManager.getCatalog(destId); if(Begin.getParentId()==End.getParentId()){ //if(Begin.getParentId()==null){ //同级父节点移动 try { CatalogFilter filter1 = new CatalogFilter(); filter1.setParentId(Begin.getParentId()); //System.out.println(catalog.getId()); filter1.sortBySortid(false); List<Catalog> childrenlist = catalogManager.listCatalog(filter1); { childrenlist.remove(Begin); Integer sortid=0; for(Catalog catalog:childrenlist) { System.out.println(catalog.getSortid()); // sortid=catalog.getSortid(); if(catalog.getSortid()==End.getSortid()){ sortid=catalog.getSortid()+1; Begin.setSortid(sortid); catalogManager.saveCatalog(Begin); sortid++; } else { catalog.setSortid(sortid); catalogManager.saveCatalog(catalog); sortid= sortid+1; } } } return "{\"result\": \"true\"}"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //return "{\"result\": \"true\"}"; //} // else { // // } // } else { //靓机电节点的移动 } return "{\"result\": \"false\"}"; } private int getSecondFrom2014() { Calendar cal = Calendar.getInstance(); long now = cal.getTimeInMillis(); cal.set(Calendar.YEAR, 2014); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, 2014); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long org = cal.getTimeInMillis(); long sec = (now - org) / 1000; return (int) sec; } }
前台方面我们引入了easyUI treegrid 包,然后在此基础上改动 下面是 catalogList.jsp 页面
<%@page import="com.trs.space.comment.Constants"%> <%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/jsp/include/taglibs.jsp"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="../css/jquery.kiketable.colsizable.css"> <link rel="stylesheet" type="text/css" href="../css/admin_base.css"> <script language="javascript" type="text/javascript" charset="utf-8" src="../js/jquery-1.4.4.min.js"></script> <script language="javascript" type="text/javascript" charset="utf-8" src="../js/jquery.event.drag-1.4.js"></script> <script language="javascript" type="text/javascript" charset="utf-8" src="../js/jquery.kiketable.colsizable.js"></script> <script language="javascript" type="text/javascript" charset="utf-8" src="../js/admin_base.js"></script> <link rel="stylesheet" type="text/css" href="../css/treegrid/default/easyui.css"> <link rel="stylesheet" type="text/css" href="../css/treegrid/icon.css"> <link rel="stylesheet" type="text/css" href="../css/treegrid/treegrid.css"> <script type="text/javascript" src="../js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="../js/jquery.easyui.min.js"></script> <script type="text/javascript" src="../js/treegrid-dnd.js"></script> <script type="text/javascript"> var data=[{ "id":1, "name":"C", "size":"", "date":"02/19/2010", "children":[{ "id":2, "name":"Program Files", "size":"120 MB", "date":"03/20/2010", "children":[{ "id":21, "name":"Java", "size":"", "date":"01/13/2010", "state":"closed", "children":[{ "id":211, "name":"java.exe", "size":"142 KB", "date":"01/13/2010" },{ "id":212, "name":"jawt.dll", "size":"5 KB", "date":"01/13/2010" }] },{ "id":22, "name":"MySQL", "size":"", "date":"01/13/2010", "state":"closed", "children":[{ "id":221, "name":"my.ini", "size":"10 KB", "date":"02/26/2009" },{ "id":222, "name":"my-huge.ini", "size":"5 KB", "date":"02/26/2009" },{ "id":223, "name":"my-large.ini", "size":"5 KB", "date":"02/26/2009" }] }] },{ "id":3, "name":"eclipse", "size":"", "date":"01/20/2010", "children":[{ "id":31, "name":"eclipse.exe", "size":"56 KB", "date":"05/19/2009" },{ "id":32, "name":"eclipse.ini", "size":"1 KB", "date":"04/20/2010" },{ "id":33, "name":"notice.html", "size":"7 KB", "date":"03/17/2005" }] }] }]; $(function(){ //初始化弹出对话框 $('#win').window('close'); $('#tt').treegrid({ // data:data, url:'catalogListItem', method:'post', dataType:'json', rownumbers: true, singleSelect:true, idField: 'id', treeField: 'title', animate:true, columns:[[ {field:'id',title:'ckc',checkbox:true}, {field:'title',title:'分类名称',width:400,align:'left',editor:'text'}, {field:'sortid',title:'排序值',width:100,align:'left',editor:'text'}, {field:'creatorNick',title:'创建者',width:100}, {field:'createdTime',title:'创建时间',width:220}, {field:'operate',title:'操作',width:220, formatter: function(value,row,index){ var html=''; html+='<a onclick="showedit(\'编辑\','+row.id+')" >编辑 </a> '; //html+=value+'<a onclick="editrow('+row+')" >编辑 </a> <a id="cancel" onclick="cancel()"></a>'; if(row.level==0){ html+=' <a href="#" onclick="Confirm(\'确认删除这个分类及其子类\','+row.id+')">删除</a> '; html+='<a href="#" onclick="showedit(\'新建\','+row.id+')">新建子节点</a> ';//默认只有二级节点 } else html+=' <a href="#" onclick="Confirm(\'确认删除这个记录\','+row.id+')">删除</a> '; return html; } } ]], onLoadSuccess: function(row){ //$(this).treegrid('enableDnd', row?row.id:null); enableDnd($('#tt')); } }); }); function enableDnd(t) { var nodes = t.treegrid('getPanel').find('tr[node-id]'); nodes.find('span.tree-hit').bind('mousedown.treegrid', function() { return false; }); nodes.draggable({ disabled: false, revert: true, cursor: 'pointer', proxy: function(source) { var p = $('<div class="tree-node-proxy tree-dnd-no"></div>').appendTo('body'); p.html($(source).find('.tree-title').html()); p.hide(); return p; }, deltaX: 15, deltaY: 15, onBeforeDrag: function() { $(this).next('tr.treegrid-tr-tree').find('tr[node-id]').droppable({ accept: 'no-accept' }); }, onStartDrag: function() { $(this).draggable('proxy').css({ left: -10000, top: -10000 }); }, onDrag: function(e) { $(this).draggable('proxy').show(); this.pageY = e.pageY; }, onStopDrag: function() { $(this).next('tr.treegrid-tr-tree').find('tr[node-id]').droppable({ accept: 'tr[node-id]' }); } }).droppable({ accept: 'tr[node-id]', onDragOver: function(e, source) { var pageY = source.pageY; var top = $(this).offset().top; var bottom = top + $(this).outerHeight(); $(source).draggable('proxy').removeClass('tree-dnd-no').addClass('tree-dnd-yes'); $(this).removeClass('row-append row-top row-bottom'); if (pageY > top + (bottom - top) / 2) { if (bottom - pageY < 5) { $(this).addClass('row-bottom'); } else { $(this).addClass('row-append'); } } else { if (pageY - top < 5) { $(this).addClass('row-top'); } else { $(this).addClass('row-append'); } } }, onDragLeave: function(e, source) { $(source).draggable('proxy').removeClass('tree-dnd-yes').addClass('tree-dnd-no'); $(this).removeClass('row-append row-top row-bottom'); }, onDrop: function(e, source) { var action, point; if ($(this).hasClass('row-append')) { action = 'append'; } else { action = 'insert'; point = $(this).hasClass('row-top') ? 'top' : 'bottom'; } $(this).removeClass('row-append row-top row-bottom'); // alert(action + ":" + point); // your logic code here // do append or insert action and reload the treegrid data var src = $('#tt').treegrid('find', $(source).attr('node-id')); var dest = $('#tt').treegrid('find', $(this).attr('node-id')); // alert(src.title+","+dest.title); $.ajax({ url: 'updateCatalogList', dataType: 'json', type:'post', data: { "srcId": src.id, "destId": dest.id }, success:function(data){ if(data.result) { $('#tt').treegrid('reload'); } } }); } }); } function showedit(type,id){ $("#form")[0].reset(); $('#win').window('open'); if(type=='编辑'){ $.ajax({ url:'catalogGet?id='+id, type:'post', dataType:'json', cache:false, success:function(data){ $("#title").val(data[0].title); $("#sortid").val(data[0].sortid); $("#id").val(id); } }); } else { $("#parentId").val(id); } } //保存 function save(){ var title= $("#title").val(); var sortid=$("#sortid").val(); var id=$("#id").val(); var parentId=$("#parentId").val(); $.ajax({ url:'catalogEdit', data:{"title":title,"sortid":sortid,"id":id,"parentId":parentId}, type:'post', dataType:'json', success: function(data) { if(data.result){ $('#win').window('close'); $('#tt').treegrid('reload'); } else alert(data.result); } }); } function Confirm(msg,id) { $.messager.confirm("确认", msg, function (r) { if (r) { //请求 $.ajax({url:'catalogDelete?id='+id, type:'post', dataType: 'json', success:// function (data) { if(data){ $('#tt').treegrid('reload'); } else alert("faile"); } }); } }); return false; } </script> <title>留言分类浏览</title> </head> <body> <div id="win" title="新建/编辑分类" class="easyui-window" style="width:300px;height:180px;"> <form id="form" style="padding:10px 20px 10px 40px;"> <p>分类名称: <input id="title" name="title" type="text"></p> <p>排序值: <input id="sortid" name="sortid" type="text"></p> <input id="id" name="id" type="hidden"> <input id="parentId" name="parentId" type="hidden"> <div style="padding:5px;text-align:center;"> <a href="#" class="easyui-linkbutton" icon="icon-ok" onclick="save()">确定</a> <a href="#" class="easyui-linkbutton" icon="icon-cancel" onclick="javascript: $('#win').window('close');">取消</a> </div> <input id="id" name="id" type="hidden"> </form> </div> <table id="head_table" cellpadding="0" cellspacing="0" > <tr> <td id="head_where"><a href="./">后台管理</a> >> 留言分类浏览</td> <td id="head_what"></td> <td id="head_who"><%UserInfo info = (UserInfo) request.getSession().getAttribute(Constants.BIND_USER_INFO); %><%=info.getAdminUser().getNickName() %></td> <td id="head_tree"><div class="tree_on"></div></td> <td id="head_search"><form id="form_search" action="search"> <input id="head_search_input" type="text" name="query"> <input id="head_search_button" type="image" src="../imgs/head_search_button.gif" title="搜索"> </form> </td> </tr> </table> <table id="main_table" cellpadding="0" cellspacing="0"> <tr> <td id="left_nav_td"> <%@include file="include/left_navigate.jsp" %> </td> <td id="main_area"><div id="main_area_box"><div id="main_area_box_inner"> <div class="tip_box"> <div class="tip_head"> <span class="tip_head_info">留言分类浏览</span> </div> <div class="tip_body"> <div class="tip_body_info">浏览所有的留言分类。</div> <div class="tip_body_link"> <c:if test="${!empty parentId}"> <a href="catalogList">返回父级分类</a> </c:if> <a href="#" onclick="showedit('新建',-1)">新建留言分类</a> </div> </div> </div> <%@include file="include/tips_warn_err.jsp" %> <form action="" id="list_form" name="list_form" method="get"> <div class="list_box"> <table id="tt" class="easyui-treegrid" cellpadding="0" cellspacing="0" border="0" style="width100%;height:450px"></table> </div> </form> </div></div></td> </tr> </table> <%@include file="include/foot_version.jsp/" %> </body> </html>
其中还有一个编辑的页面的实现 catalogEdit.jsp
<%@page import="com.trs.space.comment.Constants"%> <%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/jsp/include/taglibs.jsp"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="../css/admin_base.css" rel="stylesheet" type="text/css"> <script language="javascript" type="text/javascript" charset="utf-8" src="../js/jquery-1.4.4.min.js"></script> <script language="javascript" type="text/javascript" charset="utf-8" src="../js/admin_base.js"></script> <title>添加/修改留言分类</title> </head> <body> <table id="head_table" cellpadding="0" cellspacing="0" > <tr> <td id="head_where"><a href="./">后台管理</a> >> 添加/修改留言分类</td> <td id="head_what"></td> <td id="head_who"><%UserInfo info = (UserInfo) request.getSession().getAttribute(Constants.BIND_USER_INFO); %><%=info.getAdminUser().getNickName() %></td> <td id="head_tree"><div class="tree_on"></div></td> <td id="head_search"><form id="form_search" action="search"> <input id="head_search_input" type="text" name="query"> <input id="head_search_button" type="image" src="../imgs/head_search_button.gif" title="搜索"> </form></td> </tr> </table> <table id="main_table" cellpadding="0" cellspacing="0"> <tr> <td id="left_nav_td"> <%@include file="include/left_navigate.jsp" %> </td> <td id="main_area"><div id="main_area_box"><div id="main_area_box_inner"> <div class="tip_box"> <div class="tip_head"> <span class="tip_head_info">添加/修改留言分类</span> </div> <div class="tip_body"> <div class="tip_body_info">添加一个新的留言分类或者修改一个已有的留言分类。</div> <div class="tip_body_link"><a href="catalogList?parentId=${parentId}">返回留言分类浏览</a></div> </div> </div> <%@include file="include/tips_warn_err.jsp" %> <form:form action="catalogEdit" id="list_form" commandName="catalog" method="post"> <div class="form_box"> <table class="form_table" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="form_td_name_short">分类名称<font color=red>*</font></td> <td class="form_td_edit"><form:input class="long_large" type="text" id="title" path="title" value=""/></td> <td class="form_td_info"><div style="color: red" id="titleDiv"><form:errors path="title" cssClass="errorMsg"/>${titleError}</div></td> </tr> <tr> <td class="form_td_name_short">排序值<font color=red></font></td> <td class="form_td_edit"><form:input class="long_large" type="text" id="sortid" path="sortid" value=""/></td> <td class="form_td_info"><div style="color: red" id="sortidDiv"><form:errors path="sortid" cssClass="errorMsg"/>${sortidError}</div></td> </tr> <tr> <td></td> <td class="form_td_button"> <input type="submit" value="确认"> <input type="reset" value="清空"> <input type="hidden" value="${parentId}" name="parentId"> <input type="hidden" value="${catalog.id}" name="id"> </td> <td class="form_td_info"></td> </tr> </table> </div> </form:form> </div></div></td> </tr> </table> <%@include file="include/foot_version.jsp/" %> </body> </html>
能够实现一级拖拽 二级隐藏一级二级拖拽了