springmvc+ztree v3实现类似表单回显功能

20 篇文章 0 订阅
11 篇文章 1 订阅

在做权限管理系统时,可能会用到插件zTree v3,这是一个功能丰富强大的前端插件,应用很广泛,如异步加载菜单制作、下拉选择、权限分配等。在集成SpringMVC中,我分别实现了zTree的添删改查,本节主要实现类似表单回显功能。如图:

1、前端代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

<%@ 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数据库)

1

2

3

4

5

6

7

8

//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方法

  

1

2

3

4

5

6

7

8

9

10

11

12

@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层

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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);

}

  

1

2

3

4

5

6

7

8

9

10

11

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层

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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);

}

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//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;

    }

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

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

 https://www.cnblogs.com/hzhh123/p/5419361.html

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值