基于spring boot和mongodb打造一套完整的权限架构(五)【集成用户模块、菜单模块、角色模块】

释放双眼,带上耳机,听听看~!

      在第四章我们已经实现了对security的集成,我们已经实现了登陆到我们的系统中了,但是大家会发现我们登陆成功以后并没有显示左侧的菜单节点,本章我们将开始集成用户模块、菜单模块以及角色模块。

     1、首先我们需要在sys的entity目录底下创建Tree、QueryTree和QueryRole实体,以及修改user和UserRole实体内容如下:

Tree实体:


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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
1package com.mongo.sys.entity;
2
3import net.sf.json.JSONObject;
4import org.bson.types.ObjectId;
5
6import java.util.List;
7
8/**
9 *@author linzf
10 **/
11public class Tree implements Comparable<Tree> {
12 
13  public Tree(){
14      super();
15  }
16
17  public Tree(String id){
18      this.id = new ObjectId(id);
19  }
20
21
22
23  private ObjectId id;
24  private String code;
25  private String icon;
26  private String name;
27  private ObjectId parentId;
28  private long treeOrder;
29  private String url;
30  private String state;
31  private boolean checked;
32  private List<Tree> child;
33  private Tree tree;
34
35  public Tree getTree() {
36      return tree;
37  }
38
39  public void setTree(Tree tree) {
40      this.tree = tree;
41  }
42
43  public String getId() {
44      if(id!=null){
45          return id.toString();
46      }else{
47          return "";
48      }
49  }
50
51  public void setId(String id) {
52      this.id = new ObjectId(id);;
53  }
54
55  public String getParentId() {
56      if(parentId!=null){
57          return parentId.toString();
58      }else{
59          return "";
60      }
61  }
62
63  public void setParentId(String parentId) {
64      this.parentId = new ObjectId(parentId);;
65  }
66
67  public boolean isChecked() {
68      return checked;
69  }
70
71  public void setChecked(boolean checked) {
72      this.checked = checked;
73  }
74
75  public List<Tree> getChild() {
76      return child;
77  }
78
79  public void setChild(List<Tree> child) {
80      this.child = child;
81  }
82
83
84
85  public String getCode() {
86      return code;
87  }
88
89  public void setCode(String code) {
90      this.code = code;
91  }
92
93  public String getIcon() {
94      return icon;
95  }
96
97  public void setIcon(String icon) {
98      this.icon = icon;
99  }
100
101 public String getName() {
102     return name;
103 }
104
105 public void setName(String name) {
106     this.name = name;
107 }
108
109 public long getTreeOrder() {
110     return treeOrder;
111 }
112
113 public void setTreeOrder(long treeOrder) {
114     this.treeOrder = treeOrder;
115 }
116
117 public String getUrl() {
118     return url;
119 }
120
121 public void setUrl(String url) {
122     this.url = url;
123 }
124
125 public String getState() {
126     return state;
127 }
128
129 public void setState(String state) {
130     this.state = state;
131 }
132
133 /**
134  * 功能描述:实现集合根据treeOrder字段进行排序的功能
135  * @param o
136  * @return
137  */
138 @Override
139 public int compareTo(Tree o) {
140     long i = this.getTreeOrder() - o.getTreeOrder();
141     return Integer.parseInt(i+"");
142 }
143}
144

QueryTree查询实体:


1
2
3
4
5
6
7
8
9
1package com.mongo.sys.entity;
2
3
4import com.mongo.common.base.entity.QueryBase;
5
6public class QueryTree extends QueryBase {
7}
8
9

