springmvc+ztree v3實現相似表單回顯功能

     在作權限管理系統時,可能會用到插件zTree v3,這是一個功能豐富強大的前端插件,應用很普遍,如異步加載菜單製做、下拉選擇、權限分配等。在集成SpringMVC中,我分別實現了zTree的添刪改查,本節主要實現相似表單回顯功能。如圖:javascript

一、前端代碼

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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">
<title>非異步加載節點</title>
<link rel="stylesheet"
	href="${pageContext.request.contextPath }/res/bootstrap/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet"
	href="${pageContext.request.contextPath }/res/zTree/css/metroStyle/metroStyle.css" type="text/css">
<script type="text/javascript"
	src="${pageContext.request.contextPath }/res/bootstrap/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/res/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/res/zTree/js/jquery.ztree.core.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/res/zTree/js/jquery.ztree.excheck.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/res/zTree/js/jquery.ztree.exedit.js"></script>
<script type="text/javascript">
    var zNodes;
    var setting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };
        //當頁面加載完畢,向後臺發送ajax請求,獲取用戶id爲1的用戶所擁有的權限
        //(這裏要顯示全部權限,該id用戶的權限回顯時,被自動選中),這裏的用戶id爲1僅作測試使用,實際開發中會傳值
        function loadPower(){
                    $.ajax({
                        type:"post",
                        url:"${pageContext.request.contextPath }/user/role_list.do",
                        data:{"userId":1},
                        async:false,
                        dataType:"json",
                        success:function(data){
                            zNodes=data;
                        }
                    })
        }
        
        //用戶從新選擇權限時,獲取選擇權限的id,此處能夠拼接權限id的字符串,到後臺切割成數組。String.split(",")
        function test(){
            //獲取被選中的節點集合
            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
            var nodes = treeObj.getCheckedNodes(true);
            //若是nodes的長度大於0說明ztree中有被選中的節點
            if(nodes.length>0){
                for(var i=0;i<nodes.length;i++){
                    var id=nodes[i]["id"];//獲取選中節點的id
                    var name=nodes[i]["name"];//獲取選中節點的名字
                    alert(id);
                    alert(name);
                }
            }else{
                alert("沒有選中節點");
            }
        }
        
        //頁面加載完畢時加載此方法
        $(document).ready(function(){
            loadPower();
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });
    </script>
  </head>
  <body>
    <ul id="treeDemo" class="ztree"></ul>
    <!-- 傳遞用戶id值 -->
    <input type="hidden" name="userId" value="${userId }">
    <input type="button" value="測試被選中的節點的id" onclick="test();" />
  </body>
</body>
</html>

 二、後端

 1)實體類(採用JPA註解,mysql數據庫)css

//User.java
public class User implements Serializable{
	private Integer id;
	private String username;//用戶名
	private String password;//密碼
	private Set<Role>roles=new HashSet<Role>();//多對多

      #get、set方法

  

@Table(name="b_role")
@Entity
public class Role implements Serializable{
	
	private Integer rid;//自增Id序列
	private Integer id;//自己節點id
	private Integer pId;//父節點id,默認爲0,是整個樹的根
	private String name;//對應zTree樹的name屬性
	private Boolean isParent;//是不是父節點
	private Set<User>users=new HashSet<User>();
    #get、set方法
   ......

 2)dao層html

package sys.dao;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import sys.entity.Role;

public interface RoleRepository extends JpaRepository<Role, Integer> {
	@Query("select r from Role r where pid = ?")
	List<Role>getRoles(int pid);
	@Query(value="select * from a_role r where r.id=:id",nativeQuery=true)
	Role getRoleById(@Param("id")Integer id);
}

  

package sys.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import sys.entity.User;

public interface UserRepository extends JpaRepository<User, Integer>{
	User getByUsernameAndPassword(String username,String password);
	User getByUsername(String username);

}

 3)service層前端

package sys.service;

import java.util.List;
import java.util.Map;
import java.util.Set;

import sys.entity.Role;


public interface RoleService {
	void save(Role role);
	List<Role>getAll();
	Role getRole(Integer rid);
	void delete(Integer id);
	List<Role> findAll();
	List<Role> getRoles(int pid);
	Role getRoleById(Integer id);
	Set<Role> getRolesInId(List<Integer> id_list);
	List<Map<String, Object>>queryByUserId(Integer userId);
}

  

//RoleServiceImpl實現queryByUserId方法
/**
	 * zTree v3回顯
	 * 初始化化權限樹
	 * 拼接treeNode屬性
	 */
	@Transactional(readOnly=true)
	@Override
	public List<Map<String, Object>> queryByUserId(Integer userId) {
		//一、查出全部角色
		List<Role>listAll=roleRepository.findAll();
		//二、查出指定用戶id的角色
		Set<Role>listOne=userRepository.getOne(userId).getRoles();
		//包裝zTree
		List<Map<String, Object>>list=new ArrayList<Map<String, Object>>();
		Map<String, Object>map=null;
		for(int i=0;i<listAll.size();i++){
			map=new HashMap<>();
			Role role=listAll.get(i);
			map.put("id", role.getId());
			map.put("pId", role.getpId());
			map.put("name", role.getName());
			map.put("isParent", role.getIsParent());
			//判斷指定用戶的角色是否在全部角色中包含,有則設置checked=true.
			if(listOne!=null&&listOne.size()>0&&listOne.contains(role)){
                map.put("checked",true);
            }else {
            	map.put("checked",false);
			}
			list.add(map);
		}
		return list;
	}

  

package sys.controller;

import java.util.List;
import java.util.Map;

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;

import sys.service.RoleService;
@RequestMapping("user")
@Controller
public class UserController {
	@Autowired
	private RoleService roleService;
	@RequestMapping("getRoles")
	public String getRoles(){
		return "treedemo/demo1";
	}
	@RequestMapping("getRoles2")
	public String getRoles2(){
		return "treedemo/demo2";
	}
	
	/**
	 * 根據用戶id初始化權限樹
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("role_list")
	public List<Map<String, Object>> getRolelist(@RequestParam("userId")Integer userId){
		return roleService.queryByUserId(userId);
	}
}

 三、測試

http://localhost:8080/treeDemo/user/getRoles2.dojava

相關文章
相關標籤/搜索