1. 程式人生 > >基於spring boot和mongodb打造一套完整的許可權架構(五)【整合使用者模組、選單模組、角色模組】

基於spring boot和mongodb打造一套完整的許可權架構(五)【整合使用者模組、選單模組、角色模組】

      在第四章我們已經實現了對security的整合,我們已經實現了登陸到我們的系統中了,但是大家會發現我們登陸成功以後並沒有顯示左側的選單節點,本章我們將開始整合使用者模組、選單模組以及角色模組。

      1、首先我們需要在sys的entity目錄底下建立Tree、QueryTree和QueryRole實體,以及修改user和UserRole實體內容如下:

Tree實體:

package com.mongo.sys.entity;

import net.sf.json.JSONObject;
import org.bson.types.ObjectId;

import java.util.List;

/**
 *@author linzf
 **/
public class Tree implements Comparable<Tree> {
	
	public Tree(){
		super();
	}

	public Tree(String id){
		this.id = new ObjectId(id);
	}



	private ObjectId id;
	private String code;
	private String icon;
	private String name;
	private ObjectId parentId;
	private long treeOrder;
	private String url;
	private String state;
	private boolean checked;
	private List<Tree> child;
	private Tree tree;

	public Tree getTree() {
		return tree;
	}

	public void setTree(Tree tree) {
		this.tree = tree;
	}

	public String getId() {
		if(id!=null){
			return id.toString();
		}else{
			return "";
		}
	}

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

	public String getParentId() {
		if(parentId!=null){
			return parentId.toString();
		}else{
			return "";
		}
	}

	public void setParentId(String parentId) {
		this.parentId = new ObjectId(parentId);;
	}

	public boolean isChecked() {
		return checked;
	}

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

	public List<Tree> getChild() {
		return child;
	}

	public void setChild(List<Tree> child) {
		this.child = child;
	}



	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getIcon() {
		return icon;
	}

	public void setIcon(String icon) {
		this.icon = icon;
	}

	public String getName() {
		return name;
	}

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

	public long getTreeOrder() {
		return treeOrder;
	}

	public void setTreeOrder(long treeOrder) {
		this.treeOrder = treeOrder;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	/**
	 * 功能描述:實現集合根據treeOrder欄位進行排序的功能
	 * @param o
	 * @return
	 */
	@Override
	public int compareTo(Tree o) {
		long i = this.getTreeOrder() - o.getTreeOrder();
		return Integer.parseInt(i+"");
	}
}

QueryTree查詢實體:

package com.mongo.sys.entity;


import com.mongo.common.base.entity.QueryBase;

public class QueryTree extends QueryBase {
}

QueryRole查詢實體:

package com.mongo.sys.entity;


import com.mongo.common.base.entity.QueryBase;
import com.mongo.common.base.entity.QueryField;
import com.mongo.common.base.entity.QueryType;

public class QueryUserRole extends QueryBase {

    @QueryField(type = QueryType.LIKE)
    private String name;
    @QueryField(type = QueryType.LIKE)
    private String roleName;

    public String getName() {
        return name;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}

 User修改以後實體內容如下:

package com.mongo.sys.entity;


import com.mongo.common.base.entity.QueryField;
import com.mongo.sys.dao.UserRoleDao;
import net.sf.json.JSONObject;
import org.bson.types.ObjectId;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/*
* 類描述:使用者實體類
* @auther linzf
* @create 2018/3/30 0030 
*/
public class User implements UserDetails {

    public static void main(String [] args){
        User user = new User();
        List<UserRole> roles = new ArrayList<UserRole>();
        UserRole userRole = new UserRole();
        userRole.setId("5ac0e051c053f4297804f42c");
        userRole.setName("ROLE_ADMIN");
        userRole.setRoleName("系統管理員");
        roles.add(userRole);
        user.setLogin("shyll");
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        user.setPassword(passwordEncoder.encode("123456"));
        user.setRoles(roles);
        user.setId(ObjectId.get().toString());
        user.setState("1");
        System.out.println(JSONObject.fromObject(user).toString());

    }