QueryRole查询实体:


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
1package com.mongo.sys.entity;
2
3
4import com.mongo.common.base.entity.QueryBase;
5import com.mongo.common.base.entity.QueryField;
6import com.mongo.common.base.entity.QueryType;
7
8public class QueryUserRole extends QueryBase {
9
10    @QueryField(type = QueryType.LIKE)
11    private String name;
12    @QueryField(type = QueryType.LIKE)
13    private String roleName;
14
15    public String getName() {
16        return name;
17    }
18
19    public void setName(String name) {
20        this.name = name;
21    }
22
23    public String getRoleName() {
24        return roleName;
25    }
26
27    public void setRoleName(String roleName) {
28        this.roleName = roleName;
29    }
30}
31
32

     
 User修改以后实体内容如下:


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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
1package com.mongo.sys.entity;
2
3
4import com.mongo.common.base.entity.QueryField;
5import com.mongo.sys.dao.UserRoleDao;
6import net.sf.json.JSONObject;
7import org.bson.types.ObjectId;
8import org.springframework.security.core.GrantedAuthority;
9import org.springframework.security.core.authority.SimpleGrantedAuthority;
10import org.springframework.security.core.userdetails.UserDetails;
11import org.springframework.security.crypto.factory.PasswordEncoderFactories;
12import org.springframework.security.crypto.password.PasswordEncoder;
13
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.Date;
17import java.util.List;
18
19/*
20* 类描述:用户实体类
21* @auther linzf
22* @create 2018/3/30 0030
23*/
24public class User implements UserDetails {
25
26    public static void main(String [] args){
27        User user = new User();
28        List<UserRole> roles = new ArrayList<UserRole>();
29        UserRole userRole = new UserRole();
30        userRole.setId("5ac0e051c053f4297804f42c");
31        userRole.setName("ROLE_ADMIN");
32        userRole.setRoleName("系统管理员");
33        roles.add(userRole);
34        user.setLogin("shyll");
35        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
36        user.setPassword(passwordEncoder.encode("123456"));
37        user.setRoles(roles);
38        user.setId(ObjectId.get().toString());
39        user.setState("1");
40        System.out.println(JSONObject.fromObject(user).toString());
41
42    }
43
44
45    private ObjectId id;
46    // 增加QueryField注解在buildBaseQuery构建Query查询条件的时候会自动将其加入到Query查询条件中
47    @QueryField
48    private String login;
49    private String password;
50    private String userName;
51    private String address;
52    private String job;
53    private Date birthDate;
54    private String city;
55    private String district;
56    private String province;
57    private String streetAddress;
58    private String state;
59    private String type;
60    private Date lastLoginDate;
61    // 用户角色信息
62    private List<UserRole> roles;
63    // 角色信息集合
64    private String roleArray;
65
66    public String getRoleArray() {
67        return roleArray;
68    }
69
70    public void setRoleArray(String roleArray) {
71        this.roleArray = roleArray;
72    }
73
74    @Override
75    public Collection<? extends GrantedAuthority> getAuthorities() {
76        List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
77        if(this.getRoles()!=null){
78            List<UserRole> roles=this.getRoles();
79            for(UserRole role:roles){
80                if(role.getName()!=null){
81                    auths.add(new SimpleGrantedAuthority(role.getName()));
82                }
83            }
84        }
85        return auths;
86    }
87
88    public String getPassword() {
89        return password;
90    }
91
92    @Override
93    public String getUsername() {
94        return this.getLogin();
95    }
96
97    @Override
98    public boolean isAccountNonExpired() {
99        return true;
100    }
101
102    @Override
103    public boolean isAccountNonLocked() {
104        return true;
105    }
106
107    @Override
108    public boolean isCredentialsNonExpired() {
109        return true;
110    }
111
112    @Override
113    public boolean isEnabled() {
114        return true;
115    }
116
117    public String getId() {
118        return id.toString();
119    }
120
121    public void setId(String id) {
122        this.id = new ObjectId(id);
123    }
124
125    public String getLogin() {
126        return login;
127    }
128
129    public void setLogin(String login) {
130        this.login = login;
131    }
132
133    public void setPassword(String password) {
134        this.password = password;
135    }
136
137    public String getUserName() {
138        return userName;
139    }
140
141    public void setUserName(String userName) {
142        this.userName = userName;
143    }
144
145    public String getAddress() {
146        return address;
147    }
148
149    public void setAddress(String address) {
150        this.address = address;
151    }
152
153    public String getJob() {
154        return job;
155    }
156
157    public void setJob(String job) {
158        this.job = job;
159    }
160
161    public Date getBirthDate() {
162        return birthDate;
163    }
164
165    public void setBirthDate(Date birthDate) {
166        this.birthDate = birthDate;
167    }
168
169    public String getCity() {
170        return city;
171    }
172
173    public void setCity(String city) {
174        this.city = city;
175    }
176
177    public String getDistrict() {
178        return district;
179    }
180
181    public void setDistrict(String district) {
182        this.district = district;
183    }
184
185    public String getProvince() {
186        return province;
187    }
188
189    public void setProvince(String province) {
190        this.province = province;
191    }
192
193    public String getStreetAddress() {
194        return streetAddress;
195    }
196
197    public void setStreetAddress(String streetAddress) {
198        this.streetAddress = streetAddress;
199    }
200
201    public String getState() {
202        return state;
203    }
204
205    public void setState(String state) {
206        this.state = state;
207    }
208
209    public String getType() {
210        return type;
211    }
212
213    public void setType(String type) {
214        this.type = type;
215    }
216
217    public Date getLastLoginDate() {
218        return lastLoginDate;
219    }
220
221    public void setLastLoginDate(Date lastLoginDate) {
222        this.lastLoginDate = lastLoginDate;
223    }
224
225    public List<UserRole> getRoles() {
226        return roles;
227    }
228
229    public void setRoles(List<UserRole> roles) {
230        this.roles = roles;
231    }
232
233    /**
234     * 功能描述:组装角色数据集合
235     * @param roleArray
236     * @param userRoleDao
237     */
238    public void packagingRoles(String roleArray,UserRoleDao userRoleDao){
239        List<UserRole> roles = new ArrayList<UserRole>();
240        if(roleArray!=null){
241            UserRole userRole = null;
242            for(String roleId:roleArray.split(",")){
243                if(!roleId.isEmpty()){
244                    userRole = new UserRole();
245                    roles.add(userRoleDao.get(roleId));
246                }
247            }
248        }
249        this.setRoles(roles);
250    }
251
252}
253
254

