标签:ztree
在springmvc+spring+mybatis里整合ztree实现增删改查,上一篇已经写了demo,下面就只贴出各层实现功能的代码:
Jsp页面实现功能的js代码如下:
<script> //用于捕获分类编辑按钮的 click 事件,并且根据返回值确定是否允许进入名称编辑状态 function beforeEditName(treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"); zTree.selectNode(treeNode); return true; } //移除分类前执行 function beforeRemove(treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"); zTree.selectNode(treeNode); var confirmFlag = confirm("确认删除分类[ " + treeNode.name + " ]吗?" ) var confirmVal = false; if(confirmFlag){ var data = {id:treeNode.id}; $.ajax({ async: false, type: "post", data:data, url: "<%=request.getContextPath() %>/library/deleteLibrary/ ", success: function(json){ if(json == "success" ){ confirmVal = true; } else{ alert('亲,删除失败!'); } }, error: function(){ alert('亲,删除失败!'); } }); } return confirmVal; } //执行删除操作后提示 function onRemove(e, treeId, treeNode) { alert('亲,删除成功!'); } //用于捕获分类编辑名称结束(Input 失去焦点 或 按下 Enter 键)之后,更新分类名称数据之前的事件回调函数 function beforeRename(treeId, treeNode, newName) { if (newName.length == 0 || newName.indexOf("请输入名称")>=0) { alert('亲,请输入分类名称!'); var zTree = $.fn.zTree.getZTreeObj("treeDemo"); setTimeout( function(){zTree.editName(treeNode)}, 10); return false; } if(newName.length > 15){ alert('亲,分类名称过长!'); var zTree = $.fn.zTree.getZTreeObj("treeDemo"); setTimeout( function(){zTree.editName(treeNode)}, 10); return false; } native_name = treeNode.name; return true; } //执行编辑操作 function onRename(e, treeId, treeNode) { if(native_name == treeNode.name){ return; } var data = {id:treeNode.id,level_id:treeNode.level,pid:treeNode.pId,name:treeNode.name}; $.ajax({ async: false, type: "post", data:data, url: "<%=request.getContextPath() %>/library/updateLibraryName/ ", success : function(json){ if(json == "success" ){ alert('操作成功!'); } else{ alert('亲,操作失败,请稍后再试!'); } }, error : function() { alert('亲,网络有点不给力呀!'); } }); } //添加子分类 function addHoverDom(treeId, treeNode) { var sObj = $("#" + treeNode.tId + "_span"); if (treeNode.editNameFlag || $("#addBtn_" +treeNode.tId).length>0 || treeNode.level == 3) return; var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加分类' onfocus='this.blur();'></span>"; sObj.after(addStr); var btn = $("#addBtn_" +treeNode.tId); if (btn) btn.bind("click" , function(){ var zTree = $.fn.zTree.getZTreeObj("treeDemo"); var treeNodes; $.ajax({ async: false, type: "post", url: "<%=request.getContextPath() %>/library/saveLibrary/ ", success : function(libraryId){ if(libraryId != "" ){ treeNodes = zTree.addNodes(treeNode, {id:(libraryId), pId:treeNode.id, name:"请输入名称" }); } if (treeNodes) { zTree.editName(treeNodes[0]); } }, error : function(){ alert('亲,网络有点不给力呀!'); } }); return false; }); } //父级分类去除删除功能 function setRemoveBtn(treeId, treeNode) { return !treeNode.isParent; } //鼠标移开按钮消失 function removeHoverDom(treeId, treeNode) { $( "#addBtn_"+treeNode.tId).unbind().remove(); }; //添加按钮点击事件 function addClick(){ $( "#addParent").bind("click" , {isParent:true}, add); } //移除分类 function remove(e) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree.getSelectedNodes(), treeNode = nodes[0]; if (nodes.length == 0) { alert( "亲,请先选择一个分类!" ); return; } var callbackFlag = $("#callbackTrigger" ).attr("checked"); zTree.removeNode(treeNode, callbackFlag); }; //展开全部分类 function expandAllFlag(){ zTree_Menu.expandAll( true); } //合并全部分类 function combineAllFlag(){ zTree_Menu.expandAll( false); } //加载ztree function onloadZTree(){ var ztreeNodes; $.ajax( { async : true, //是否异步 cache : false, //是否使用缓存 type : 'post', //请求方式,post dataType : "json", //数据传输格式 url : "<%=request.getContextPath() %>/library/findAllLibrary/ ", //请求链接 error : function() { alert('亲,网络有点不给力呀!'); }, success : function(data) { ztreeNodes = eval( "["+data+"]" ); //将string类型转换成json对象 $.fn.zTree.init($( "#treeDemo"), setting, ztreeNodes); zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo" ); $( "#selectAll").bind("click" , selectAll); expandAllFlag(); addClick(); } }); } //初始化操作 $(document).ready( function(){ onloadZTree(); }); </script>
备注:后台传过来的json数据一定执行这个操作:eval( "["+data+"]" ) 将string转换为对象
Controller层代码如下:
import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value="library/") public class LibraryController { @Autowired public LibraryService libraryService; /** * 跳转到分类页面 * @return */ @RequestMapping(value="toListLibrary/") public String toListLibrary(){ return "library/listLibrary"; } /** * 查询所有分类信息 * @return */ @RequestMapping(value="findAllLibrary/") @ResponseBody public List<Object> findAllLibrary(HttpServletRequest request, HttpServletResponse response){ return libraryService.findAllLibrary(); } /** * 保存分类 * @return */ @RequestMapping(value="saveLibrary/") @ResponseBody public String saveLibrary(HttpServletRequest request, HttpServletResponse response){ String libraryId = UUIDUtil.randomUUID(); return libraryId; } /** * 更新分类名称 * @return */ @RequestMapping(value="updateLibraryName/") @ResponseBody public String updateLibraryName(HttpServletRequest request, HttpServletResponse response, Library library) { String createname=(String) request.getSession().getAttribute(Constants.CURRENT_USER_NAME); library.setCreate_user(createname); library.setUpdate_user(createname); return libraryService.addOrUpdateLibrary(library); } /** * 删除分类 * @return */ @RequestMapping(value="deleteLibrary/") @ResponseBody public String deleteLibrary(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "id") String id) { return libraryService.deleteLibrary(id); } }
service层代码如下:
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class LibraryService { protected final static Log log = LogFactory.getLog(LibraryService.class); @Autowired private LibraryMapper libraryMapper; /** * 查询所有分类信息 * @return */ public List<Object> findAllLibrary(){ List<Object> listZTree = new ArrayList<Object>(); List<Library> listLibrary = libraryMapper.findAllLibrary(); String str = ""; for (int i = 0; i < listLibrary.size(); i++) { Library library = listLibrary.get(i);//分类信息 str = "{id:'" +library.getId() + "', pId:'"+library.getPid()+"', name:\""+library.getName()+"\" }";//封装ztree需要格式的字符串 log.info(str); listZTree.add(str); } return listZTree; } /** * 保存或更新分类信息 * @param library * @return */ public String addOrUpdateLibrary(Library library){ int numFlag = 0; //根据id查询分类信息 if (StringUtils.isBlank(library.getId())) { return "error"; } int num = libraryMapper.findLibraryById(library.getId()); if (num >0) {//更新信息 library.setUpdate_time(new Date()); library.setCreate_user(null); library.setPid(null); numFlag = libraryMapper.updateByPrimaryKeySelective(library); }else{//插入信息 if(library.getPid().equals("null")){ library.setPid("0"); } int orderId = libraryMapper.findLastLibrary(library); orderId++; library.setCreate_time(new Date()); library.setUpdate_time(new Date()); library.setOrder_id(orderId); numFlag = libraryMapper.insert(library); } return "success"; } /** * 删除分类 * @param id * @return */ public String deleteLibrary(String id){ int num = libraryMapper.deleteByPrimaryKey(id); return "success"; } }备注:执行完数据操作需要判断返回值,这里我直接返回success活error了。
Mapper层代码如下
import java.util.List; import java.util.Map; public interface LibraryMapper extends BaseMapper<Library,String>{ /** * 查询所有分类信息 * @return */ public List<Library> findAllLibrary(); /** * 根据id查询条数 * @param id * @return */ public int findLibraryById(String id); /** * 查询最大排序号 * @return */ public int findLastLibrary(Library library); }备注:BaseMapper里有几个公用的增删改查的方法,Library是数据库表对应的实体,都很简单,避免代码过多这里就省略了
<?xml version="1.0" encoding= "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace= "LibraryMapper" > < resultMap id= "BaseResultMap" type= "Library" > <id column ="id" property="id" jdbcType= "VARCHAR" /> <result column ="pid" property="pid" jdbcType= "VARCHAR" /> <result column ="name" property="name" jdbcType= "VARCHAR" /> <result column ="create_time" property="create_time" jdbcType= "TIMESTAMP" /> <result column ="update_time" property="update_time" jdbcType= "TIMESTAMP" /> <result column ="is_delete" property="is_delete" jdbcType= "INTEGER" /> <result column ="update_user" property="update_user" jdbcType= "VARCHAR" /> <result column ="create_user" property="create_user" jdbcType= "VARCHAR" /> <result column ="level_id" property="level_id" jdbcType= "INTEGER" /> <result column ="order_id" property="order_id" jdbcType= "INTEGER" /> </ resultMap> < sql id= "Base_Column_List" > id, pid , name, create_time, update_time, is_delete, update_user, create_user, level_id, order_id </ sql> <!-- 根据id查询分类信息是否存在 --> < select id= "findLibraryById" parameterType ="java.lang.String" resultType= "java.lang.Integer" > select count(*) from onair_vms_library where is_delete=1 and id = #{id,jdbcType=VARCHAR} </ select> <!-- 根据 pid查询最大排序号 --> < select id= "findLastLibrary" resultType ="java.lang.Integer" parameterType="Library" > SELECT MAX(order_id) as order_id FROM onair_vms_library where pid = #{pid,jdbcType=VARCHAR} </ select> <!-- 查询所有分类信息 --> < select id= "findAllLibrary" resultMap ="BaseResultMap"> select <include refid ="Base_Column_List"/> from onair_vms_library where is_delete = 1 order by order_id </ select> < select id= "selectByPrimaryKey" resultMap ="BaseResultMap" parameterType="java.lang.String" > select <include refid ="Base_Column_List" /> from onair_vms_library where id = #{id,jdbcType=VARCHAR} </ select> < delete id= "deleteByPrimaryKey" parameterType="java.lang.String" > update onair_vms_library set is_delete = 0 where id = #{id,jdbcType=VARCHAR} </ delete> < insert id= "insert" parameterType="Library" > insert into onair_vms_library (id, pid, name, create_time, update_time, is_delete, update_user, create_user, level_id, order_id) values (#{id,jdbcType=VARCHAR}, #{pid,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{create_time,jdbcType=TIMESTAMP}, #{update_time,jdbcType=TIMESTAMP}, #{is_delete,jdbcType=INTEGER}, #{update_user,jdbcType=VARCHAR}, #{create_user,jdbcType=VARCHAR}, #{level_id,jdbcType=INTEGER}, #{order_id,jdbcType=INTEGER}) </ insert> < update id= "updateByPrimaryKey" parameterType="Library" > update onair_vms_library set pid = #{pid,jdbcType=VARCHAR}, name = #{name,jdbcType=VARCHAR}, create_time = #{create_time,jdbcType=TIMESTAMP}, update_time = #{update_time,jdbcType=TIMESTAMP}, is_delete = #{is_delete,jdbcType=INTEGER}, update_user = #{update_user,jdbcType=VARCHAR}, create_user = #{create_user,jdbcType=VARCHAR}, level_id = #{level_id,jdbcType=INTEGER}, order_id = #{order_id,jdbcType=INTEGER} where id = #{id,jdbcType=VARCHAR} </ update> </mapper>备注:mapper对应的xml
与jsp对应的VO层代码如下:
public class LibraryVo { /* id */ private String id; /* 目标id */ private String targetId; /* pid */ private String pId; /* 目标pid */ private String targetPId; /* "inner":成为子节点,"prev":成为同级前一个节点,"next":成为同级后一个节点 */ private String moveType; public String getId() { return id; } public void setId(String id) { this. id = id; } public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this. targetId = targetId; } public String getpId() { return pId; } public void setpId(String pId) { this. pId = pId; } public String getTargetPId() { return targetPId; } public void setTargetPId(String targetPId) { this. targetPId = targetPId; } public String getMoveType() { return moveType; } public void setMoveType(String moveType) { this. moveType = moveType; } }
上面的代码实现了基本的增删改查,有哪些地方有问题欢迎指正,也欢迎交流,每一次的进步都离不开大家的帮助。
ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查),布布扣,bubuko.com
ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)
标签:ztree
原文地址:http://blog.csdn.net/huangaigang6688/article/details/27376831