    private ObjectId id;
    // 增加QueryField註解在buildBaseQuery構建Query查詢條件的時候會自動將其加入到Query查詢條件中
    @QueryField
    private String login;
    private String password;
    private String userName;
    private String address;
    private String job;
    private Date birthDate;
    private String city;
    private String district;
    private String province;
    private String streetAddress;
    private String state;
    private String type;
    private Date lastLoginDate;
    // 使用者角色資訊
    private List<UserRole> roles;
    // 角色資訊集合
    private String roleArray;

    public String getRoleArray() {
        return roleArray;
    }

    public void setRoleArray(String roleArray) {
        this.roleArray = roleArray;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        if(this.getRoles()!=null){
            List<UserRole> roles=this.getRoles();
            for(UserRole role:roles){
                if(role.getName()!=null){
                    auths.add(new SimpleGrantedAuthority(role.getName()));
                }
            }
        }
        return auths;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.getLogin();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public String getId() {
        return id.toString();
    }

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

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getStreetAddress() {
        return streetAddress;
    }

    public void setStreetAddress(String streetAddress) {
        this.streetAddress = streetAddress;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Date getLastLoginDate() {
        return lastLoginDate;
    }

    public void setLastLoginDate(Date lastLoginDate) {
        this.lastLoginDate = lastLoginDate;
    }

    public List<UserRole> getRoles() {
        return roles;
    }

    public void setRoles(List<UserRole> roles) {
        this.roles = roles;
    }

    /**
     * 功能描述:組裝角色資料集合
     * @param roleArray
     * @param userRoleDao
     */
    public void packagingRoles(String roleArray,UserRoleDao userRoleDao){
        List<UserRole> roles = new ArrayList<UserRole>();
        if(roleArray!=null){
            UserRole userRole = null;
            for(String roleId:roleArray.split(",")){
                if(!roleId.isEmpty()){
                    userRole = new UserRole();
                    roles.add(userRoleDao.get(roleId));
                }
            }
        }
        this.setRoles(roles);
    }

}

UserRole修改以後實體內容如下:

package com.mongo.sys.entity;


import com.mongo.common.base.entity.QueryField;
import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.List;


/*
* 類描述:使用者角色實體類
* @auther linzf
* @create 2018/3/30 0030 
*/
public class UserRole {

    private ObjectId id;
    // 增加QueryField註解在buildBaseQuery構建Query查詢條件的時候會自動將其加入到Query查詢條件中
    @QueryField
    private String name;

    private String roleName;

    private List<Tree> treeList;

    // 臨時採訪選單數集合的資料
    private String treeArray;

    public List<Tree> getTreeList() {
        return treeList;
    }

    public void setTreeList(List<Tree> treeList) {
        this.treeList = treeList;
    }

    public String getTreeArray() {
        return treeArray;
    }

    public void setTreeArray(String treeArray) {
        this.treeArray = treeArray;
    }

    public String getId() {
        return id.toString();
    }

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

    public String getName() {
        return name;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public void packagingTrees(String treeArray){
        Tree tree = null;
        List<Tree> trees = new ArrayList<>();
        for(String id:treeArray.split(",")){
            if(!id.isEmpty()){
                tree = new Tree(id);
                trees.add(tree);
            }
        }
        this.setTreeList(trees);
    }

}

2、建立好選單的實體、角色實體以後我們就要開始編寫我們的選單的dao層和角色的dao層。

TreeDao資料庫層操作類內容如下:

package com.mongo.sys.dao;


import com.mongo.common.base.dao.MongodbBaseDao;
import com.mongo.sys.entity.QueryTree;
import com.mongo.sys.entity.Tree;
import org.springframework.stereotype.Component;

@Component
public class TreeDao extends MongodbBaseDao<Tree,QueryTree> {

}

UserRoleDao資料庫層操作類內容如下:

package com.mongo.sys.dao;


import com.mongo.common.base.dao.MongodbBaseDao;
import com.mongo.sys.entity.QueryUserRole;
import com.mongo.sys.entity.UserRole;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserRoleDao extends MongodbBaseDao<UserRole,QueryUserRole> {

    /**
     * 功能描述:根據角色ID的集合來獲取所有的角色資料
     * @param roles
     * @return
     */
    public List<UserRole> getUserRoleByRoleId(List<UserRole> roles){
        Query query = new Query();
        String [] ids = new String[roles.size()];
        for(int i=0;i<roles.size();i++){
            ids[i] = roles.get(i).getId();
        }
        query.addCriteria(Criteria.where("id").in(ids));
        return mongoTemplate.find(query,UserRole.class);
    }

}

 3、當我們編寫好我們的選單和角色的資料庫操作的dao層,首先我們要在util工具類底下建立一個選單節點遞迴類NodeUtil和使用者工具類UserInfo,主要是用於密碼加密以及獲取登陸的使用者資訊等,工具類程式碼如下:

NodeUtil工具類內容如下:

package com.mongo.common.util.node;







import com.mongo.sys.entity.Tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/*
* 類描述:
* @auther linzf
* @create 2017/9/20 0020 
*/
public class NodeUtil {

    private static List<Tree> returnList = new ArrayList<Tree>();

    /**
     * 根據父節點的ID獲取所有子節點
     * @param list 分類表
     * @param typeId 傳入的父節點ID
     * @return String
     */
    public static List<Tree> getChildNodes(List<Tree> list, String typeId) {
        returnList = new ArrayList<Tree>();
        if(list == null && typeId == null) return new ArrayList<Tree>();
        for (Iterator<Tree> iterator = list.iterator(); iterator.hasNext();) {
            Tree node = (Tree) iterator.next();
            // 一、根據傳入的某個父節點ID,遍歷該父節點的所有子節點
            if (node.getParentId().equals("5ac0c4a0c053f417ac310e3f") && typeId.equals(node.getId())) {
                recursionFn(list, node);
            }
            // 二、遍歷所有的父節點下的所有子節點
            if (node.getParentId().equals("5ac0c4a0c053f417ac310e3f")) {
                recursionFn(list, node);
            }
        }
        // 對頂層選單按照treeOrder從大到小進行進行排序
        Collections.sort(returnList);
        return returnList;
    }

    private static void recursionFn(List<Tree> list, Tree node) {
        List<Tree> childList = getChildList(list, node);// 得到子節點列表
        if (hasChild(list, node)) {// 判斷是否有子節點
            Iterator<Tree> it = childList.iterator();
            while (it.hasNext()) {
                Tree n = (Tree) it.next();
                if(hasChild(list,n)){// 判斷子節點是否還有相應的子節點,若有則再次遞迴遍歷
                    recursionFn(list, n);
                }
            }
            node.setChild(childList);
            returnList.add(node);
        }
    }

    // 得到子節點列表
    private static List<Tree> getChildList(List<Tree> list, Tree node) {
        List<Tree> nodeList = new ArrayList<Tree>();
        Iterator<Tree> it = list.iterator();
        while (it.hasNext()) {
            Tree n = (Tree) it.next();
            if (n.getParentId().equals(node.getId())) {
                nodeList.add(n);
            }
        }
        Collections.sort(nodeList);
        return nodeList;
    }

    // 判斷是否有子節點
    private static boolean hasChild(List<Tree> list, Tree node) {
        return getChildList(list, node).size() > 0 ? true : false;
    }

}

UserInfo工具類內容如下:

package com.mongo.common.util.user;




import com.mongo.common.util.node.NodeUtil;
import com.mongo.sys.entity.Tree;
import com.mongo.sys.entity.User;
import com.mongo.sys.entity.UserRole;
import com.mongo.sys.service.TreeService;
import com.mongo.sys.service.UserRoleService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @auher linzf
 * @since 2018-03-31
 */
public class UserInfo {

    /**
     * 功能描述:載入選單節點的資料
     * @return
     */
    public static List<Tree> loadUserTree(UserRoleService userRoleService, TreeService treeService){
        Map<String,Tree> treeMap = new HashMap<String,Tree>();
        User user = getUser();
        List<UserRole> userRoleList = userRoleService.getUserRoleByRoleId(user);
        for(UserRole userRole:userRoleList){
            for(Tree tree:userRole.getTreeList()){
                treeMap.put(tree.getId(),treeService.get(tree.getId()));
            }
        }
        List<Tree> treeList = NodeUtil.getChildNodes(new ArrayList<Tree>(treeMap.values()),"5ac0c4a0c053f417ac310e3f");
        return treeList;
    }

    /**
     * 功能描述:實現對密碼進行bcrypt加密
     * @param password
     * @return
     */
    public static String encode(String password){
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 功能描述:獲取當前登陸的使用者的資訊
     * 註釋:強轉一個null物件不會產生報錯
     * @return
     */
    public static User getUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        return (User)Optional.ofNullable(securityContextImpl.getAuthentication().getPrincipal()).orElse(null);
    }

    /**
     * 功能描述:獲取當前登陸的使用者的許可權集合
     * @return
     */
    public static List<GrantedAuthority> getGrantedAuthority(){
        return (List<GrantedAuthority>)Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).orElse(new ArrayList<>());
    }

    /**
     * 功能描述:判斷當前的使用者是否包含某一個許可權
     * @param authority
     * 註釋:
     *      allMatch:Stream 中全部元素符合傳入的 predicate,返回 true
     *      anyMatch:Stream 中只要有一個元素符合傳入的 predicate,返回 true
     *      noneMatch:Stream 中沒有一個元素符合傳入的 predicate,返回 true
     * @return
     */
    public static boolean hasAuthority(String authority){
        return getGrantedAuthority().stream().anyMatch(obj->obj.getAuthority().equalsIgnoreCase(authority));
    }

}

 4、編寫好我們的工具類以後我們就可以正式開始編寫我們的使用者、角色、選單的service業務實現類。

TreeService內容如下:

package com.mongo.sys.service;


import com.mongo.common.base.dao.MongodbBaseDao;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.sys.dao.TreeDao;
import com.mongo.sys.entity.QueryTree;
import com.mongo.sys.entity.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TreeService extends MongodbBaseService<Tree,QueryTree> {

    @Autowired
    private TreeDao treeDao;

    @Override
    protected MongodbBaseDao<Tree, QueryTree> getDao() {
        return treeDao;
    }
}

UserRoleService內容如下:

package com.mongo.sys.service;


import com.mongo.common.base.dao.MongodbBaseDao;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.sys.dao.UserRoleDao;
import com.mongo.sys.entity.QueryUserRole;
import com.mongo.sys.entity.User;
import com.mongo.sys.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRoleService extends MongodbBaseService<UserRole,QueryUserRole> {

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    protected MongodbBaseDao<UserRole, QueryUserRole> getDao() {
        return userRoleDao;
    }

    @Override
    public UserRole save(UserRole entity) {
        entity.packagingTrees(entity.getTreeArray());
        return super.save(entity);
    }

    @Override
    public void updateById(String id, UserRole entity) {
        entity.packagingTrees(entity.getTreeArray());
        super.updateById(id, entity);
    }



    /**
     * 功能描述:根據使用者來獲取使用者相應的角色以及他的選單資料
     * @param user
     * @return
     */
    public List<UserRole> getUserRoleByRoleId(User user){
        return userRoleDao.getUserRoleByRoleId(user.getRoles());
    }
}

UserService內容如下:

package com.mongo.sys.service;


import com.mongo.common.base.dao.MongodbBaseDao;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.common.util.user.UserInfo;
import com.mongo.sys.dao.UserDao;
import com.mongo.sys.dao.UserRoleDao;
import com.mongo.sys.entity.QueryUser;
import com.mongo.sys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * 功能描述:實現使用者管理的service
 */
@Service
public class UserService extends MongodbBaseService<User,QueryUser> {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    protected MongodbBaseDao<User,QueryUser> getDao() {
        return userDao;
    }

    /**
     * 功能描述:更新使用者狀態為可用或者不可用
     * @param user
     * @return
     */
    public void userControl(User user){
        userDao.userControl(user);
    }


    @Override
    public void updateById(String id, User user) {
        user.packagingRoles(user.getRoleArray(),userRoleDao);
        super.updateById(id, user);
    }

    @Override
    public User save(User entity) {
        entity.setAddress(entity.getProvince()+entity.getCity()+entity.getDistrict()+entity.getStreetAddress());
        entity.setPassword(UserInfo.encode(entity.getPassword()));
        entity.setState("1");
        entity.packagingRoles(entity.getRoleArray(),userRoleDao);
        return super.save(entity);
    }

    /**
     * 功能描述:根據賬號來獲取使用者資訊
     * @param login
     * @return
     */
    public User findByLogin(String login){
        return userDao.findByLogin(login);
    }

}

 5、編寫好了我們的業務實現類service,接著我們就開始編寫我們的controller控制層的實現類,UserController、TreeController、RoleController.

UserController:

package com.mongo.sys.controller;


import com.mongo.common.base.constant.SystemStaticConst;
import com.mongo.common.base.controller.MongodbBaseController;
import com.mongo.common.base.entity.Pagination;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.common.util.user.UserInfo;
import com.mongo.sys.entity.QueryUser;
import com.mongo.sys.entity.Tree;
import com.mongo.sys.entity.User;
import com.mongo.sys.entity.UserRole;
import com.mongo.sys.service.TreeService;
import com.mongo.sys.service.UserRoleService;
import com.mongo.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/user")
public class UserController extends MongodbBaseController<User,QueryUser> {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private TreeService treeService;

    @Override
    protected MongodbBaseService<User,QueryUser> getService() {
        return userService;
    }


    /**
     * 功能描述:更新使用者狀態為禁用/啟用
     * @param entity
     * @return
     */
    @RequestMapping(value="/userControl")
    @ResponseBody
    public Map<String,Object> userControl(User entity) throws Exception{
        Map<String,Object> result = new HashMap<String, Object>();
        userService.userControl(entity);
        result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
        result.put(SystemStaticConst.MSG,"更新使用者狀態成功!");
        result.put("entity",entity);
        return result;
    }

    /**
     * 功能描述:載入所有的許可權資料
     * @return
     */
    @RequestMapping(value = "/loadRoles",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> loadRoles(){
        Map<String,Object> result = new HashMap<String, Object>();
        List<UserRole> userRoleList = userRoleService.find(new Query());
        result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
        result.put("list",userRoleList);
        return result;
    }

    /**
     * 功能描述:載入首頁選單節點的資料
     * @return
     */
    @RequestMapping(value="/mainTree",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> mainTree(){
        Map<String,Object> result = new HashMap<String, Object>();
        List<Tree> trees = UserInfo.loadUserTree(userRoleService,treeService);
        result.put("data",trees);
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        return result;
    }


    /**
     * 功能描述:獲取使用者的分頁的資料
     * @param entity
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> list(QueryUser entity){
        Map<String,Object> result = new HashMap<String, Object>();
        Pagination page = userService.findByPage(entity);
        result.put("totalCount",page.getTotalNumber());
        result.put("result",page.getItems());
        return result;
    }
}

TreeController

package com.mongo.sys.controller;


import com.mongo.common.base.constant.SystemStaticConst;
import com.mongo.common.base.controller.MongodbBaseController;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.sys.entity.QueryTree;
import com.mongo.sys.entity.Tree;
import com.mongo.sys.service.TreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/tree")
public class TreeController  extends MongodbBaseController<Tree,QueryTree> {

    @Autowired
    private TreeService treeService;

    @Override
    protected MongodbBaseService<Tree, QueryTree> getService() {
        return treeService;
    }

    /**
     * 功能描述:跳轉到修改選單節點的頁面
     * @param entity
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/updateTreePage")
    public String updateTreePage(Tree entity,Model model) throws Exception{
        entity = treeService.get(entity.getId());
        Tree pTree = null;
        if(entity.getParentId().equals("5ac0c4a0c053f417ac310e3f")){
            pTree = new Tree();
            pTree.setId("5ac0c4a0c053f417ac310e3f");
            pTree.setName("頂層節點");
        }else{
            pTree = treeService.get(entity.getParentId());
        }
        entity.setTree(pTree);
        model.addAttribute("entity",entity);
        return getPageBaseRoot()+UPDATEPAGE;
    }

    /**
     * 功能描述:跳轉到增加選單節點的頁面
     * @param entity
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/addTreePage")
    public String addPage(Tree entity,Model model) throws Exception{
        if(entity.getId().equals("5ac0c4a0c053f417ac310e3f")){
            entity = new Tree();
            entity.setId("5ac0c4a0c053f417ac310e3f");
            entity.setName("頂層節點");
        }else{
            entity = treeService.get(entity.getId());
        }
        model.addAttribute("entity",entity);
        return getPageBaseRoot()+ADDPAGE;
    }

    /**
     * 功能描述:直接載入整個選單樹的資料(且必須要有管理員許可權才可以載入該選單樹的資料)
     * @return
     */
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/loadUserTree",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> loadUserTree(){
        Map<String,Object> result = new HashMap<String, Object>();
        List<Tree> treeList = treeService.find(new Query());
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put(SystemStaticConst.MSG,"載入選單資料成功!");
        result.put("data",treeList);
        return result;
    }
}

RoleController

package com.mongo.sys.controller;


import com.mongo.common.base.constant.SystemStaticConst;
import com.mongo.common.base.controller.MongodbBaseController;
import com.mongo.common.base.entity.Pagination;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.sys.entity.QueryUserRole;
import com.mongo.sys.entity.Tree;
import com.mongo.sys.entity.UserRole;
import com.mongo.sys.service.TreeService;
import com.mongo.sys.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/role")
public class RoleController extends MongodbBaseController<UserRole,QueryUserRole> {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private TreeService treeService;

    @Override
    protected MongodbBaseService<UserRole, QueryUserRole> getService() {
        return userRoleService;
    }

    /**
     * 功能描述:獲取使用者的分頁的資料
     * @param entity
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> list(QueryUserRole entity){
        Map<String,Object> result = new HashMap<String, Object>();
        Pagination<UserRole> page = userRoleService.findByPage(entity);
        result.put("totalCount",page.getTotalNumber());
        result.put("result",page.getItems());
        return result;
    }

    /**
     * 功能描述:根據使用者的許可權去載入角色資料
     * @return
     */
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/loadRoleTree",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> loadRoleTree(UserRole entity){
        entity = userRoleService.get(entity.getId()+"");
        List<Tree> treeList = treeService.find(new Query());
        if(entity!=null){
            for(Tree tree:entity.getTreeList()){
                treeList.stream().forEach(t->{
                    if(t.getId().equals(tree.getId())){
                        t.setChecked(true);
                    }
                });
            }
        }
        Map<String,Object> result = new HashMap<String, Object>();
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put("data",treeList);
        return result;
    }

}

 到此處我們完成了這三個模組的整合工作,剩餘的組織架構和資料字典模組,就請大家自己去我的github上直接下載就好了,此處就不再進行累述了。

QQ交流群:578746866