UserRole修改以后实体内容如下:


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
82
83
1package com.mongo.sys.entity;
2
3
4import com.mongo.common.base.entity.QueryField;
5import org.bson.types.ObjectId;
6
7import java.util.ArrayList;
8import java.util.List;
9
10
11/*
12* 类描述:用户角色实体类
13* @auther linzf
14* @create 2018/3/30 0030
15*/
16public class UserRole {
17
18    private ObjectId id;
19    // 增加QueryField注解在buildBaseQuery构建Query查询条件的时候会自动将其加入到Query查询条件中
20    @QueryField
21    private String name;
22
23    private String roleName;
24
25    private List<Tree> treeList;
26
27    // 临时采访菜单数集合的数据
28    private String treeArray;
29
30    public List<Tree> getTreeList() {
31        return treeList;
32    }
33
34    public void setTreeList(List<Tree> treeList) {
35        this.treeList = treeList;
36    }
37
38    public String getTreeArray() {
39        return treeArray;
40    }
41
42    public void setTreeArray(String treeArray) {
43        this.treeArray = treeArray;
44    }
45
46    public String getId() {
47        return id.toString();
48    }
49
50    public void setId(String id) {
51        this.id = new ObjectId(id);
52    }
53
54    public String getName() {
55        return name;
56    }
57
58    public void setName(String name) {
59        this.name = name;
60    }
61
62    public String getRoleName() {
63        return roleName;
64    }
65
66    public void setRoleName(String roleName) {
67        this.roleName = roleName;
68    }
69
70    public void packagingTrees(String treeArray){
71        Tree tree = null;
72        List<Tree> trees = new ArrayList<>();
73        for(String id:treeArray.split(",")){
74            if(!id.isEmpty()){
75                tree = new Tree(id);
76                trees.add(tree);
77            }
78        }
79        this.setTreeList(trees);
80    }
81
82}
83

**     
 2、创建好菜单的实体、角色实体以后我们就要开始编写我们的菜单的dao层和角色的dao层。**

TreeDao数据库层操作类内容如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1package com.mongo.sys.dao;
2
3
4import com.mongo.common.base.dao.MongodbBaseDao;
5import com.mongo.sys.entity.QueryTree;
6import com.mongo.sys.entity.Tree;
7import org.springframework.stereotype.Component;
8
9@Component
10public class TreeDao extends MongodbBaseDao<Tree,QueryTree> {
11
12}
13
14

