ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)

本文主要是介绍ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

       在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='添加分类' οnfοcus='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);}//加载ztreefunction onloadZTree(){var ztreeNodes;$.ajax( {async : true, //是否异步cache : false, //是否使用缓存type : 'post', //请求方式,postdataType : "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 {@Autowiredpublic LibraryService libraryService;/*** 跳转到分类页面* @return*/@RequestMapping(value="toListLibrary/")public String toListLibrary(){return "library/listLibrary";}/*** 查询所有分类信息* @return*/@RequestMapping(value="findAllLibrary/")@ResponseBodypublic List<Object> findAllLibrary(HttpServletRequest request, HttpServletResponse response){return libraryService.findAllLibrary();}/*** 保存分类* @return*/@RequestMapping(value="saveLibrary/")@ResponseBodypublic String saveLibrary(HttpServletRequest request, HttpServletResponse response){String libraryId = UUIDUtil.randomUUID();return libraryId;}/*** 更新分类名称* @return*/@RequestMapping(value="updateLibraryName/")@ResponseBodypublic 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/")@ResponseBodypublic 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);@Autowiredprivate 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_librarywhere 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_librarywhere pid = #{pid,jdbcType=VARCHAR}</ select><!-- 查询所有分类信息 -->< select id= "findAllLibrary" resultMap ="BaseResultMap">select<include refid ="Base_Column_List"/>from onair_vms_librarywhere 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_librarywhere id = #{id,jdbcType=VARCHAR}</ select>< delete id= "deleteByPrimaryKey" parameterType="java.lang.String" >update  onair_vms_library set is_delete = 0where 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_libraryset 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整合实现增删改查)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/603420

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

mybatis的整体架构

mybatis的整体架构分为三层: 1.基础支持层 该层包括:数据源模块、事务管理模块、缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块、解析器模块 2.核心处理层 该层包括:配置解析、参数映射、SQL解析、SQL执行、结果集映射、插件 3.接口层 该层包括:SqlSession 基础支持层 该层保护mybatis的基础模块,它们为核心处理层提供了良好的支撑。

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na