在做权限管理系统时,可能会用到插件zTree v3,这是一个功能丰富强大的前端插件,应用很广泛,如异步加载菜单制作、下拉选择、权限分配等。在集成SpringMVC中,我分别实现了zTree的添删改查,本节主要实现类似表单回显功能。如图:
1、前端代码
<%@ 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>
2、后端
1)实体类(采用JPA注解,mysql数据库)
//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层
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) {
//1、查出所有角色
List<Role>listAll=roleRepository.findAll();
//2、查出指定用户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);
}
}
3、测试
http://localhost:8080/treeDemo/user/getRoles2.do