UserRoleDao数据库层操作类内容如下:


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
1package com.mongo.sys.dao;
2
3
4import com.mongo.common.base.dao.MongodbBaseDao;
5import com.mongo.sys.entity.QueryUserRole;
6import com.mongo.sys.entity.UserRole;
7import org.springframework.data.mongodb.core.query.Criteria;
8import org.springframework.data.mongodb.core.query.Query;
9import org.springframework.stereotype.Component;
10
11import java.util.List;
12
13@Component
14public class UserRoleDao extends MongodbBaseDao<UserRole,QueryUserRole> {
15
16    /**
17     * 功能描述:根据角色ID的集合来获取所有的角色数据
18     * @param roles
19     * @return
20     */
21    public List<UserRole> getUserRoleByRoleId(List<UserRole> roles){
22        Query query = new Query();
23        String [] ids = new String[roles.size()];
24        for(int i=0;i<roles.size();i++){
25            ids[i] = roles.get(i).getId();
26        }
27        query.addCriteria(Criteria.where("id").in(ids));
28        return mongoTemplate.find(query,UserRole.class);
29    }
30
31}
32
33

**     
 3、当我们编写好我们的菜单和角色的数据库操作的dao层,首先我们要在util工具类底下创建一个菜单节点递归类NodeUtil和用户工具类UserInfo,主要是用于密码加密以及获取登陆的用户信息等,工具类代码如下:**

NodeUtil工具类内容如下:


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
82
83
84
85
86
1package com.mongo.common.util.node;
2
3
4
5
6
7
8
9import com.mongo.sys.entity.Tree;
10
11import java.util.ArrayList;
12import java.util.Collections;
13import java.util.Iterator;
14import java.util.List;
15
16/*
17* 类描述:
18* @auther linzf
19* @create 2017/9/20 0020
20*/
21public class NodeUtil {
22
23    private static List<Tree> returnList = new ArrayList<Tree>();
24
25    /**
26     * 根据父节点的ID获取所有子节点
27     * @param list 分类表
28     * @param typeId 传入的父节点ID
29     * @return String
30     */
31    public static List<Tree> getChildNodes(List<Tree> list, String typeId) {
32        returnList = new ArrayList<Tree>();
33        if(list == null && typeId == null) return new ArrayList<Tree>();
34        for (Iterator<Tree> iterator = list.iterator(); iterator.hasNext();) {
35            Tree node = (Tree) iterator.next();
36            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
37            if (node.getParentId().equals("5ac0c4a0c053f417ac310e3f") && typeId.equals(node.getId())) {
38                recursionFn(list, node);
39            }
40            // 二、遍历所有的父节点下的所有子节点
41            if (node.getParentId().equals("5ac0c4a0c053f417ac310e3f")) {
42                recursionFn(list, node);
43            }
44        }
45        // 对顶层菜单按照treeOrder从大到小进行进行排序
46        Collections.sort(returnList);
47        return returnList;
48    }
49
50    private static void recursionFn(List<Tree> list, Tree node) {
51        List<Tree> childList = getChildList(list, node);// 得到子节点列表
52        if (hasChild(list, node)) {// 判断是否有子节点
53            Iterator<Tree> it = childList.iterator();
54            while (it.hasNext()) {
55                Tree n = (Tree) it.next();
56                if(hasChild(list,n)){// 判断子节点是否还有相应的子节点,若有则再次递归遍历
57                    recursionFn(list, n);
58                }
59            }
60            node.setChild(childList);
61            returnList.add(node);
62        }
63    }
64
65    // 得到子节点列表
66    private static List<Tree> getChildList(List<Tree> list, Tree node) {
67        List<Tree> nodeList = new ArrayList<Tree>();
68        Iterator<Tree> it = list.iterator();
69        while (it.hasNext()) {
70            Tree n = (Tree) it.next();
71            if (n.getParentId().equals(node.getId())) {
72                nodeList.add(n);
73            }
74        }
75        Collections.sort(nodeList);
76        return nodeList;
77    }
78
79    // 判断是否有子节点
80    private static boolean hasChild(List<Tree> list, Tree node) {
81        return getChildList(list, node).size() > 0 ? true : false;
82    }
83
84}
85
86

