xiaomin 850 0 2017-07-07 22:01:15

文章位置:左搜> 编程技术> 正文
1.页面
<!DOCTYPE html>
<HTML>
 <HEAD>
  <TITLE> ZTREE DEMO </TITLE>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="demoStyle/demo.css" type="text/css">
  <link rel="stylesheet" href="zTreeStyle/zTreeStyle.css" type="text/css">
  <script type="text/javascript" src="ztreeJs/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="ztreeJs/jquery.ztree.all.min.js"></script>
 </HEAD>
<BODY>	
<div style="margin-left: 5%">  
   <article class="page-container">  
           <div class="row cl">  
               <label class="form-label col-xs-3 col-sm-3"><span  
                    class="c-red">*</span>角色名称:</label>  
               <div class="formControls col-xs-6 col-sm-6">  
                  <input type="hidden" name="roleId" value="111" id="roleId"/> 
                  <input type="text" class="input-text" value="测试" id="roleName" name="roleName">  
                </div>  
            </div>  
            <div class="row cl">  
                <label class="form-label col-xs-3 col-sm-3">权限列表:</label>  
                <div class="formControls col-xs-6 col-sm-6">  
                    <!-- 权限代码 zTree-->  
                    <div class="content_wrap">  
                        <div class="zTreeDemoBackground left">  
                            <ul id="treeDemo" class="ztree"></ul>  
                        </div>  
                    </div>  
                </div>  
            </div>  
            <div class="row cl">  
                <div class="col-xs-3 col-sm-3 col-xs-offset-3 col-sm-offset-3">  
                    <button type="button" class="btn btn-success radius sbm"">  
                        <i class="icon-ok"></i> 确定  
                    </button>  
                    <button type="button" class="btn btn-success radius reset">  
                        <i class="icon-ok"></i> 取消  
                    </button>  
                </div>  
            </div>  
        </article>  
    </div>  
</BODY>
</HTML>

2.js
//假设我们做的是为某个角色设置菜单权限,并且新增和修改权限用的一个页面
$(function() { 
      var roleId=$("#roleId").val();
      onLoadZTree(roleId);
 });
var setting = {  
        check : {  
            enable : true  
        },  
        data : {  
            simpleData : {  
                enable : true,  
                idKey : "id",  
                pIdKey : "pId",  
                rootPId : ""  
            }  
        }  
    };  

