1 domain.java
package com.ruoyi.project.system.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.framework.aspectj.lang.annotation.Excel;
import com.ruoyi.framework.aspectj.lang.annotation.Excel.ColumnType;
import com.ruoyi.framework.web.domain.BaseEntity;
/**
* 角色表 sys_role
*/
public class SysRole extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 角色ID */
@Excel(name = "角色序号", cellType = ColumnType.NUMERIC)
private Long roleId;
/** 角色名称 */
@Excel(name = "角色名称")
private String roleName;
/** 角色权限 */
@Excel(name = "角色权限")
private String roleKey;
/** 角色排序 */
@Excel(name = "角色排序")
private String roleSort;
/** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限) */
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限")
private String dataScope;
/** 菜单树选择项是否关联显示( 0:父子不互相关联显示 1:父子互相关联显示) */
private boolean menuCheckStrictly;
/** 部门树选择项是否关联显示(0:父子不互相关联显示 1:父子互相关联显示 ) */
private boolean deptCheckStrictly;
/** 角色状态(0正常 1停用) */
@Excel(name = "角色状态", readConverterExp = "0=正常,1=停用")
private String status;
/** 删除标志(0代表存在 2代表删除) */
private String delFlag;
/** 用户是否存在此角色标识 默认不存在 */
private boolean flag = false;
/** 菜单组 */
private Long[] menuIds;
/** 部门组(数据权限) */
private Long[] deptIds;
public SysRole()
{
}
public SysRole(Long roleId)
{
this.roleId = roleId;
}
public Long getRoleId()
{
return roleId;
}
public void setRoleId(Long roleId)
{
this.roleId = roleId;
}
public boolean isAdmin()
{
return isAdmin(this.roleId);
}
public static boolean isAdmin(Long roleId)
{
return roleId != null && 1L == roleId;
}
@NotBlank(message = "角色名称不能为空")
@Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符")
public String getRoleName()
{
return roleName;
}
public void setRoleName(String roleName)
{
this.roleName = roleName;
}
@NotBlank(message = "权限字符不能为空")
@Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符")
public String getRoleKey()
{
return roleKey;
}
public void setRoleKey(String roleKey)
{
this.roleKey = roleKey;
}
@NotBlank(message = "显示顺序不能为空")
public String getRoleSort()
{
return roleSort;
}
public void setRoleSort(String roleSort)
{
this.roleSort = roleSort;
}
public String getDataScope()
{
return dataScope;
}
public void setDataScope(String dataScope)
{
this.dataScope = dataScope;
}
public boolean isMenuCheckStrictly()
{
return menuCheckStrictly;
}
public void setMenuCheckStrictly(boolean menuCheckStrictly)
{
this.menuCheckStrictly = menuCheckStrictly;
}
public boolean isDeptCheckStrictly()
{
return deptCheckStrictly;
}
public void setDeptCheckStrictly(boolean deptCheckStrictly)
{
this.deptCheckStrictly = deptCheckStrictly;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getDelFlag()
{
return delFlag;
}
public void setDelFlag(String delFlag)
{
this.delFlag = delFlag;
}
public boolean isFlag()
{
return flag;
}
public void setFlag(boolean flag)
{
this.flag = flag;
}
public Long[] getMenuIds()
{
return menuIds;
}
public void setMenuIds(Long[] menuIds)
{
this.menuIds = menuIds;
}
public Long[] getDeptIds()
{
return deptIds;
}
public void setDeptIds(Long[] deptIds)
{
this.deptIds = deptIds;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("roleId", getRoleId())
.append("roleName", getRoleName())
.append("roleKey", getRoleKey())
.append("roleSort", getRoleSort())
.append("dataScope", getDataScope())
.append("menuCheckStrictly", isMenuCheckStrictly())
.append("deptCheckStrictly", isDeptCheckStrictly())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}
2 mapper.java
package com.ruoyi.project.system.mapper;
import java.util.List;
import com.ruoyi.project.system.domain.SysRole;
/**
* 角色表 数据层
*/
public interface SysRoleMapper
{
/**
* 根据条件分页查询角色数据
*
* @param role 角色信息
* @return 角色数据集合信息
*/
public List<SysRole> selectRoleList(SysRole role);
/**
* 根据用户ID查询角色
*
* @param userId 用户ID
* @return 角色列表
*/
public List<SysRole> selectRolePermissionByUserId(Long userId);
/**
* 查询所有角色
*
* @return 角色列表
*/
public List<SysRole> selectRoleAll();
/**
* 根据用户ID获取角色选择框列表
*
* @param userId 用户ID
* @return 选中角色ID列表
*/
public List<Integer> selectRoleListByUserId(Long userId);
/**
* 通过角色ID查询角色
*
* @param roleId 角色ID
* @return 角色对象信息
*/
public SysRole selectRoleById(Long roleId);
/**
* 根据用户ID查询角色
*
* @param userName 用户名
* @return 角色列表
*/
public List<SysRole> selectRolesByUserName(String userName);
/**
* 校验角色名称是否唯一
*
* @param roleName 角色名称
* @return 角色信息
*/
public SysRole checkRoleNameUnique(String roleName);
/**
* 校验角色权限是否唯一
*
* @param roleKey 角色权限
* @return 角色信息
*/
public SysRole checkRoleKeyUnique(String roleKey);
/**
* 修改角色信息
*
* @param role 角色信息
* @return 结果
*/
public int updateRole(SysRole role);
/**
* 新增角色信息
*
* @param role 角色信息
* @return 结果
*/
public int insertRole(SysRole role);
/**
* 通过角色ID删除角色
*
* @param roleId 角色ID
* @return 结果
*/
public int deleteRoleById(Long roleId);
/**
* 批量删除角色信息
*
* @param roleIds 需要删除的角色ID
* @return 结果
*/
public int deleteRoleByIds(Long[] roleIds);
}
3 service.java
package com.ruoyi.project.system.service;
import java.util.List;
import java.util.Set;
import com.ruoyi.project.system.domain.SysRole;
/**
* 角色业务层
*
* @author ruoyi
*/
public interface ISysRoleService
{
/**
* 根据条件分页查询角色数据
*
* @param role 角色信息
* @return 角色数据集合信息
*/
public List<SysRole> selectRoleList(SysRole role);
/**
* 根据用户ID查询角色
*
* @param userId 用户ID
* @return 权限列表
*/
public Set<String> selectRolePermissionByUserId(Long userId);
/**
* 查询所有角色
*
* @return 角色列表
*/
public List<SysRole> selectRoleAll();
/**
* 根据用户ID获取角色选择框列表
*
* @param userId 用户ID
* @return 选中角色ID列表
*/
public List<Integer> selectRoleListByUserId(Long userId);
/**
* 通过角色ID查询角色
*
* @param roleId 角色ID
* @return 角色对象信息
*/
public SysRole selectRoleById(Long roleId);
/**
* 校验角色名称是否唯一
*
* @param role 角色信息
* @return 结果
*/
public String checkRoleNameUnique(SysRole role);
/**
* 校验角色权限是否唯一
*
* @param role 角色信息
* @return 结果
*/
public String checkRoleKeyUnique(SysRole role);
/**
* 校验角色是否允许操作
*
* @param role 角色信息
*/
public void checkRoleAllowed(SysRole role);
/**
* 通过角色ID查询角色使用数量
*
* @param roleId 角色ID
* @return 结果
*/
public int countUserRoleByRoleId(Long roleId);
/**
* 新增保存角色信息
*
* @param role 角色信息
* @return 结果
*/
public int insertRole(SysRole role);
/**
* 修改保存角色信息
*
* @param role 角色信息
* @return 结果
*/
public int updateRole(SysRole role);
/**
* 修改角色状态
*
* @param role 角色信息
* @return 结果
*/
public int updateRoleStatus(SysRole role);
/**
* 修改数据权限信息
*
* @param role 角色信息
* @return 结果
*/
public int authDataScope(SysRole role);
/**
* 通过角色ID删除角色
*
* @param roleId 角色ID
* @return 结果
*/
public int deleteRoleById(Long roleId);
/**
* 批量删除角色信息
*
* @param roleIds 需要删除的角色ID
* @return 结果
*/
public int deleteRoleByIds(Long[] roleIds);
}
4 serviceImpl.java
package com.ruoyi.project.system.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysRoleDept;
import com.ruoyi.project.system.domain.SysRoleMenu;
import com.ruoyi.project.system.mapper.SysRoleDeptMapper;
import com.ruoyi.project.system.mapper.SysRoleMapper;
import com.ruoyi.project.system.mapper.SysRoleMenuMapper;
import com.ruoyi.project.system.mapper.SysUserRoleMapper;
import com.ruoyi.project.system.service.ISysRoleService;
/**
* 角色 业务层处理
*/
@Service
public class SysRoleServiceImpl implements ISysRoleService
{
@Autowired
private SysRoleMapper roleMapper;
@Autowired
private SysRoleMenuMapper roleMenuMapper;
@Autowired
private SysUserRoleMapper userRoleMapper;
@Autowired
private SysRoleDeptMapper roleDeptMapper;
/**
* 根据条件分页查询角色数据
*
* @param role 角色信息
* @return 角色数据集合信息
*/
@Override
@DataScope(deptAlias = "d")
public List<SysRole> selectRoleList(SysRole role)
{
return roleMapper.selectRoleList(role);
}
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
@Override
public Set<String> selectRolePermissionByUserId(Long userId)
{
List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (SysRole perm : perms)
{
if (StringUtils.isNotNull(perm))
{
permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
}
}
return permsSet;
}
/**
* 查询所有角色
*
* @return 角色列表
*/
@Override
public List<SysRole> selectRoleAll()
{
return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
}
/**
* 根据用户ID获取角色选择框列表
*
* @param userId 用户ID
* @return 选中角色ID列表
*/
@Override
public List<Integer> selectRoleListByUserId(Long userId)
{
return roleMapper.selectRoleListByUserId(userId);
}
/**
* 通过角色ID查询角色
*
* @param roleId 角色ID
* @return 角色对象信息
*/
@Override
public SysRole selectRoleById(Long roleId)
{
return roleMapper.selectRoleById(roleId);
}
/**
* 校验角色名称是否唯一
*
* @param role 角色信息
* @return 结果
*/
@Override
public String checkRoleNameUnique(SysRole role)
{
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
{
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}
/**
* 校验角色权限是否唯一
*
* @param role 角色信息
* @return 结果
*/
@Override
public String checkRoleKeyUnique(SysRole role)
{
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
{
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}
/**
* 校验角色是否允许操作
*
* @param role 角色信息
*/
@Override
public void checkRoleAllowed(SysRole role)
{
if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin())
{
throw new CustomException("不允许操作超级管理员角色");
}
}
/**
* 通过角色ID查询角色使用数量
*
* @param roleId 角色ID
* @return 结果
*/
@Override
public int countUserRoleByRoleId(Long roleId)
{
return userRoleMapper.countUserRoleByRoleId(roleId);
}
/**
* 新增保存角色信息
*
* @param role 角色信息
* @return 结果
*/
@Override
@Transactional
public int insertRole(SysRole role)
{
// 新增角色信息
roleMapper.insertRole(role);
return insertRoleMenu(role);
}
/**
* 修改保存角色信息
*
* @param role 角色信息
* @return 结果
*/
@Override
@Transactional
public int updateRole(SysRole role)
{
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
return insertRoleMenu(role);
}
/**
* 修改角色状态
*
* @param role 角色信息
* @return 结果
*/
@Override
public int updateRoleStatus(SysRole role)
{
return roleMapper.updateRole(role);
}
/**
* 修改数据权限信息
*
* @param role 角色信息
* @return 结果
*/
@Override
@Transactional
public int authDataScope(SysRole role)
{
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与部门关联
roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
// 新增角色和部门信息(数据权限)
return insertRoleDept(role);
}
/**
* 新增角色菜单信息
*
* @param role 角色对象
*/
public int insertRoleMenu(SysRole role)
{
int rows = 1;
// 新增用户与角色管理
List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
for (Long menuId : role.getMenuIds())
{
SysRoleMenu rm = new SysRoleMenu();
rm.setRoleId(role.getRoleId());
rm.setMenuId(menuId);
list.add(rm);
}
if (list.size() > 0)
{
rows = roleMenuMapper.batchRoleMenu(list);
}
return rows;
}
/**
* 新增角色部门信息(数据权限)
*
* @param role 角色对象
*/
public int insertRoleDept(SysRole role)
{
int rows = 1;
// 新增角色与部门(数据权限)管理
List<SysRoleDept> list = new ArrayList<SysRoleDept>();
for (Long deptId : role.getDeptIds())
{
SysRoleDept rd = new SysRoleDept();
rd.setRoleId(role.getRoleId());
rd.setDeptId(deptId);
list.add(rd);
}
if (list.size() > 0)
{
rows = roleDeptMapper.batchRoleDept(list);
}
return rows;
}
/**
* 通过角色ID删除角色
*
* @param roleId 角色ID
* @return 结果
*/
@Override
@Transactional
public int deleteRoleById(Long roleId)
{
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(roleId);
// 删除角色与部门关联
roleDeptMapper.deleteRoleDeptByRoleId(roleId);
return roleMapper.deleteRoleById(roleId);
}
/**
* 批量删除角色信息
*
* @param roleIds 需要删除的角色ID
* @return 结果
*/
@Override
@Transactional
public int deleteRoleByIds(Long[] roleIds)
{
for (Long roleId : roleIds)
{
checkRoleAllowed(new SysRole(roleId));
SysRole role = selectRoleById(roleId);
if (countUserRoleByRoleId(roleId) > 0)
{
throw new CustomException(String.format("%1$s已分配,不能删除", role.getRoleName()));
}
}
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenu(roleIds);
// 删除角色与部门关联
roleDeptMapper.deleteRoleDept(roleIds);
return roleMapper.deleteRoleByIds(roleIds);
}
}
5 controller.java
package com.ruoyi.project.system.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.SysPermissionService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.service.ISysRoleService;
import com.ruoyi.project.system.service.ISysUserService;
/**
* 角色信息
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
@Autowired
private ISysRoleService roleService;
@Autowired
private TokenService tokenService;
@Autowired
private SysPermissionService permissionService;
@Autowired
private ISysUserService userService;
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role)
{
startPage();
List<SysRole> list = roleService.selectRoleList(role);
return getDataTable(list);
}
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@GetMapping("/export")
public AjaxResult export(SysRole role)
{
List<SysRole> list = roleService.selectRoleList(role);
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
return util.exportExcel(list, "角色数据");
}
/**
* 根据角色编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public AjaxResult getInfo(@PathVariable Long roleId)
{
return AjaxResult.success(roleService.selectRoleById(roleId));
}
/**
* 新增角色
*/
@PreAuthorize("@ss.hasPermi('system:role:add')")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysRole role)
{
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
{
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
{
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setCreateBy(SecurityUtils.getUsername());
return toAjax(roleService.insertRole(role));
}
/**
* 修改保存角色
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
{
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
{
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setUpdateBy(SecurityUtils.getUsername());
if (roleService.updateRole(role) > 0)
{
// 更新缓存用户权限
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
{
loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
tokenService.setLoginUser(loginUser);
}
return AjaxResult.success();
}
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
* 修改保存数据权限
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public AjaxResult dataScope(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
return toAjax(roleService.authDataScope(role));
}
/**
* 状态修改
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
role.setUpdateBy(SecurityUtils.getUsername());
return toAjax(roleService.updateRoleStatus(role));
}
/**
* 删除角色
*/
@PreAuthorize("@ss.hasPermi('system:role:remove')")
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public AjaxResult remove(@PathVariable Long[] roleIds)
{
return toAjax(roleService.deleteRoleByIds(roleIds));
}
/**
* 获取角色选择框列表
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
return AjaxResult.success(roleService.selectRoleAll());
}
}
6 mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.project.system.mapper.SysRoleMapper">
<resultMap type="SysRole" id="SysRoleResult">
<id property="roleId" column="role_id" />
<result property="roleName" column="role_name" />
<result property="roleKey" column="role_key" />
<result property="roleSort" column="role_sort" />
<result property="dataScope" column="data_scope" />
<result property="menuCheckStrictly" column="menu_check_strictly" />
<result property="deptCheckStrictly" column="dept_check_strictly" />
<result property="status" column="status" />
<result property="delFlag" column="del_flag" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectRoleVo">
select distinct r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.menu_check_strictly, r.dept_check_strictly,
r.status, r.del_flag, r.create_time, r.remark
from sys_role r
left join sys_user_role ur on ur.role_id = r.role_id
left join sys_user u on u.user_id = ur.user_id
left join sys_dept d on u.dept_id = d.dept_id
</sql>
<select id="selectRoleList" parameterType="SysRole" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.del_flag = '0'
<if test="roleName != null and roleName != ''">
AND r.role_name like concat(concat('%',#{roleName}),'%')
</if>
<if test="status != null and status != ''">
AND r.status = #{status}
</if>
<if test="roleKey != null and roleKey != ''">
AND r.role_key like concat(concat('%',#{roleKey}),'%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and r.create_time >= to_date(#{params.beginTime},'yyyy-MM-dd HH24:mi:ss')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and r.create_time <= to_date(#{params.endTime},'yyyy-MM-dd HH24:mi:ss')
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
order by r.role_sort
</select>
<select id="selectRolePermissionByUserId" parameterType="Long" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
WHERE r.del_flag = '0' and ur.user_id = #{userId}
</select>
<select id="selectRoleAll" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
</select>
<select id="selectRoleListByUserId" parameterType="Long" resultType="Integer">
select r.role_id
from sys_role r
left join sys_user_role ur on ur.role_id = r.role_id
left join sys_user u on u.user_id = ur.user_id
where u.user_id = #{userId}
</select>
<select id="selectRoleById" parameterType="Long" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.role_id = #{roleId}
</select>
<select id="selectRolesByUserName" parameterType="String" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
WHERE r.del_flag = '0' and u.user_name = #{userName}
</select>
<select id="checkRoleNameUnique" parameterType="String" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.role_name=#{roleName} and rownum <![CDATA[ <= ]]> 1
</select>
<select id="checkRoleKeyUnique" parameterType="String" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
where r.role_key=#{roleKey} and rownum <![CDATA[ <= ]]> 1
</select>
<insert id="insertRole" parameterType="SysRole" useGeneratedKeys="true" keyProperty="roleId">
<selectKey keyProperty="roleId" order="BEFORE" resultType="Long">
select seq_sys_role.nextval as roleId from DUAL
</selectKey>
insert into sys_role(
<if test="roleId != null and roleId != 0">role_id,</if>
<if test="roleName != null and roleName != ''">role_name,</if>
<if test="roleKey != null and roleKey != ''">role_key,</if>
<if test="roleSort != null and roleSort != ''">role_sort,</if>
<if test="dataScope != null and dataScope != ''">data_scope,</if>
<if test="menuCheckStrictly != null">menu_check_strictly,</if>
<if test="deptCheckStrictly != null">dept_check_strictly,</if>
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="roleId != null and roleId != 0">#{roleId},</if>
<if test="roleName != null and roleName != ''">#{roleName},</if>
<if test="roleKey != null and roleKey != ''">#{roleKey},</if>
<if test="roleSort != null and roleSort != ''">#{roleSort},</if>
<if test="dataScope != null and dataScope != ''">#{dataScope},</if>
<if test="menuCheckStrictly != null">#{menuCheckStrictly},</if>
<if test="deptCheckStrictly != null">#{deptCheckStrictly},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate
)
</insert>
<update id="updateRole" parameterType="SysRole">
update sys_role
<set>
<if test="roleName != null and roleName != ''">role_name = #{roleName},</if>
<if test="roleKey != null and roleKey != ''">role_key = #{roleKey},</if>
<if test="roleSort != null and roleSort != ''">role_sort = #{roleSort},</if>
<if test="dataScope != null and dataScope != ''">data_scope = #{dataScope},</if>
<if test="menuCheckStrictly != null">menu_check_strictly = #{menuCheckStrictly},</if>
<if test="deptCheckStrictly != null">dept_check_strictly = #{deptCheckStrictly},</if>
<if test="status != null and status != ''">status = #{status},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate
</set>
where role_id = #{roleId}
</update>
<update id="updateRoleStatus" parameterType="SysRole">
update sys_user set status = #{status} where user_id = #{userId}
</update>
<delete id="deleteRoleById" parameterType="Long">
delete from sys_role where role_id = #{roleId}
</delete>
<delete id="deleteRoleByIds" parameterType="Long">
update sys_role set del_flag = '2' where role_id in
<foreach collection="array" item="roleId" open="(" separator="," close=")">
#{roleId}
</foreach>
</delete>
</mapper>
7 api.js
import request from '@/utils/request'
// 查询角色列表
export function listRole(query) {
return request({
url: '/system/role/list',
method: 'get',
params: query
})
}
// 查询角色详细
export function getRole(roleId) {
return request({
url: '/system/role/' + roleId,
method: 'get'
})
}
// 新增角色
export function addRole(data) {
return request({
url: '/system/role',
method: 'post',
data: data
})
}
// 修改角色
export function updateRole(data) {
return request({
url: '/system/role',
method: 'put',
data: data
})
}
// 角色数据权限
export function dataScope(data) {
return request({
url: '/system/role/dataScope',
method: 'put',
data: data
})
}
// 角色状态修改
export function changeRoleStatus(roleId, status) {
const data = {
roleId,
status
}
return request({
url: '/system/role/changeStatus',
method: 'put',
data: data
})
}
// 删除角色
export function delRole(roleId) {
return request({
url: '/system/role/' + roleId,
method: 'delete'
})
}
// 导出角色
export function exportRole(query) {
return request({
url: '/system/role/export',
method: 'get',
params: query
})
}
8 index.vue
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
<el-form-item label="角色名称" prop="roleName">
<el-input
v-model="queryParams.roleName"
placeholder="请输入角色名称"
clearable
size="small"
style="width: 240px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="权限字符" prop="roleKey">
<el-input
v-model="queryParams.roleKey"
placeholder="请输入权限字符"
clearable
size="small"
style="width: 240px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item label="状态" prop="status">
<el-select
v-model="queryParams.status"
placeholder="角色状态"
clearable
size="small"
style="width: 240px"
>
<el-option
v-for="dict in statusOptions"
:key="dict.dictValue"
:label="dict.dictLabel"
:value="dict.dictValue"
/>
</el-select>
</el-form-item>
<el-form-item label="创建时间">
<el-date-picker
v-model="dateRange"
size="small"
style="width: 240px"
value-format="yyyy-MM-dd"
type="daterange"
range-separator="-"
start-placeholder="开始日期"
end-placeholder="结束日期"
></el-date-picker>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['system:role:add']"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['system:role:edit']"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['system:role:remove']"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['system:role:export']"
>导出</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="角色编号" prop="roleId" width="120" />
<el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
<el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150" />
<el-table-column label="显示顺序" prop="roleSort" width="100" />
<el-table-column label="状态" align="center" width="100">
<template slot-scope="scope">
<el-switch
v-model="scope.row.status"
active-value="0"
inactive-value="1"
@change="handleStatusChange(scope.row)"
></el-switch>
</template>
</el-table-column>
<el-table-column label="创建时间" align="center" prop="createTime" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.createTime) }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
v-hasPermi="['system:role:edit']"
>修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-circle-check"
@click="handleDataScope(scope.row)"
v-hasPermi="['system:role:edit']"
>数据权限</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
v-hasPermi="['system:role:remove']"
>删除</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<!-- 添加或修改角色配置对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item label="角色名称" prop="roleName">
<el-input v-model="form.roleName" placeholder="请输入角色名称" />
</el-form-item>
<el-form-item label="权限字符" prop="roleKey">
<el-input v-model="form.roleKey" placeholder="请输入权限字符" />
</el-form-item>
<el-form-item label="角色顺序" prop="roleSort">
<el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
</el-form-item>
<el-form-item label="状态">
<el-radio-group v-model="form.status">
<el-radio
v-for="dict in statusOptions"
:key="dict.dictValue"
:label="dict.dictValue"
>{{dict.dictLabel}}</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="菜单权限">
<el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
<el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
<el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
<el-tree
class="tree-border"
:data="menuOptions"
show-checkbox
ref="menu"
node-key="id"
:check-strictly="!form.menuCheckStrictly"
empty-text="加载中,请稍后"
:props="defaultProps"
></el-tree>
</el-form-item>
<el-form-item label="备注">
<el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
<!-- 分配角色数据权限对话框 -->
<el-dialog :title="title" :visible.sync="openDataScope" width="500px" append-to-body>
<el-form :model="form" label-width="80px">
<el-form-item label="角色名称">
<el-input v-model="form.roleName" :disabled="true" />
</el-form-item>
<el-form-item label="权限字符">
<el-input v-model="form.roleKey" :disabled="true" />
</el-form-item>
<el-form-item label="权限范围">
<el-select v-model="form.dataScope" @change="dataScopeSelectChange">
<el-option
v-for="item in dataScopeOptions"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</el-form-item>
<el-form-item label="数据权限" v-show="form.dataScope == 2">
<el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
<el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
<el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
<el-tree
class="tree-border"
:data="deptOptions"
show-checkbox
default-expand-all
ref="dept"
node-key="id"
:check-strictly="!form.deptCheckStrictly"
empty-text="加载中,请稍后"
:props="defaultProps"
></el-tree>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitDataScope">确 定</el-button>
<el-button @click="cancelDataScope">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { listRole, getRole, delRole, addRole, updateRole, exportRole, dataScope, changeRoleStatus } from "@/api/system/role";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import { treeselect as deptTreeselect, roleDeptTreeselect } from "@/api/system/dept";
export default {
name: "Role",
data() {
return {
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
// 角色表格数据
roleList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 是否显示弹出层(数据权限)
openDataScope: false,
menuExpand: false,
menuNodeAll: false,
deptExpand: true,
deptNodeAll: false,
// 日期范围
dateRange: [],
// 状态数据字典
statusOptions: [],
// 数据范围选项
dataScopeOptions: [
{
value: "1",
label: "全部数据权限"
},
{
value: "2",
label: "自定数据权限"
},
{
value: "3",
label: "本部门数据权限"
},
{
value: "4",
label: "本部门及以下数据权限"
},
{
value: "5",
label: "仅本人数据权限"
}
],
// 菜单列表
menuOptions: [],
// 部门列表
deptOptions: [],
// 查询参数
queryParams: {
pageNum: 1,
pageSize: 10,
roleName: undefined,
roleKey: undefined,
status: undefined
},
// 表单参数
form: {},
defaultProps: {
children: "children",
label: "label"
},
// 表单校验
rules: {
roleName: [
{ required: true, message: "角色名称不能为空", trigger: "blur" }
],
roleKey: [
{ required: true, message: "权限字符不能为空", trigger: "blur" }
],
roleSort: [
{ required: true, message: "角色顺序不能为空", trigger: "blur" }
]
}
};
},
created() {
this.getList();
this.getDicts("sys_normal_disable").then(response => {
this.statusOptions = response.data;
});
},
methods: {
/** 查询角色列表 */
getList() {
this.loading = true;
listRole(this.addDateRange(this.queryParams, this.dateRange)).then(
response => {
this.roleList = response.rows;
this.total = response.total;
this.loading = false;
}
);
},
/** 查询菜单树结构 */
getMenuTreeselect() {
menuTreeselect().then(response => {
this.menuOptions = response.data;
});
},
/** 查询部门树结构 */
getDeptTreeselect() {
deptTreeselect().then(response => {
this.deptOptions = response.data;
});
},
// 所有菜单节点数据
getMenuAllCheckedKeys() {
// 目前被选中的菜单节点
let checkedKeys = this.$refs.menu.getCheckedKeys();
// 半选中的菜单节点
let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
return checkedKeys;
},
// 所有部门节点数据
getDeptAllCheckedKeys() {
// 目前被选中的部门节点
let checkedKeys = this.$refs.dept.getCheckedKeys();
// 半选中的部门节点
let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
return checkedKeys;
},
/** 根据角色ID查询菜单树结构 */
getRoleMenuTreeselect(roleId) {
return roleMenuTreeselect(roleId).then(response => {
this.menuOptions = response.menus;
return response;
});
},
/** 根据角色ID查询部门树结构 */
getRoleDeptTreeselect(roleId) {
return roleDeptTreeselect(roleId).then(response => {
this.deptOptions = response.depts;
return response;
});
},
// 角色状态修改
handleStatusChange(row) {
let text = row.status === "0" ? "启用" : "停用";
this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return changeRoleStatus(row.roleId, row.status);
}).then(() => {
this.msgSuccess(text + "成功");
}).catch(function() {
row.status = row.status === "0" ? "1" : "0";
});
},
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
// 取消按钮(数据权限)
cancelDataScope() {
this.openDataScope = false;
this.reset();
},
// 表单重置
reset() {
if (this.$refs.menu != undefined) {
this.$refs.menu.setCheckedKeys([]);
}
this.menuExpand = false,
this.menuNodeAll = false,
this.deptExpand = true,
this.deptNodeAll = false,
this.form = {
roleId: undefined,
roleName: undefined,
roleKey: undefined,
roleSort: 0,
status: "0",
menuIds: [],
deptIds: [],
menuCheckStrictly: true,
deptCheckStrictly: true,
remark: undefined
};
this.resetForm("form");
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
/** 重置按钮操作 */
resetQuery() {
this.dateRange = [];
this.resetForm("queryForm");
this.handleQuery();
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.roleId)
this.single = selection.length!=1
this.multiple = !selection.length
},
// 树权限(展开/折叠)
handleCheckedTreeExpand(value, type) {
if (type == 'menu') {
let treeList = this.menuOptions;
for (let i = 0; i < treeList.length; i++) {
this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
}
} else if (type == 'dept') {
let treeList = this.deptOptions;
for (let i = 0; i < treeList.length; i++) {
this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
}
}
},
// 树权限(全选/全不选)
handleCheckedTreeNodeAll(value, type) {
if (type == 'menu') {
this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
} else if (type == 'dept') {
this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
}
},
// 树权限(父子联动)
handleCheckedTreeConnect(value, type) {
if (type == 'menu') {
this.form.menuCheckStrictly = value ? true: false;
} else if (type == 'dept') {
this.form.deptCheckStrictly = value ? true: false;
}
},
/** 新增按钮操作 */
handleAdd() {
this.reset();
this.getMenuTreeselect();
this.open = true;
this.title = "添加角色";
},
/** 修改按钮操作 */
handleUpdate(row) {
this.reset();
const roleId = row.roleId || this.ids
const roleMenu = this.getRoleMenuTreeselect(roleId);
getRole(roleId).then(response => {
this.form = response.data;
this.open = true;
this.$nextTick(() => {
roleMenu.then(res => {
let checkedKeys = res.checkedKeys
checkedKeys.forEach((v) => {
this.$nextTick(()=>{
this.$refs.menu.setChecked(v, true ,false);
})
})
});
});
this.title = "修改角色";
});
},
/** 选择角色权限范围触发 */
dataScopeSelectChange(value) {
if(value !== '2') {
this.$refs.dept.setCheckedKeys([]);
}
},
/** 分配数据权限操作 */
handleDataScope(row) {
this.reset();
const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId);
getRole(row.roleId).then(response => {
this.form = response.data;
this.openDataScope = true;
this.$nextTick(() => {
roleDeptTreeselect.then(res => {
this.$refs.dept.setCheckedKeys(res.checkedKeys);
});
});
this.title = "分配数据权限";
});
},
/** 提交按钮 */
submitForm: function() {
this.$refs["form"].validate(valid => {
if (valid) {
if (this.form.roleId != undefined) {
this.form.menuIds = this.getMenuAllCheckedKeys();
updateRole(this.form).then(response => {
this.msgSuccess("修改成功");
this.open = false;
this.getList();
});
} else {
this.form.menuIds = this.getMenuAllCheckedKeys();
addRole(this.form).then(response => {
this.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
}
});
},
/** 提交按钮(数据权限) */
submitDataScope: function() {
if (this.form.roleId != undefined) {
this.form.deptIds = this.getDeptAllCheckedKeys();
dataScope(this.form).then(response => {
this.msgSuccess("修改成功");
this.openDataScope = false;
this.getList();
});
}
},
/** 删除按钮操作 */
handleDelete(row) {
const roleIds = row.roleId || this.ids;
this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return delRole(roleIds);
}).then(() => {
this.getList();
this.msgSuccess("删除成功");
})
},
/** 导出按钮操作 */
handleExport() {
const queryParams = this.queryParams;
this.$confirm('是否确认导出所有角色数据项?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return exportRole(queryParams);
}).then(response => {
this.download(response.msg);
})
}
}
};
</script>
网友评论