UserInfo工具类内容如下:


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
82
83
84
85
86
87
88
89
90
1package com.mongo.common.util.user;
2
3
4
5
6import com.mongo.common.util.node.NodeUtil;
7import com.mongo.sys.entity.Tree;
8import com.mongo.sys.entity.User;
9import com.mongo.sys.entity.UserRole;
10import com.mongo.sys.service.TreeService;
11import com.mongo.sys.service.UserRoleService;
12import org.springframework.security.core.GrantedAuthority;
13import org.springframework.security.core.context.SecurityContextHolder;
14import org.springframework.security.core.context.SecurityContextImpl;
15import org.springframework.security.crypto.factory.PasswordEncoderFactories;
16import org.springframework.security.crypto.password.PasswordEncoder;
17import org.springframework.web.context.request.RequestContextHolder;
18import org.springframework.web.context.request.ServletRequestAttributes;
19
20import javax.servlet.http.HttpServletRequest;
21import java.util.*;
22
23/**
24 * @auher linzf
25 * @since 2018-03-31
26 */
27public class UserInfo {
28
29    /**
30     * 功能描述:加载菜单节点的数据
31     * @return
32     */
33    public static List<Tree> loadUserTree(UserRoleService userRoleService, TreeService treeService){
34        Map<String,Tree> treeMap = new HashMap<String,Tree>();
35        User user = getUser();
36        List<UserRole> userRoleList = userRoleService.getUserRoleByRoleId(user);
37        for(UserRole userRole:userRoleList){
38            for(Tree tree:userRole.getTreeList()){
39                treeMap.put(tree.getId(),treeService.get(tree.getId()));
40            }
41        }
42        List<Tree> treeList = NodeUtil.getChildNodes(new ArrayList<Tree>(treeMap.values()),"5ac0c4a0c053f417ac310e3f");
43        return treeList;
44    }
45
46    /**
47     * 功能描述:实现对密码进行bcrypt加密
48     * @param password
49     * @return
50     */
51    public static String encode(String password){
52        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
53        return passwordEncoder.encode(password);
54    }
55
56    /**
57     * 功能描述:获取当前登陆的用户的信息
58     * 注释:强转一个null对象不会产生报错
59     * @return
60     */
61    public static User getUser(){
62        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
63        SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
64        return (User)Optional.ofNullable(securityContextImpl.getAuthentication().getPrincipal()).orElse(null);
65    }
66
67    /**
68     * 功能描述:获取当前登陆的用户的权限集合
69     * @return
70     */
71    public static List<GrantedAuthority> getGrantedAuthority(){
72        return (List<GrantedAuthority>)Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).orElse(new ArrayList<>());
73    }
74
75    /**
76     * 功能描述:判断当前的用户是否包含某一个权限
77     * @param authority
78     * 注释:
79     *      allMatch:Stream 中全部元素符合传入的 predicate,返回 true
80     *      anyMatch:Stream 中只要有一个元素符合传入的 predicate,返回 true
81     *      noneMatch:Stream 中没有一个元素符合传入的 predicate,返回 true
82     * @return
83     */
84    public static boolean hasAuthority(String authority){
85        return getGrantedAuthority().stream().anyMatch(obj->obj.getAuthority().equalsIgnoreCase(authority));
86    }
87
88}
89
90

**     
 4、编写好我们的工具类以后我们就可以正式开始编写我们的用户、角色、菜单的service业务实现类。**

TreeService内容如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1package com.mongo.sys.service;
2
3
4import com.mongo.common.base.dao.MongodbBaseDao;
5import com.mongo.common.base.service.MongodbBaseService;
6import com.mongo.sys.dao.TreeDao;
7import com.mongo.sys.entity.QueryTree;
8import com.mongo.sys.entity.Tree;
9import org.springframework.beans.factory.annotation.Autowired;
10import org.springframework.stereotype.Service;
11
12@Service
13public class TreeService extends MongodbBaseService<Tree,QueryTree> {
14
15    @Autowired
16    private TreeDao treeDao;
17
18    @Override
19    protected MongodbBaseDao<Tree, QueryTree> getDao() {
20        return treeDao;
21    }
22}
23
24