var treeNodes;  
function onLoadZTree(roleId) {  
	$.ajax({
		   type:'post',//请求方式:post  
		   dataType : 'json',//数据传输格式:json  
		   url:'/sysRoleMenu/menuTreeAjax',//获取角色菜单URL地址
		   data:{"sysRoleId":roleId},
		   async:false,//是否异步  
		   cache : false,//是否使用缓存  
		   error:function(errorMsg){
		        //请求失败处理函数  
                alert('亲,请求失败!');  
		},
				success:function(data){
					if(data.errCode == 'ok'){
						 treeNodes = data.data;//把后台封装好的简单Json格式赋给treeNodes  
					}else{
						alert('亲,初始化角色菜单失败');
					}
				}
			}); 
//这里我们假设返回的数据是:
var treeNodes =[
            { id:1, pId:0, name:"父节点1", open:true, checked:true},
            { id:11, pId:1, name:"父节点11", checked:true},
            { id:111, pId:11, name:"叶子节点111", checked:true},
            { id:112, pId:11, name:"叶子节点112", checked:true},
            { id:113, pId:11, name:"叶子节点113", checked:true},
            { id:114, pId:11, name:"叶子节点114", checked:true},
            { id:12, pId:1, name:"父节点12"},
            { id:121, pId:12, name:"叶子节点121"},
            { id:122, pId:12, name:"叶子节点122"},
            { id:123, pId:12, name:"叶子节点123"},
            { id:124, pId:12, name:"叶子节点124"},
            { id:13, pId:1, name:"父节点13", isParent:true},
            { id:2, pId:0, name:"父节点2"},
            { id:21, pId:2, name:"父节点21", open:true},
            { id:211, pId:21, name:"叶子节点211"},
            { id:212, pId:21, name:"叶子节点212"},
            { id:213, pId:21, name:"叶子节点213"},
            { id:214, pId:21, name:"叶子节点214"},
            { id:22, pId:2, name:"父节点22"},
            { id:221, pId:22, name:"叶子节点221"},
            { id:222, pId:22, name:"叶子节点222"},
            { id:223, pId:22, name:"叶子节点223"},
            { id:224, pId:22, name:"叶子节点224"},
            { id:23, pId:2, name:"父节点23"},
            { id:231, pId:23, name:"叶子节点231"},
            { id:232, pId:23, name:"叶子节点232"},
            { id:233, pId:23, name:"叶子节点233"},
            { id:234, pId:23, name:"叶子节点234"},
            { id:3, pId:0, name:"父节点3", isParent:true}
        ];
			var t = $("#treeDemo");  
	        t = $.fn.zTree.init(t, setting, treeNodes)
	    }; 

   //组装被选中的菜单为jsonArray格式
    function onCheck() {  
    	var roleId = $("#roleId").val();
    	var roleName = $("#roleName").val();
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = treeObj.getCheckedNodes(true);//获取被选中的节点
        var jsonArr = "[";  
        for (var i = 0; i < nodes.length; i++) {  
            jsonArr += "{";  
            jsonArr += "\"roleId\":\""+roleId+"\",";
            jsonArr += "\"roleName\":\""+roleName+"\",";
            jsonArr += "\"menuId\":\""+nodes[i].id+"\",";  
            jsonArr += "\"menuName\":\""+nodes[i].name+"\"";  
            jsonArr += "}"  
            jsonArr += ','
        }  
           jsonArr = jsonArr.substring(0, jsonArr.length - 1);  
           jsonArr += "]"; 
        return jsonArr;  
	};

$(function() {  
        $(".sbm").click(function(){
        	var roleId= $("#roleId").val();
			var sysRoleMenuStr = onCheck(); 
			 $.ajax({
					type:'post',//请求方式:post  
					dataType : 'json',//数据传输格式:json  
					url:'/sysRoleMenu/createSysRoleMenu',
					data:{"sysRoleId":roleId,"sysRoleMenuStr":sysRoleMenuStr},
					async:false,//是否异步  
					cache : false,//是否使用缓存  
					error:function(errorMsg){
						
						alert("亲分配权限菜单成功");
                        //成功之后你需要做什么操作都在这里写  
					},
					success:function(data){
						if(data.errCode == 'ok'){
							alert("亲分配权限菜单出错");
						}else{
							alert("亲分配权限菜单出错");
						}
					}
				});
			}
			
			 
		});
    }); 
3.控制层
@Controller
@RequestMapping(value = "/sysRoleMenu")
public class SysRoleMenuController{
    
    /**
	 * 初始化菜单树列表
	 * 
	 * @param model
	 * @param sysRoleId
	 * @return
	 */
    @ResponseBody
	@RequestMapping("/menuTreeAjax")
	public BaseResult initMenuTreeList(Model model, String sysRoleId) {
		BaseResult baseResult = new BaseResult();
		try {

			List<SysMenuTreeVo> MenuTreeList = sysRoleMenuService.getSysMenuTreeVo(sysRoleId);
			baseResult = new BaseResult(ResultCode.AJAX_OK, MenuTreeList, "数据加载成功");

		} catch (Exception e) {
			baseResult = new BaseResult(ResultCode.AJAX_Err, "", e.getMessage());
			return baseResult;
		}

		return baseResult;
	}
  
