基于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上直接下载就好了,此处就不再进行累述了。

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

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

QQ交流群:578746866

猜你喜欢

转载自blog.csdn.net/linzhefeng89/article/details/79974124
今日推荐