UserRoleService内容如下:


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
1package com.mongo.sys.service;
2
3
4import com.mongo.common.base.dao.MongodbBaseDao;
5import com.mongo.common.base.service.MongodbBaseService;
6import com.mongo.sys.dao.UserRoleDao;
7import com.mongo.sys.entity.QueryUserRole;
8import com.mongo.sys.entity.User;
9import com.mongo.sys.entity.UserRole;
10import org.springframework.beans.factory.annotation.Autowired;
11import org.springframework.stereotype.Service;
12
13import java.util.List;
14
15@Service
16public class UserRoleService extends MongodbBaseService<UserRole,QueryUserRole> {
17
18    @Autowired
19    private UserRoleDao userRoleDao;
20
21    @Override
22    protected MongodbBaseDao<UserRole, QueryUserRole> getDao() {
23        return userRoleDao;
24    }
25
26    @Override
27    public UserRole save(UserRole entity) {
28        entity.packagingTrees(entity.getTreeArray());
29        return super.save(entity);
30    }
31
32    @Override
33    public void updateById(String id, UserRole entity) {
34        entity.packagingTrees(entity.getTreeArray());
35        super.updateById(id, entity);
36    }
37
38
39
40    /**
41     * 功能描述:根据用户来获取用户相应的角色以及他的菜单数据
42     * @param user
43     * @return
44     */
45    public List<UserRole> getUserRoleByRoleId(User user){
46        return userRoleDao.getUserRoleByRoleId(user.getRoles());
47    }
48}
49
50

UserService内容如下:


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
1package com.mongo.sys.service;
2
3
4import com.mongo.common.base.dao.MongodbBaseDao;
5import com.mongo.common.base.service.MongodbBaseService;
6import com.mongo.common.util.user.UserInfo;
7import com.mongo.sys.dao.UserDao;
8import com.mongo.sys.dao.UserRoleDao;
9import com.mongo.sys.entity.QueryUser;
10import com.mongo.sys.entity.User;
11import org.springframework.beans.factory.annotation.Autowired;
12import org.springframework.data.mongodb.core.query.Query;
13import org.springframework.data.mongodb.core.query.Update;
14import org.springframework.stereotype.Service;
15
16/**
17 * 功能描述:实现用户管理的service
18 */
19@Service
20public class UserService extends MongodbBaseService<User,QueryUser> {
21
22    @Autowired
23    private UserDao userDao;
24
25    @Autowired
26    private UserRoleDao userRoleDao;
27
28    @Override
29    protected MongodbBaseDao<User,QueryUser> getDao() {
30        return userDao;
31    }
32
33    /**
34     * 功能描述:更新用户状态为可用或者不可用
35     * @param user
36     * @return
37     */
38    public void userControl(User user){
39        userDao.userControl(user);
40    }
41
42
43    @Override
44    public void updateById(String id, User user) {
45        user.packagingRoles(user.getRoleArray(),userRoleDao);
46        super.updateById(id, user);
47    }
48
49    @Override
50    public User save(User entity) {
51        entity.setAddress(entity.getProvince()+entity.getCity()+entity.getDistrict()+entity.getStreetAddress());
52        entity.setPassword(UserInfo.encode(entity.getPassword()));
53        entity.setState("1");
54        entity.packagingRoles(entity.getRoleArray(),userRoleDao);
55        return super.save(entity);
56    }
57
58    /**
59     * 功能描述:根据账号来获取用户信息
60     * @param login
61     * @return
62     */
63    public User findByLogin(String login){
64        return userDao.findByLogin(login);
65    }
66
67}
68
69

     
 5、编写好了我们的业务实现类service,接着我们就开始编写我们的controller控制层的实现类,UserController、TreeController、RoleController.