    /**
	 * 创建角色菜单权限
	 * 
	 * @param model
	 * @param sysRoleId
	 * @param sysRoleMenuStr
	 * @return
	 */
    @ResponseBody
	@RequestMapping("/createSysRoleMenu")
	public BaseResult createSysRoleMenu(Model model, String sysRoleId, String sysRoleMenuStr) {
		// 解析数据
		List<SysRoleMenu> sysRoleMenuList = changeSysRoleMenuList(sysRoleMenuStr);

		BaseResult baseResult = new BaseResult();
		try {

			sysRoleMenuService.createSysRoleMenu(sysRoleId, sysRoleMenuList);//这个方法我采用的是先删除角色下面的所有菜单权限,然后再执行的新增,这样新增修改就只用一个页面
			baseResult = new BaseResult(ResultCode.AJAX_OK, "", "创建成功");

		} catch (Exception e) {
			baseResult = new BaseResult(ResultCode.AJAX_Err, "", e.getMessage());
			log.error("SysRoleMenuController类createSysRoleMenu方法,创建菜单权限出错!", e);
			return baseResult;
		}

		return baseResult;
	}

   /**
	 * 解析菜单jsonArray数据
	 * 
	 * @param sysRoleMenuStr
	 * @return
	 * @throws LoadRecordException
	 */
public List<SysRoleMenu> changeSysRoleMenuList(String sysRoleMenuStr) throws LoadRecordException {
		List<SysRoleMenu> sysRoleMenus = null;
		if (StringUtil.isBlank(sysRoleMenuStr)) {
			return sysRoleMenus;
		}
		try {
			sysRoleMenus = new ArrayList<SysRoleMenu>();

			JSONArray jsonArray = JSON.parseArray(sysRoleMenuStr);
			for (Object object : jsonArray) {

				SysRoleMenu sysRoleMenu = new SysRoleMenu();
				JSONObject jsonObject = JSON.parseObject(object.toString());

				String roleId = jsonObject.getString("roleId");
				String roleName = jsonObject.getString("roleName");
				String menuId = jsonObject.getString("menuId");
				String menuName = jsonObject.getString("menuName");

				sysRoleMenu.setRoleId(roleId);
				sysRoleMenu.setRoleName(roleName);
				sysRoleMenu.setMenuId(menuId);
				sysRoleMenu.setMenuName(menuName);
				sysRoleMenus.add(sysRoleMenu);
			}

		} catch (Exception e) {
			log.error("解析菜单数据出错,class:SysRoleMenuController;method:changeProductSaleRegionList;exception:Exception", e);
			throw new LoadRecordException("解析菜单数据错误,请确定你的格式:" + e.getMessage(), e);
		}

		return sysRoleMenus;
	}


}
4.前台需要的封装对象
public class SysMenuTreeVo {

	// 菜单主键ID
	private String id;

	// 上级菜单
	private String pId;

	// 菜单名称
	private String name;

	// 是否展开
	private Boolean open = Boolean.FALSE;

	// 是否选中
	private Boolean checked = Boolean.FALSE;

	public SysMenuTreeVo() {

	}

	public SysMenuTreeVo(SysMenu sysMenu, Boolean checked, Boolean open) {
		if (sysMenu != null) {
			this.id = sysMenu.getId();
			if (StringUtil.isNotBlank(sysMenu.getParentId())) {
				this.pId = sysMenu.getParentId();
			} else {
				this.pId = "0";
			}
			this.name = sysMenu.getName();

		}
		this.open = open;
		this.checked = checked;

	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getpId() {
		return pId;
	}

	public void setpId(String pId) {
		this.pId = pId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Boolean getOpen() {
		return open;
	}

	public void setOpen(Boolean open) {
		this.open = open;
	}

	public Boolean getChecked() {
		return checked;
	}

	public void setChecked(Boolean checked) {
		this.checked = checked;
	}

	@Override
	public String toString() {
		return "SysMenuTreeVo [id=" + id + ", pId=" + pId + ", name=" + name + ", open=" + open + ", checked=" + checked
				+ "]";
	}
5.页面展示效果