UserController:


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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
1package com.mongo.sys.controller;
2
3
4import com.mongo.common.base.constant.SystemStaticConst;
5import com.mongo.common.base.controller.MongodbBaseController;
6import com.mongo.common.base.entity.Pagination;
7import com.mongo.common.base.service.MongodbBaseService;
8import com.mongo.common.util.user.UserInfo;
9import com.mongo.sys.entity.QueryUser;
10import com.mongo.sys.entity.Tree;
11import com.mongo.sys.entity.User;
12import com.mongo.sys.entity.UserRole;
13import com.mongo.sys.service.TreeService;
14import com.mongo.sys.service.UserRoleService;
15import com.mongo.sys.service.UserService;
16import org.springframework.beans.factory.annotation.Autowired;
17import org.springframework.data.mongodb.core.query.Query;
18import org.springframework.http.MediaType;
19import org.springframework.stereotype.Controller;
20import org.springframework.web.bind.annotation.RequestMapping;
21import org.springframework.web.bind.annotation.RequestMethod;
22import org.springframework.web.bind.annotation.ResponseBody;
23
24import java.util.HashMap;
25import java.util.List;
26import java.util.Map;
27
28@Controller
29@RequestMapping("/user")
30public class UserController extends MongodbBaseController<User,QueryUser> {
31
32    @Autowired
33    private UserService userService;
34    @Autowired
35    private UserRoleService userRoleService;
36    @Autowired
37    private TreeService treeService;
38
39    @Override
40    protected MongodbBaseService<User,QueryUser> getService() {
41        return userService;
42    }
43
44
45    /**
46     * 功能描述:更新用户状态为禁用/启用
47     * @param entity
48     * @return
49     */
50    @RequestMapping(value="/userControl")
51    @ResponseBody
52    public Map<String,Object> userControl(User entity) throws Exception{
53        Map<String,Object> result = new HashMap<String, Object>();
54        userService.userControl(entity);
55        result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
56        result.put(SystemStaticConst.MSG,"更新用户状态成功!");
57        result.put("entity",entity);
58        return result;
59    }
60
61    /**
62     * 功能描述:加载所有的权限数据
63     * @return
64     */
65    @RequestMapping(value = "/loadRoles",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
66    @ResponseBody
67    public Map<String,Object> loadRoles(){
68        Map<String,Object> result = new HashMap<String, Object>();
69        List<UserRole> userRoleList = userRoleService.find(new Query());
70        result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
71        result.put("list",userRoleList);
72        return result;
73    }
74
75    /**
76     * 功能描述:加载首页菜单节点的数据
77     * @return
78     */
79    @RequestMapping(value="/mainTree",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
80    @ResponseBody
81    public Map<String,Object> mainTree(){
82        Map<String,Object> result = new HashMap<String, Object>();
83        List<Tree> trees = UserInfo.loadUserTree(userRoleService,treeService);
84        result.put("data",trees);
85        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
86        return result;
87    }
88
89
90    /**
91     * 功能描述:获取用户的分页的数据
92     * @param entity
93     * @return
94     */
95    @RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
96    @ResponseBody
97    public Map<String,Object> list(QueryUser entity){
98        Map<String,Object> result = new HashMap<String, Object>();
99        Pagination page = userService.findByPage(entity);
100        result.put("totalCount",page.getTotalNumber());
101        result.put("result",page.getItems());
102        return result;
103    }
104}
105
106

TreeController


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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
1package com.mongo.sys.controller;
2
3
4import com.mongo.common.base.constant.SystemStaticConst;
5import com.mongo.common.base.controller.MongodbBaseController;
6import com.mongo.common.base.service.MongodbBaseService;
7import com.mongo.sys.entity.QueryTree;
8import com.mongo.sys.entity.Tree;
9import com.mongo.sys.service.TreeService;
10import org.springframework.beans.factory.annotation.Autowired;
11import org.springframework.data.mongodb.core.query.Query;
12import org.springframework.http.MediaType;
13import org.springframework.security.access.prepost.PreAuthorize;
14import org.springframework.stereotype.Controller;
15import org.springframework.ui.Model;
16import org.springframework.web.bind.annotation.RequestMapping;
17import org.springframework.web.bind.annotation.RequestMethod;
18import org.springframework.web.bind.annotation.ResponseBody;
19
20import java.util.HashMap;
21import java.util.List;
22import java.util.Map;
23
24@Controller
25@RequestMapping("/tree")
26public class TreeController  extends MongodbBaseController<Tree,QueryTree> {
27
28    @Autowired
29    private TreeService treeService;
30
31    @Override
32    protected MongodbBaseService<Tree, QueryTree> getService() {
33        return treeService;
34    }
35
36    /**
37     * 功能描述:跳转到修改菜单节点的页面
38     * @param entity
39     * @param model
40     * @return
41     * @throws Exception
42     */
43    @RequestMapping(value="/updateTreePage")
44    public String updateTreePage(Tree entity,Model model) throws Exception{
45        entity = treeService.get(entity.getId());
46        Tree pTree = null;
47        if(entity.getParentId().equals("5ac0c4a0c053f417ac310e3f")){
48            pTree = new Tree();
49            pTree.setId("5ac0c4a0c053f417ac310e3f");
50            pTree.setName("顶层节点");
51        }else{
52            pTree = treeService.get(entity.getParentId());
53        }
54        entity.setTree(pTree);
55        model.addAttribute("entity",entity);
56        return getPageBaseRoot()+UPDATEPAGE;
57    }
58
59    /**
60     * 功能描述:跳转到增加菜单节点的页面
61     * @param entity
62     * @param model
63     * @return
64     * @throws Exception
65     */
66    @RequestMapping(value="/addTreePage")
67    public String addPage(Tree entity,Model model) throws Exception{
68        if(entity.getId().equals("5ac0c4a0c053f417ac310e3f")){
69            entity = new Tree();
70            entity.setId("5ac0c4a0c053f417ac310e3f");
71            entity.setName("顶层节点");
72        }else{
73            entity = treeService.get(entity.getId());
74        }
75        model.addAttribute("entity",entity);
76        return getPageBaseRoot()+ADDPAGE;
77    }
78
79    /**
80     * 功能描述:直接加载整个菜单树的数据(且必须要有管理员权限才可以加载该菜单树的数据)
81     * @return
82     */
83    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
84    @RequestMapping(value = "/loadUserTree",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
85    @ResponseBody
86    public Map<String,Object> loadUserTree(){
87        Map<String,Object> result = new HashMap<String, Object>();
88        List<Tree> treeList = treeService.find(new Query());
89        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
90        result.put(SystemStaticConst.MSG,"加载菜单数据成功!");
91        result.put("data",treeList);
92        return result;
93    }
94}
95
96

RoleController


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
82
83
1package com.mongo.sys.controller;
2
3
4import com.mongo.common.base.constant.SystemStaticConst;
5import com.mongo.common.base.controller.MongodbBaseController;
6import com.mongo.common.base.entity.Pagination;
7import com.mongo.common.base.service.MongodbBaseService;
8import com.mongo.sys.entity.QueryUserRole;
9import com.mongo.sys.entity.Tree;
10import com.mongo.sys.entity.UserRole;
11import com.mongo.sys.service.TreeService;
12import com.mongo.sys.service.UserRoleService;
13import org.springframework.beans.factory.annotation.Autowired;
14import org.springframework.data.mongodb.core.query.Query;
15import org.springframework.http.MediaType;
16import org.springframework.security.access.prepost.PreAuthorize;
17import org.springframework.stereotype.Controller;
18import org.springframework.web.bind.annotation.RequestMapping;
19import org.springframework.web.bind.annotation.RequestMethod;
20import org.springframework.web.bind.annotation.ResponseBody;
21
22import java.util.HashMap;
23import java.util.List;
24import java.util.Map;
25
26@Controller
27@RequestMapping("/role")
28public class RoleController extends MongodbBaseController<UserRole,QueryUserRole> {
29
30    @Autowired
31    private UserRoleService userRoleService;
32
33    @Autowired
34    private TreeService treeService;
35
36    @Override
37    protected MongodbBaseService<UserRole, QueryUserRole> getService() {
38        return userRoleService;
39    }
40
41    /**
42     * 功能描述:获取用户的分页的数据
43     * @param entity
44     * @return
45     */
46    @RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
47    @ResponseBody
48    public Map<String,Object> list(QueryUserRole entity){
49        Map<String,Object> result = new HashMap<String, Object>();
50        Pagination<UserRole> page = userRoleService.findByPage(entity);
51        result.put("totalCount",page.getTotalNumber());
52        result.put("result",page.getItems());
53        return result;
54    }
55
56    /**
57     * 功能描述:根据用户的权限去加载角色数据
58     * @return
59     */
60    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
61    @RequestMapping(value = "/loadRoleTree",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
62    @ResponseBody
63    public Map<String,Object> loadRoleTree(UserRole entity){
64        entity = userRoleService.get(entity.getId()+"");
65        List<Tree> treeList = treeService.find(new Query());
66        if(entity!=null){
67            for(Tree tree:entity.getTreeList()){
68                treeList.stream().forEach(t->{
69                    if(t.getId().equals(tree.getId())){
70                        t.setChecked(true);
71                    }
72                });
73            }
74        }
75        Map<String,Object> result = new HashMap<String, Object>();
76        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
77        result.put("data",treeList);
78        return result;
79    }
80
81}
82
83

     
 到此处我们完成了这三个模块的集成工作,剩余的组织架构和数据字典模块,就请大家自己去我的github上直接下载就好了,此处就不再进行累述了。

       到此为止的GitHub项目地址:https://github.com/185594-5-27/csdn/tree/master-base-5

上一篇文章地址:基于spring boot和mongodb打造一套完整的权限架构(四)【完全集成security】

QQ交流群:578746866

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索