JAVA项目实战-shrio框架使用(二)

本节介绍利用shiro框架完成用户模块,角色模块接口

1.数据库实体对象

package com.sf.detectcore.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

@TableName(value = "sys_menu")
public class SysMenu implements Serializable {

    @TableId(type = IdType.AUTO,value = "menu_id")
    private Long menuId;

    private String name;

    private String icon;

    private Long parentId;

    private Byte status;

    private String identity;

    private static final long serialVersionUID = 1L;

    public Long getMenuId() {
        return menuId;
    }

    public void setMenuId(Long menuId) {
        this.menuId = menuId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon == null ? null : icon.trim();
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public Byte getStatus() {
        return status;
    }

    public void setStatus(Byte status) {
        this.status = status;
    }


    @Override
    public String toString() {
        return "SysMenu{" +
                "menuId=" + menuId +
                ", name='" + name + '\'' +
                ", icon='" + icon + '\'' +
                ", parentId=" + parentId +
                ", status=" + status +
                ", identity='" + identity + '\'' +
                '}';
    }
}
package com.sf.detectcore.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.List;

@TableName(value = "sys_permission")
public class SysPermission implements Serializable {

    @TableId(type = IdType.AUTO,value = "permission_id")
    private Long permissionId;

    private String name;

    private String sn;

    private String resources;

    private Long parentId;

    private Long menuId;

    private Byte status;

    /**
     * 子权限
     */
    @TableField(exist = false)
    private List<SysPermission> children;

    private static final long serialVersionUID = 1L;

    public Long getPermissionId() {
        return permissionId;
    }

    public void setPermissionId(Long permissionId) {
        this.permissionId = permissionId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getSn() {
        return sn;
    }

    public void setSn(String sn) {
        this.sn = sn == null ? null : sn.trim();
    }

    public String getResources() {
        return resources;
    }

    public void setResources(String resources) {
        this.resources = resources == null ? null : resources.trim();
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public Long getMenuId() {
        return menuId;
    }

    public void setMenuId(Long menuId) {
        this.menuId = menuId;
    }

    public Byte getStatus() {
        return status;
    }

    public void setStatus(Byte status) {
        this.status = status;
    }

    public List<SysPermission> getChildren() { return children; }

    public void setChildren(List<SysPermission> children) { this.children = children; }
}
package com.sf.detectcore.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
@TableName(value = "sys_role")
public class SysRole implements Serializable {

    @TableId(type = IdType.AUTO,value = "role_id")
    private Long roleId;

    private String name;

    private String remarks;

    private Byte status;

    private Date createTime;

    private Long createId;

    private Date updateTime;

    private Long updateId;

    /**
     * 角色所拥有的权限id集合
     */
    @TableField(exist = false)
    private List<Long> permissionIds;

    /**
     * 角色所拥有的权限集合
     */
    @TableField(exist = false)
    private List<SysPermission> permissions;

    private static final long serialVersionUID = 1L;

    public Long getRoleId() {
        return roleId;
    }

    public void setRoleId(Long roleId) {
        this.roleId = roleId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks == null ? null : remarks.trim();
    }

    public Byte getStatus() {
        return status;
    }

    public void setStatus(Byte status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Long getCreateId() {
        return createId;
    }

    public void setCreateId(Long createId) {
        this.createId = createId;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Long getUpdateId() {
        return updateId;
    }

    public void setUpdateId(Long updateId) {
        this.updateId = updateId;
    }

    public List<Long> getPermissionIds() { return permissionIds; }

    public void setPermissionIds(List<Long> permissionIds) { this.permissionIds = permissionIds; }

    public List<SysPermission> getPermissions() { return permissions; }

    public void setPermissions(List<SysPermission> permissions) { this.permissions = permissions; }
}
package com.sf.detectcore.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

@TableName(value = "sys_role_permission")
public class SysRolePermission implements Serializable {

    @TableId(type = IdType.AUTO,value = "id")
    private Long id;

    private Long roleId;

    private Long permissionId;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getRoleId() {
        return roleId;
    }

    public void setRoleId(Long roleId) {
        this.roleId = roleId;
    }

    public Long getPermissionId() {
        return permissionId;
    }

    public void setPermissionId(Long permissionId) {
        this.permissionId = permissionId;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", roleId=").append(roleId);
        sb.append(", permissionId=").append(permissionId);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}
package com.sf.detectcore.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@TableName(value = "sys_user")
public class SysUser implements Serializable {

    @TableId(type = IdType.AUTO,value = "user_id")
    private Long userId;

    private String name;

    private String account;

    @JsonIgnore
    private String password;

    private Integer status;

    private Date createTime;

    private Long createId;

    private Date updateTime;

    private Long updateId;


    private Long labId;

    /**
     * 角色ID集合
     */
    @TableField(exist = false)
    private List<Long> roleIds;

    /**
     * 角色ID集合
     */
    @TableField(exist = false)
    private Long roleId;

    /**
     * 角色名字
     */
    @TableField(exist = false)
    private String roleName;


    /**
     * 实验室名字
     */
    @TableField(exist = false)
    private String labName;

    private static final long serialVersionUID = 1L;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account == null ? null : account.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Long getCreateId() {
        return createId;
    }

    public void setCreateId(Long createId) {
        this.createId = createId;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Long getUpdateId() {
        return updateId;
    }

    public void setUpdateId(Long updateId) {
        this.updateId = updateId;
    }

    public List<Long> getRoleIds() { return roleIds; }

    public void setRoleIds(List<Long> roleIds) { this.roleIds = roleIds; }


    public Long getLabId() {
        return labId;
    }

    public void setLabId(Long labId) {
        this.labId = labId;
    }

    public String getLabName() {
        return labName;
    }

    public void setLabName(String labName) {
        this.labName = labName;
    }

    public String getRoleName() {
        return roleName;
    }

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

    public Long getRoleId() {
        return roleId;
    }

    public void setRoleId(Long roleId) {
        this.roleId = roleId;
    }
}

2.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.sf.detectcore.mapper.SysMenuMapper" >
  <resultMap id="BaseResultMap" type="com.sf.detectcore.entity.SysMenu" >
    <id column="menu_id" property="menuId" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="icon" property="icon" jdbcType="VARCHAR" />
    <result column="parent_id" property="parentId" jdbcType="BIGINT" />
    <result column="status" property="status" jdbcType="TINYINT" />
    <result column="identity" property="identity" jdbcType="VARCHAR" />
  </resultMap>

  <!-- 插入一条数据 -->
  <insert id="insert" parameterType="com.sf.detectcore.entity.SysMenu" >
    <selectKey resultType="java.lang.Long" keyProperty="menuId" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into m_menu (`name`, icon, parent_id,
    `status`)
    values (#{name,jdbcType=VARCHAR}, #{icon,jdbcType=VARCHAR}, #{parentId,jdbcType=BIGINT},
    #{status,jdbcType=TINYINT})
  </insert>

  <resultMap type="com.sf.detectcore.entity.SysMenu" id="menuMap">
    <!-- 基本属性 -->
    <id property="menuId" column="menu_id" />
    <result property="name" column="name" />
    <result property="icon" column="icon" />
  </resultMap>

  <!-- 根据userId查询所有菜单 -->
  <select id="getMenusByUserId" resultType="com.sf.detectcore.controller.user.model.MenuResponse" parameterType="java.lang.Long">
    SELECT  m1.menu_id menuId, m1.name name, m1.icon icon,m1.parent_id parentId ,m1.identity
    FROM sys_menu m1
    JOIN sys_permission t1  ON m1.menu_id = t1.menu_id
    JOIN sys_role_permission t2 ON t1.permission_id = t2.permission_id
    JOIN  sys_role t3 ON t2.role_id = t3.role_id
    JOIN  sys_user_role t4 ON t3.role_id = t4.role_id
    JOIN  sys_user t5 ON t4.user_id = t5.user_id
    WHERE t5.user_id = #{userId} AND m1.`status` = 0
    ORDER BY m1.menu_id ASC
  </select>


  <!-- 根据parentId查询二级菜单 -->
  <select id="getByParentId" resultType="com.sf.detectcore.controller.user.model.MenuResponse" parameterType="java.lang.Long">
    select m.menu_id menuId, m.name name, m.icon icon,m.parent_id parentId ,m.identity identity FROM sys_menu m
    where m.parent_id = #{parentId}
  </select>


</mapper>
<?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.sf.detectcore.mapper.SysPermissionMapper" >
  <resultMap id="BaseResultMap" type="com.sf.detectcore.entity.SysPermission" >
    <id column="permission_id" property="permissionId" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sn" property="sn" jdbcType="VARCHAR" />
    <result column="resources" property="resources" jdbcType="VARCHAR" />
    <result column="parent_id" property="parentId" jdbcType="BIGINT" />
    <result column="menu_id" property="menuId" jdbcType="BIGINT" />
    <result column="status" property="status" jdbcType="TINYINT" />
  </resultMap>

  <!-- 根据用多个角色id查询拥有的权限-->
  <select id="getPermissionsByRoles" resultMap="BaseResultMap" parameterType="java.util.List" >
    SELECT DISTINCT * FROM(
    SELECT p.* FROM sys_permission p
    LEFT JOIN sys_role_permission rp ON p.permission_id = rp.permission_id
    WHERE rp.role_id in
    <foreach collection="roleIds" index="index" item="id" open="(" separator="," close=")">
      #{id}
    </foreach>
    AND p.`status` = 0 AND p.sn IS NOT NULL
    ORDER BY p.permission_id
    ) a
  </select>

  <!-- 查询系统所有有效权限-->
  <select id="getAllPermissions" resultMap="BaseResultMap" >
    select permission_id, `name`, sn, resources, parent_id, menu_id, `status` from sys_permission
    WHERE `status` = 0 AND sn IS NOT NULL AND resources IS NOT NULL
  </select>

  <!-- 根据主键Id查询权限 -->
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select permission_id, `name`, sn, resources, parent_id, menu_id, `status`
    from sys_permission
    where permission_id = #{permissionId,jdbcType=BIGINT}
  </select>


  <!-- 查询用户的角色id-->
  <select id="getUserRoleId" resultType="java.lang.Long" parameterType="java.lang.Long">
    select role_id from sys_user_role WHERE user_id = #{userId}
  </select>


  <!-- 查询用户对应角色拥有的权限id-->
  <select id="getUserPermIds" resultType="java.lang.Long" parameterType="java.lang.Long">
    select permission_id from sys_role_permission WHERE role_id = #{roleId}
  </select>


  <!-- 根据权限id查询一条权限数据(二级菜单权限)-->
  <select id="getTwoMenuPermById" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select permission_id, `name`, sn, resources, parent_id, menu_id, `status` from sys_permission
    where permission_id = #{permId}
          and parent_id is not null
          and menu_id is not null
  </select>


  <!-- 查询一条权限的所有子权限数据-->
  <select id="getChildrenPermission" resultMap="BaseResultMap" parameterType="com.sf.detectcore.controller.role.model.RolePermissionParam" >
    select permission_id, `name`, sn, resources, parent_id, menu_id, `status` from sys_permission
    where parent_id = #{parentPermId}
    and permission_id in
    <foreach collection="permIds" index="index" item="id" open="(" separator="," close=")">
      #{id}
    </foreach>
  </select>

</mapper>
<?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.sf.detectcore.mapper.SysRoleMapper" >
  <resultMap id="BaseResultMap" type="com.sf.detectcore.entity.SysRole" >
    <id column="role_id" property="roleId" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="remarks" property="remarks" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="TINYINT" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="create_id" property="createId" jdbcType="BIGINT" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
    <result column="update_id" property="updateId" jdbcType="BIGINT" />
  </resultMap>


  <!-- 插入一条数据 -->
  <insert id="insert" parameterType="com.sf.detectcore.entity.SysRole" >
    <selectKey resultType="java.lang.Long" keyProperty="roleId" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into sys_role (`name`, remarks, `status`,
    create_time, create_id, update_time,
    update_id)
    values (#{name,jdbcType=VARCHAR}, #{remarks,jdbcType=VARCHAR}, #{status,jdbcType=TINYINT},
    #{createTime,jdbcType=TIMESTAMP}, #{createId,jdbcType=BIGINT}, #{updateTime,jdbcType=TIMESTAMP},
    #{updateId,jdbcType=BIGINT})
  </insert>

  <!-- 根据用户自增id查询他拥有的角色-->
  <select id="getRolesByUserId" resultMap="BaseResultMap" parameterType="java.lang.Long">
    SELECT r.* FROM sys_role r
    LEFT JOIN sys_user_role ur ON r.role_id = ur.role_id
    WHERE ur.user_id = #{id} AND r.`status` = 0
  </select>

  <!--  根据主键修改角色信息 -->
  <update id="updateByPrimaryKey" parameterType="com.sf.detectcore.entity.SysRole" >
    update sys_role
    set `name` = #{name,jdbcType=VARCHAR},
      remarks = #{remarks,jdbcType=VARCHAR},
      `status` = #{status,jdbcType=TINYINT},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      create_id = #{createId,jdbcType=BIGINT},
      update_time = #{updateTime,jdbcType=TIMESTAMP},
      update_id = #{updateId,jdbcType=BIGINT}
    where role_id = #{roleId,jdbcType=BIGINT}
  </update>

  <!-- 根据主键Id查询角色信息 -->
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select role_id, `name`, remarks, `status`, create_time, create_id, update_time, update_id
    from sys_role
    where role_id = #{roleId,jdbcType=BIGINT}
  </select>

  <!-- 根据主键删除角色 -->
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from sys_role
    where role_id = #{roleId,jdbcType=BIGINT}
  </delete>

  <!-- 获取所有系统角色-->
  <select id="getAllSystemRole" resultMap="BaseResultMap">
    select role_id, `name`, remarks, `status`, create_time, create_id, update_time, update_id
    from sys_role where role_id > 1
  </select>
</mapper>
<?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.sf.detectcore.mapper.SysRolePermissionMapper" >
  <resultMap id="BaseResultMap" type="com.sf.detectcore.entity.SysRolePermission" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="role_id" property="roleId" jdbcType="BIGINT" />
    <result column="permission_id" property="permissionId" jdbcType="BIGINT" />
  </resultMap>


  <!-- 根据主键Id查询角色权限关系 -->
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select id, role_id, permission_id
    from sys_role_permission
    where id = #{id,jdbcType=BIGINT}
  </select>

</mapper>
<?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.sf.detectcore.mapper.SysUserMapper" >
  <resultMap id="BaseResultMap" type="com.sf.detectcore.entity.SysUser" >
    <id column="user_id" property="userId" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="account" property="account" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="TINYINT" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="create_id" property="createId" jdbcType="BIGINT" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
    <result column="update_id" property="updateId" jdbcType="BIGINT" />
    <result column="lab_id" property="labId" jdbcType="BIGINT" />
  </resultMap>

  <select id="selectAll" resultMap="BaseResultMap" >
    select user_id, `name`, account, `password`,  `status`,
    create_time, create_id, update_time, update_id
    from sys_user
  </select>

  <!-- 根据账号查询用户-->
  <select id="getUserByAccount" resultMap="BaseResultMap" parameterType="java.lang.String">
    select user_id, `name`, account, `password`, `status`, create_time, create_id,
    update_time, update_id,lab_id
    from sys_user where binary account = #{account}
  </select>

  <!-- 根据主键修改用户信息 -->
  <update id="updateByPrimaryKey" parameterType="com.sf.detectcore.entity.SysUser" >
    update sys_user
    set `name` = #{name,jdbcType=VARCHAR},
      account = #{account,jdbcType=VARCHAR},
      `password` = #{password,jdbcType=VARCHAR},
      `status` = #{status,jdbcType=TINYINT},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      create_id = #{createId,jdbcType=BIGINT},
      update_time = #{updateTime,jdbcType=TIMESTAMP},
      update_id = #{updateId,jdbcType=BIGINT},
      lab_id = #{labId,jdbcType=BIGINT}
    where user_id = #{userId,jdbcType=BIGINT}
  </update>

  <!-- 根据主键删除用户 -->
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from sys_user
    where user_id = #{userId,jdbcType=BIGINT}
  </delete>

  <!-- 根据主键查询用户信息 -->
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select user_id, `name`, account, `password`, `status`, create_time, create_id,
    update_time, update_id
    from sys_user
    where user_id = #{userId,jdbcType=BIGINT}
  </select>

  <!-- 查询指定用户的角色id-->
  <select id="getRoleId" resultType="java.lang.Long" parameterType="java.lang.Long">
    SELECT role_id FROM sys_user_role WHERE user_id = #{userId}
  </select>

  <!-- 获取当前用户在指定页面的权限-->
  <select id="findUserPagePermission" resultType="java.lang.String" parameterType="java.util.Map">
    SELECT p.resources from sys_permission p
    LEFT JOIN sys_role_permission rp on p.permission_id = rp.permission_id
    WHERE rp.role_id = #{roleId} AND p.parent_id = #{menuId} AND p.resources IS NOT NULL
  </select>
</mapper>
<?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.sf.detectcore.mapper.SysUserRoleMapper" >
  <resultMap id="BaseResultMap" type="com.sf.detectcore.entity.SysUserRole" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="user_id" property="userId" jdbcType="BIGINT" />
    <result column="role_id" property="roleId" jdbcType="BIGINT" />
  </resultMap>

</mapper>

3.mapper层

package com.sf.detectcore.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sf.detectcore.controller.user.model.MenuResponse;
import com.sf.detectcore.entity.SysMenu;
import java.util.List;

/**
 * @ClassName SysMenuMapper
 * @Description SysMenuMapper
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysMenuMapper extends BaseMapper<SysMenu> {

    /**
     * 插入一条数据
     * @param record
     * @return
     */
    @Override
    int insert(SysMenu record);


    /**
     * 根据用户id查询他拥有所有菜单
     * @param userId
     * @return List
     */
    List<MenuResponse> getMenusByUserId(Long userId);


    /**
     * 根据父Id(parentId) 查询二级菜单
     * @param parentId
     * @return
     */
    List<MenuResponse> getByParentId(Long parentId);

}
package com.sf.detectcore.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sf.detectcore.controller.query.SysPermissionQuery;
import com.sf.detectcore.controller.role.model.RolePermissionParam;
import com.sf.detectcore.entity.SysPermission;
import org.apache.ibatis.annotations.Param;

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

/**
 * @ClassName SysPermissionMapper
 * @Description SysPermissionMapper
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysPermissionMapper extends BaseMapper<SysPermission> {

    /**
     * 根据用多个角色id查询拥有的权限
     * @param roleIds
     * @return List
     */
    List<SysPermission> getPermissionsByRoles(@Param("roleIds")List<Long> roleIds);

    /**
     * 查询系统所有有效权限
     * @return List
     */
    List<SysPermission> getAllPermissions();


    /**
     * 根据主键Id查询权限
     * @param permissionId
     * @return
     */
    SysPermission selectByPrimaryKey(Long permissionId);

    /**
     * 查询用户的角色id
     * @param userId
     * @return Long
     */
    Long getUserRoleId(Long userId);

    /**
     * 查询用户对应角色拥有的权限id
     * @param roleId
     * @return List
     */
    List<Long> getUserPermIds(Long roleId);

    /**
     * 根据权限id查询一条权限数据(二级菜单权限)
     * @param permId
     * @return SysPermission
     */
    SysPermission getTwoMenuPermById(Long permId);

    /**
     * 查询一条权限的所有子权限数据
     * @param param
     * @return List
     */
    List<SysPermission> getChildrenPermission(RolePermissionParam param);

}
package com.sf.detectcore.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sf.detectcore.entity.SysRole;
import java.util.List;

/**
 * @ClassName SysRoleMapper
 * @Description SysRoleMapper
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysRoleMapper extends BaseMapper<SysRole> {

    /**
     * 插入一条数据
     * @param record
     * @return
     */
    @Override
    int insert(SysRole record);

    /**
     * 根据用户自增id查询他拥有的角色
     * @param id
     * @return List
     */
    List<SysRole> getRolesByUserId(Long id);

    /**
     * 根据主键修改角色信息
     * @param record
     * @return
     */
    int updateByPrimaryKey(SysRole record);

    /**
     * 根据主键Id查询角色信息
     * @param roleId
     * @return
     */
    SysRole selectByPrimaryKey(Long roleId);

    /**
     * 根据主键删除角色
     * @param roleId
     * @return
     */
    int deleteByPrimaryKey(Long roleId);


    /**
     * 获取所有系统角色
     * @return ResultData
     */
    List<SysRole> getAllSystemRole();
}
package com.sf.detectcore.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sf.detectcore.entity.SysRolePermission;
import java.util.List;

/**
 * @ClassName SysRolePermissionMapper
 * @Description SysRolePermissionMapper
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysRolePermissionMapper extends BaseMapper<SysRolePermission> {

    /**
     * 根据主键Id查询角色权限关系
     * @param id
     * @return
     */
    SysRolePermission selectByPrimaryKey(Long id);




}
package com.sf.detectcore.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sf.detectcore.entity.SysUser;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysUserMapper
 * @Description UserMapper
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysUserMapper extends BaseMapper<SysUser> {

    List<SysUser> selectAll();

    /**
     * 根据账号查询用户
     * @param account
     * @return User
     */
    SysUser getUserByAccount(String account);

    /**
     * 根据主键修改用户信息
     * @param record
     * @return
     */
    int updateByPrimaryKey(SysUser record);

    /**
     * 根据主键删除用户
     * @param userId
     * @return
     */
    int deleteByPrimaryKey(Long userId);

    /**
     * 根据主键查询用户信息
     * @param userId
     * @return
     */
    SysUser selectByPrimaryKey(Long userId);

    /**
     * 查询指定用户的角色id
     * @param userId
     * @return Long
     */
    Long getRoleId(Long userId);

    /**
     * 获取当前用户在指定页面的权限
     * @param map
     * @return List
     */
    List<String> findUserPagePermission(Map<String,Object> map);


}
package com.sf.detectcore.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sf.detectcore.entity.SysUserRole;
import java.util.List;

/**
 * @ClassName SysUserRoleMapper
 * @Description SysUserRoleMapper
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {


}

4.service层

 

package com.sf.detectcore.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.detectcore.controller.user.model.MenuResponse;
import com.sf.detectcore.entity.SysMenu;

import java.util.List;

/**
 * @ClassName SysMenuService
 * @Description 菜单相关服务
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysMenuService extends IService<SysMenu> {

    /**
     * 根据用户id查询他拥有的菜单
     * @param userId
     * @returist
     */
    List<MenuResponse> findUserMenus(Long userId);
}

 

package com.sf.detectcore.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.detectcore.entity.SysPermission;
import com.sf.detectcore.entity.SysRole;

import java.util.List;

/**
 * @ClassName SysPermissionService
 * @Description 权限相关服务
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysPermissionService extends IService<SysPermission> {

    /**
     * 根据用户的多个角色查询拥有的权限
     * @param roles
     * @return
     */
    List<SysPermission> findPermissionsByRoles(List<SysRole> roles);

    /**
     * 查询系统所有有效权限
     * @return List
     */
    List<SysPermission> loadAllPermissions();


}
package com.sf.detectcore.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.detectcore.entity.SysRolePermission;

/**
 * @ClassName SysRolePermissionService
 * @Description SysRolePermissionService
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysRolePermissionService extends IService<SysRolePermission> {
}
package com.sf.detectcore.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.detectcore.controller.query.RoleQuery;
import com.sf.detectcore.entity.SysRole;
import com.sf.detectcore.entity.SysUser;
import com.sf.detectcore.util.R;

import java.util.List;

/**
 * @ClassName SysRoleService
 * @Description 角色相关服务
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysRoleService extends IService<SysRole> {


    /**
     * 根据roleId查询角色
     * @param roleId
     * @return
     */
    SysRole getByRoleId(Long roleId);

    /**
     * 添加系统角色数据
     * @param sysRole
     * @return R
     */
    R addRole(SysRole sysRole);


    /**
     * 编辑系统角色数据
     * @param sysRole
     * @return R
     */
    R editRole(SysRole sysRole);

    /**
     * 查询一个角色的详情
     * @param id
     * @return R
     */
    R getRoleById(Long id);


    /**
     * 删除角色
     * @param ids
     * @return R
     */
    R deleteRole(String ids);


    /**
     * 查询角色列表数据
     * @param roleQuery
     * @param user
     * @return R
     */
    R getRolePagingData(RoleQuery roleQuery , SysUser user);


    /**
     * 查询系统所有权限
     * @return R
     */
    R getSystemPermission();


    /**
     * 获取所有系统角色,添加用户时使用,排除超级管理员
     * @param user
     * @return R
     */
    R getSystemRole(SysUser user);

}
package com.sf.detectcore.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.detectcore.entity.SysUserRole;

/**
 * @ClassName SysUserRoleService
 * @Description SysUserRoleService
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysUserRoleService extends IService<SysUserRole> {
}
package com.sf.detectcore.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.sf.detectcore.controller.query.UserQuery;
import com.sf.detectcore.entity.SysRole;
import com.sf.detectcore.entity.SysUser;
import com.sf.detectcore.util.R;

import java.util.List;

/**
 * @ClassName SysUserService
 * @Description 管理员相关服务
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public interface SysUserService extends IService<SysUser> {


    /**
     * 根据账号查询用户
     * @param account
     * @return SysUser
     */
    SysUser findUserByAccount(String account);

    /**
     * 根据用户自增id查询他拥有的角色
     * @param
     * @return List
     */
    List<SysRole> findRolesByUserId(Long id);


    /**
     * 新增系统用户
     * @param user
     */
    void addUser(SysUser user);

    /**
     * 编辑系统用户
     * @param user
     */
    void editUser(SysUser user);


    /**
     * 删除系统用户
     * @param userIds
     */
    void deleteUser(String userIds);


    /**
     * 查询系统用户数据
     * @param userQuery
     * @param user
     * @return R
     */
    R getUserPagingData(UserQuery userQuery , SysUser user);


    /**
     * 查询系统用户数据
     * @param id
     * @return R
     */
    R getUserById(Long id);

    /**
     * 获取当前用户在指定页面的权限
     * @param userId
     * @param menuId
     * @return R
     */
    R findUserPagePermission(Long userId, Long menuId);


    /**
     * 通过实验室Id查询用户信息
     * @param id
     * @return
     */
    List<SysUser> listQueryByLabId(Long id);


}

5.serviceImpl

package com.sf.detectcore.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.detectcore.controller.user.model.MenuResponse;
import com.sf.detectcore.entity.SysMenu;
import com.sf.detectcore.mapper.SysMenuMapper;
import com.sf.detectcore.service.SysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

   private final Logger logger = LoggerFactory.getLogger(SysMenuServiceImpl.class);

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<MenuResponse> findUserMenus(Long userId) {
        List<MenuResponse> list  = new ArrayList<>();
        //所有菜单
        List<MenuResponse> sysMenus = sysMenuMapper.getMenusByUserId(userId);
        if(sysMenus != null && sysMenus.size() != 0) {
            for(MenuResponse menuResponse: sysMenus) {
                List<MenuResponse> list1  = new ArrayList<>();
                if (Objects.equals(0L,menuResponse.getParentId())){
                    list.add(menuResponse);
                    //添加二级菜单
                    for (MenuResponse menuResponse1: sysMenus){
                        if (Objects.equals(menuResponse.getMenuId(),menuResponse1.getParentId())){
                            list1.add(menuResponse1);
                        }
                    }
                    menuResponse.setChildren(list1);
                }
            }
        }
        return list;
    }
}
package com.sf.detectcore.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.detectcore.entity.SysPermission;
import com.sf.detectcore.entity.SysRole;
import com.sf.detectcore.mapper.SysPermissionMapper;
import com.sf.detectcore.service.SysPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper,SysPermission> implements SysPermissionService {

    private final Logger logger = LoggerFactory.getLogger(SysPermissionServiceImpl.class);

    @Autowired
    SysPermissionMapper sysPermissionMapper;

    @Override
    public List<SysPermission> findPermissionsByRoles(List<SysRole> roles) {
        List<Long> roleIds = new ArrayList<>();
        for (SysRole role : roles) {
            if(role != null){
                roleIds.add(role.getRoleId());
            }
        }
        if(roleIds.size() <= 0){
            return null;
        }
        try{
            return sysPermissionMapper.getPermissionsByRoles(roleIds);
        }catch (Exception e){
            logger.error("根据用户角色查询拥有权限时异常:{}" , e);
            return null;
        }
    }

    @Override
    public List<SysPermission> loadAllPermissions() {
        return sysPermissionMapper.getAllPermissions();
    }



}
package com.sf.detectcore.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.detectcore.entity.SysRolePermission;
import com.sf.detectcore.mapper.SysRolePermissionMapper;
import com.sf.detectcore.service.SysRolePermissionService;
import org.springframework.stereotype.Service;

@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper,SysRolePermission> implements SysRolePermissionService {
}
package com.sf.detectcore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.detectcore.config.constant.SystemConstants;
import com.sf.detectcore.controller.query.RoleQuery;
import com.sf.detectcore.controller.role.model.RolePermissionParam;
import com.sf.detectcore.entity.*;
import com.sf.detectcore.mapper.SysPermissionMapper;
import com.sf.detectcore.mapper.SysRoleMapper;
import com.sf.detectcore.mapper.SysRolePermissionMapper;
import com.sf.detectcore.mapper.SysUserRoleMapper;
import com.sf.detectcore.service.SysRoleService;
import com.sf.detectcore.util.R;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    private final Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public SysRole getByRoleId(Long roleId) {
        return sysRoleMapper.selectByPrimaryKey(roleId);
    }

    @Transactional(propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
    @Override
    public R addRole(SysRole sysRole) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("name" , sysRole.getName());
        SysRole existRole = sysRoleMapper.selectOne(wrapper);
        if(existRole != null){
            return new R(SystemConstants.PARAM_INCORRECT_CODE , Boolean.FALSE,"当前角色名称已经存在,添加失败!");
        }
        // 1添加基本信息
        sysRoleMapper.insert(sysRole);
        return R.ok();
    }

    @Transactional(propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
    @Override
    public R editRole(SysRole sysRole) {
        // 1修改角色基本信息
        sysRoleMapper.updateByPrimaryKey(sysRole);
        if (Objects.nonNull(sysRole.getPermissionIds())){
            // 2修改角色权限关系数据 删除角色之前的权限数据
            QueryWrapper<SysRolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id" ,sysRole.getRoleId());
            sysRolePermissionMapper.delete(wrapper);
            List<Long> permissionIds = sysRole.getPermissionIds();
            for (Long id : permissionIds) {
                SysRolePermission relation = new SysRolePermission();
                relation.setRoleId(sysRole.getRoleId());
                relation.setPermissionId(id);
                sysRolePermissionMapper.insert(relation);
            }
        }
        return R.ok();
    }

    @Override
    public R getRoleById(Long id) {
        SysRole role = sysRoleMapper.selectByPrimaryKey(id);

        QueryWrapper<SysRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id" , id);
        List<SysRolePermission> relations = sysRolePermissionMapper.selectList(wrapper);
        logger.info("relations:{}",relations);
        List<Long> result = new ArrayList<>();
        int i=0;
        for (SysRolePermission relation : relations) {
            Long permissionId = relation.getPermissionId();
            SysPermission permission = sysPermissionMapper.selectByPrimaryKey(permissionId);
            if(!StringUtils.isEmpty(permission.getResources())){
                result.add(relation.getPermissionId());
            }
        }
        role.setPermissionIds(result);
        return R.ok(result);
    }

    @Override
    public R deleteRole(String ids) {
        try{
            QueryWrapper<SysUserRole> urWrapper = new QueryWrapper<>();
            urWrapper.in("role_id" , ids.split(","));
            List<SysUserRole> relations = sysUserRoleMapper.selectList(urWrapper);
            if(relations != null && relations.size() >= 1){
                return R.error(SystemConstants.PARAM_INCORRECT_CODE,"所选角色有系统用户使用,不能删除!");
            }
            for (String id : ids.split(",")) {
                //删除角色-权限数据
                QueryWrapper<SysRolePermission> wrapper = new QueryWrapper<>();
                wrapper.eq("role_id",Long.valueOf(id));
                sysRolePermissionMapper.delete(wrapper);
                // 删除基本数据
                sysRoleMapper.deleteByPrimaryKey(Long.valueOf(id));
            }
            return R.ok();
        }catch (Exception e){
            log.error("删除角色异常,异常信息:{}" , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE,"失败");
        }
    }

    @Override
    public R getRolePagingData(RoleQuery roleQuery, SysUser user) {
        try{
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            if(roleQuery.getName() != null && !roleQuery.getName().isEmpty()){
                wrapper.like("name" , roleQuery.getName());
            }
            //角色列表,不展示超级管理员,数据库表统一配置为自增id为1
            wrapper.notIn("role_id",1);
            IPage<SysRole> pageData = sysRoleMapper.selectPage(new Page<>(roleQuery.getPageNum(), roleQuery.getPageSize()), wrapper);
            return R.ok(pageData);
        }catch (Exception e){
            log.error("查询角色列表数据异常,异常信息:{}" , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "查询失败");
        }
    }

    @Override
    public R getSystemPermission() {
        List<SysPermission> permission = new ArrayList<>();
        try{
            //查询出所有父权限Id
            QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id",0);
            List<SysPermission> sysPermissions1 = sysPermissionMapper.selectList(queryWrapper);
            permission.addAll(sysPermissions1);
            for (SysPermission sysPermission1:sysPermissions1){
                QueryWrapper<SysPermission> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("parent_id",sysPermission1.getPermissionId());
                List<SysPermission> sysPermissions2 = sysPermissionMapper.selectList(queryWrapper1);
                sysPermission1.setChildren(sysPermissions2);
                for (SysPermission sysPermission2:sysPermissions2){
                    QueryWrapper<SysPermission> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("parent_id",sysPermission2.getPermissionId());
                    List<SysPermission> sysPermissions3 = sysPermissionMapper.selectList(queryWrapper2);
                    sysPermission2.setChildren(sysPermissions3);
                }
            }

            return R.ok(permission);

        }catch (Exception e){
            log.error("getSystemPermission查询系统权限异常,异常信息:{}" , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "查询失败");
        }
    }

    @Override
    public R getSystemRole(SysUser user) {
        List<SysRole> systemRole;
//        if(user.getStationId() != null){
//            Long userId = user.getUserId();
//            systemRole = sysRoleMapper.getSystemRole(userId);
//        }else{
            systemRole = sysRoleMapper.getAllSystemRole();
//        }
        return R.ok(systemRole);
    }
}
package com.sf.detectcore.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.detectcore.entity.SysUserRole;
import com.sf.detectcore.mapper.SysUserRoleMapper;
import com.sf.detectcore.service.SysUserRoleService;
import org.springframework.stereotype.Service;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
}
package com.sf.detectcore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.detectcore.config.constant.SystemConstants;
import com.sf.detectcore.controller.query.UserQuery;
import com.sf.detectcore.entity.Lab;
import com.sf.detectcore.entity.SysRole;
import com.sf.detectcore.entity.SysUser;
import com.sf.detectcore.entity.SysUserRole;
import com.sf.detectcore.mapper.LabMapper;
import com.sf.detectcore.mapper.SysRoleMapper;
import com.sf.detectcore.mapper.SysUserMapper;
import com.sf.detectcore.mapper.SysUserRoleMapper;
import com.sf.detectcore.service.SysUserService;
import com.sf.detectcore.util.R;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private LabMapper labMapper;


    @Override
    public SysUser findUserByAccount(String account){
        return sysUserMapper.getUserByAccount(account);
    }

    @Override
    public List<SysRole> findRolesByUserId(Long id) {
        return sysRoleMapper.getRolesByUserId(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void addUser(SysUser user) {
        // 1添加用户信息
        sysUserMapper.insert(user);

        // 2添加用户角色信息
        List<Long> roleIds = user.getRoleIds();
        for (Long roleId : roleIds) {
            SysUserRole relation = new SysUserRole();
            relation.setUserId(user.getUserId());
            relation.setRoleId(roleId);
            sysUserRoleMapper.insert(relation);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void editUser(SysUser user) {
        // 1编辑用户基本信息
        sysUserMapper.updateByPrimaryKey(user);

        // 2编辑用户角色信息(先删除以往的角色,再添加角色)
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" , user.getUserId());
        sysUserRoleMapper.delete(wrapper);
        List<Long> roleIds = user.getRoleIds();
        for (Long roleId : roleIds) {
            SysUserRole relation = new SysUserRole();
            relation.setUserId(user.getUserId());
            relation.setRoleId(roleId);
            sysUserRoleMapper.insert(relation);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void deleteUser(String userIds) {
        for (String userId : userIds.split(",")) {
            // 1删除用户基本信息
            sysUserMapper.deleteByPrimaryKey(Long.valueOf(userId));
            // 2删除用户角色信息
            QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id" , userId);
            sysUserRoleMapper.delete(wrapper);
        }
    }

    @Override
    public R getUserPagingData(UserQuery userQuery, SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if(userQuery.getName() != null && !userQuery.getName().isEmpty()){
            wrapper.like("name" , userQuery.getName());
        }
        if(userQuery.getAccount() != null && !userQuery.getAccount().isEmpty()){
            wrapper.eq("account" , userQuery.getAccount());
        }
        //用户列表,不展示超级管理员,数据库表统一配置为自增id为1
        wrapper.notIn("user_id",1);
        IPage<SysUser> pageData = sysUserMapper.selectPage(new Page<>(userQuery.getPageNum(), userQuery.getPageSize()), wrapper);
        List<SysUser> users = pageData.getRecords();
        for (SysUser userd : users) {
            if(userd.getLabId() != null){
                Lab lab = labMapper.selectById(userd.getLabId());
                userd.setLabName(lab.getName());
            }
            //默认一个 用户仅存在一个角色
            List<SysRole> rolesByUserId = sysRoleMapper.getRolesByUserId(userd.getUserId());
            userd.setRoleId(rolesByUserId.get(0).getRoleId());
            userd.setRoleName(rolesByUserId.get(0).getName());
        }
        return R.ok(pageData);
    }

    @Override
    public R getUserById(Long id) {
        // 基本信息
        SysUser user = sysUserMapper.selectByPrimaryKey(id);
        // 角色自增ID
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" , id);
        List<SysUserRole> relationList = sysUserRoleMapper.selectList(wrapper);
        List<Long> roleIds = new ArrayList<>();
        for (SysUserRole relation : relationList) {
            if(relation != null){
                roleIds.add(relation.getRoleId());
            }
        }
        user.setRoleIds(roleIds);
        user.setRoleId(roleIds.get(0));
        return R.ok(user);
    }

//    @Override
//    public List<SysUser> getUsersByStationId(Long stationId) {
//        QueryWrapper<Station> wrapper = new QueryWrapper<>();
//        if(user.getStationId() != null && user.getStationId() > 0){
//            wrapper.eq("station_id" , user.getStationId());
//        }
//        wrapper.eq("s_df" , 0);
//        return stationMapper.selectList(wrapper);
//    }

    @Override
    public R findUserPagePermission(Long userId, Long menuId) {
        try {
            Long roleId = sysUserMapper.getRoleId(userId);
            Map<String, Object> map = new HashMap<>();
            map.put("roleId" , roleId);
            map.put("menuId" , menuId);
            List<String> datas = sysUserMapper.findUserPagePermission(map);
            return R.ok(datas);
        }catch (Exception e){
            log.error("findUserPagePermission查询用户拥有的权限异常:{}" , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "查询失败");
        }
    }

    @Override
    public List<SysUser> listQueryByLabId(Long id) {
        QueryWrapper<SysUser> q1 = new QueryWrapper<>();
        q1.eq("lab_id",id);
        return sysUserMapper.selectList(q1);
    }
}

6.登录控制器

 

package com.sf.detectcore.controller.login;

import com.alibaba.fastjson.JSON;
import com.sf.detectcore.config.constant.Constant;
import com.sf.detectcore.config.constant.SystemConstants;
import com.sf.detectcore.controller.login.model.LoginModel;
import com.sf.detectcore.entity.SysRole;
import com.sf.detectcore.entity.SysUser;
import com.sf.detectcore.service.SysUserService;
import com.sf.detectcore.util.R;
import com.sf.detectcore.util.VerifyCodeUtil;
import com.sf.detectcore.util.redis.RedisUtil;
import com.sf.detectcore.util.rsa.RSAUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description 登录相关接口
 * @Author huyong
 * @Date 2019/10/14 14:52
 * @Version 1.0
 */
@Api(value="LoginController", description = "登录相关接口")
@RestController
@RequestMapping(value="login")
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    /** 登录有效时间 */
    @Value("${shiro.timeout}")
    private int timeOut;

    /** RSA私钥 */
    @Value("${RSA.privateKey}")
    private String privateKey;

    /** RSA公钥 */
    @Value("${RSA.publicKey}")
    private String publicKey;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    StringRedisTemplate redis;

    @Autowired
    RedisUtil redisUtil;

    @ApiOperation(value = "用户登录", notes = "用户登录" , httpMethod = "POST")
    @PostMapping(value = "login")
    @ResponseBody
    public R login(@Valid @RequestBody LoginModel loginModel, HttpServletRequest request){
        String sessionVerifyCode = (String)request.getSession().getAttribute(SystemConstants.VERIFYCODE);
        System.out.println(sessionVerifyCode+": "+loginModel.getVerifyCode());
        if(sessionVerifyCode == null || !sessionVerifyCode.equals(loginModel.getVerifyCode())){
            return new R(SystemConstants.PARAM_INCORRECT_CODE,false , "验证码错误或已过期,请刷新页面重试");
        }
        request.getSession().removeAttribute(SystemConstants.VERIFYCODE);

        SysUser user = sysUserService.findUserByAccount(loginModel.getAccount());
        if(user == null){
            return new R(SystemConstants.PARAM_INCORRECT_CODE,false , "系统无此用户!");
        }
        String userPwd = getRsaDecryStr(user.getPassword());
        String loginPwd = getRsaDecryStr(loginModel.getPassword());
        if(!userPwd.equals(loginPwd)){
            return new R(SystemConstants.AUTH_FAIL_CODE,false  , "密码错误!");
        }

        List<SysRole> roles = sysUserService.findRolesByUserId(user.getUserId());
        if (Objects.equals(Constant.INT_1,user.getStatus())){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE,"账号不可用,请联系管理员");
        }
        try{
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            Session oldSession = subject.getSession();
            // 重置session
            final LinkedHashMap<Object, Object> attributes = new LinkedHashMap<>();
            Collection<Object> keys = oldSession.getAttributeKeys();
            for (Object key : keys) {
                final Object value = oldSession.getAttribute(key);
                if(value != null){
                    attributes.put(key , value);
                }
            }
            oldSession.stop();
            Session session = subject.getSession();
            for (final Object key : attributes.keySet()) {
                session.setAttribute(key , attributes.get(key));
            }
            if(!subject.isAuthenticated()){
                UsernamePasswordToken token = new UsernamePasswordToken(loginModel.getAccount(), userPwd);
                subject.login(token);
                // shiro设置一次登录session的有效时间
                session.setTimeout(timeOut);
                session.setAttribute(SystemConstants.SESSION_USER , user);
                session.setAttribute(SystemConstants.SESSION_USER_ROLES , roles);
                session.setAttribute(SystemConstants.SESSION_ID, session.getId());
                //设置Key过期时间,将用户信息Json字符串存redis
                user.setRoleName(roles.get(0).getName());
                redis.opsForValue().set(SystemConstants.REDIS_KEY_PREFIX+session.getId() ,JSON.toJSONString(user),timeOut, TimeUnit.MILLISECONDS);
                // 必要值返回给前端
                Map<String, Object> map = new HashMap<>();
                map.put(SystemConstants.SESSION_USER, user);
                map.put(SystemConstants.SESSION_USER_ROLES , roles);
                map.put(SystemConstants.SESSION_ID , session.getId());
                logger.info("登录成功:{}",user);
                return R.ok(map);
            }
        }catch (AuthenticationException e){
            logger.error("用户_{}登录shiro认证异常,异常信息:{}" , loginModel.getAccount() , e);
            return new R(SystemConstants.AUTH_FAIL_CODE,false , null);
        }catch (Exception e){
            logger.error("用户_{}登录异常,异常信息:{}" , loginModel.getAccount() , e);
            return new R(SystemConstants.SERVER_ERROR_CODE,false , "登录异常");
        }
        return new R(SystemConstants.SERVER_ERROR_CODE,false , "登录失败");
    }

    @GetMapping(value = "/getVerifyCodeImage")
    @ResponseBody
    public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_LOWER, 4, null);
        session.removeAttribute(SystemConstants.VERIFYCODE);
        session.setAttribute(SystemConstants.VERIFYCODE , verifyCode);
        response.setContentType("image/jpeg");
        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
        ImageIO.write(bufferedImage, "jpeg", response.getOutputStream());
    }

    public String getRsaDecryStr(String str){
        //将加密字符串解密并返回
        String replaceStr = str.replace(" ", "+");
        return RSAUtils.decryptDataOnJava(replaceStr , privateKey);
    }


    @ApiOperation(value = "拦截登录接口", notes = "返回json,由前端判断,跳转登录页面" , httpMethod = "GET")
    @GetMapping(value = "goLogin")
    @ResponseBody
    public R goLogin(HttpServletRequest request){
        //清除redis中的登录信息
        if(redisUtil.hasKey(request.getSession().getId())) {
            redisUtil.del(request.getSession().getId());
        }
        //清除session
        SecurityUtils.getSubject().logout();
        return R.error(SystemConstants.AUTH_FAIL_CODE,"用户信息过期,请重新登录");
    }

    @ApiOperation(value = "没有权限时拦截到的接口", notes = "没有权限时拦截到的接口" , httpMethod = "GET")
    @GetMapping(value = "unauthorized")
    @ResponseBody
    public R unauthorized(){
        return R.error(SystemConstants.PARAM_INCORRECT_CODE,"抱歉,您当前没有权限访问!");
    }


    @ApiOperation(value = "退出登录", notes = "退出登录" , httpMethod = "GET")
    @GetMapping(value = "logout")
    @ResponseBody
    public R logout(HttpServletRequest request){
        //清除redis中的登录信息
        if(redisUtil.hasKey(request.getSession().getId())) {
            redisUtil.del(request.getSession().getId());
        }
        //清除session
        SecurityUtils.getSubject().logout();
        return R.ok();
    }
}

 

登录参数模块

 

package com.sf.detectcore.controller.login.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotBlank;

/**
 * @ClassName LoginModel
 * @Description 登录参数
 * @Author huyong
 * @Date 2019/10/16 17:34
 * @Version 1.0
 */
@ApiModel("登录参数模型")
@Data
public class LoginModel {

    @ApiModelProperty(value="账号",required = true,example = "admin")
    @NotBlank(message = "请输入用户名")
    private String account;

    @ApiModelProperty(value="密码",required = true,example = "Md0SXbpC9zjYN+qkoSgv2+5DI4JbH6HEuSRGQ/nh3SzxkUXWkx2iNquaYLcvxQGCU28vvVDrlXu7zKxE+NM+jxZDVZ9maZQ5eIlWYPHhFxEWeGnXKL+4amGWOZvoxyAVJ34+VAItzUQEGhSUZStz8rNKl38lQvFtlNJQXsGEb3o=")
    @NotBlank(message = "请输入密码")
    private String password;

    @ApiModelProperty(value="验证码",required = true)
    @NotBlank(message = "验证码不能为空")
    private String verifyCode;

}

用户模块控制器

 

package com.sf.detectcore.controller.user;

import com.sf.detectcore.config.constant.Constant;
import com.sf.detectcore.config.constant.SystemConstants;
import com.sf.detectcore.controller.query.UserQuery;
import com.sf.detectcore.controller.user.model.AddUserModel;
import com.sf.detectcore.controller.user.model.EditUserModel;
import com.sf.detectcore.controller.user.model.MenuResponse;
import com.sf.detectcore.entity.SysMenu;
import com.sf.detectcore.entity.SysUser;
import com.sf.detectcore.service.SysMenuService;
import com.sf.detectcore.service.SysUserService;
import com.sf.detectcore.util.R;
import com.sf.detectcore.util.rsa.RSAUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName SysUserController
 * @Description 管理员相关接口
 * @Author huyong
 * @Date 2019/10/8 18:23
 * @Version 1.0
 */
@Api(value = "系统用户相关接口" , description = "系统用户相关接口")
@RestController
@RequestMapping(value = "user")
public class SysUserController {

    private final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    /** RSA私钥 */
    @Value("${RSA.privateKey}")
    private String privateKey;

    /** RSA公钥 */
    @Value("${RSA.publicKey}")
    private String publicKey;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;


    @ApiOperation(value = "新增-系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "姓名",required = true,dataType = "String"),
            @ApiImplicitParam(name = "account",value = "登录账户(8位字母)",required = true,dataType = "String"),
            @ApiImplicitParam(name = "roleIds",value = "角色Id",required = true,dataType ="List"),
            @ApiImplicitParam(name = "labId",value = "实验室Id(实验室管理员必传)",dataType = "Long")
    })
    @PostMapping(value = "addUser")
    public R addUser(@Valid @RequestBody AddUserModel userModel, BindingResult bindingResult, HttpServletRequest request){
        if(bindingResult.hasErrors()){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, bindingResult.getFieldError().getDefaultMessage());
        }
        if(userModel.getRoleIds().isEmpty()){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "请选择用户角色!");
        }
        if(userModel.getRoleIds().size() != 1){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, "请选择一个角色!" );
        }

        String account = userModel.getAccount();
        SysUser checkUser = sysUserService.findUserByAccount(account);
        if(checkUser != null){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "当前用户名已存在,请重新设置!");
        }

        SysUser sessionUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userModel , user);
        user.setCreateId(sessionUser.getUserId());
        user.setUpdateId(sessionUser.getUserId());
        String encryptPwd = RSAUtils.encryptedDataOnJava(SystemConstants.DEFAULT_PASSWORD, publicKey);
        user.setPassword(encryptPwd);
        try{
            sysUserService.addUser(user);
            return R.ok(null, Constant.OK_MESSAGE_ADD);
        }catch (Exception e){
            logger.error("添加系统用户异常,操作人:{},异常信息:{}" , sessionUser.getUserId() , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "失败");
        }
    }

    @ApiOperation(value = "编辑-系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "姓名",required = true,dataType = "String"),
            @ApiImplicitParam(name = "account",value = "登录账户(8位字母)",required = true,dataType = "String"),
            @ApiImplicitParam(name = "roleIds",value = "角色Id",required = true,dataType ="List"),
            @ApiImplicitParam(name = "status",value = "状态(0:启用 1:禁用)",dataType = "Integer"),
            @ApiImplicitParam(name = "labId",value = "实验室Id(实验室管理员必传)",dataType = "Long")
    })
    @PostMapping(value = "editUser")
    public R editUser(@Valid @RequestBody EditUserModel userModel, BindingResult bindingResult, HttpServletRequest request){
        if(bindingResult.hasErrors()){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, bindingResult.getFieldError().getDefaultMessage());
        }
        Long userId = userModel.getUserId();
        if(userId == null || userId <= 0){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "参数缺失:id");
        }
        SysUser currentUser = sysUserService.getById(userId);
        if(currentUser == null){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "用户不存在,无法编辑!");
        }

        if(userModel.getRoleIds().isEmpty()){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "请选择用户角色!" );
        }
        currentUser.setRoleIds(userModel.getRoleIds());
        SysUser sessionUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        currentUser.setName(userModel.getName());
        currentUser.setAccount(userModel.getAccount());
        currentUser.setStatus(userModel.getStatus());
        currentUser.setUpdateId(sessionUser.getUserId());
        currentUser.setUpdateTime(new Date());
        currentUser.setLabId(userModel.getLabId());
        try {
            sysUserService.editUser(currentUser);
            return R.ok(Constant.OK_MESSAGE_UPDATE);
        }catch (Exception e){
            logger.error("编辑用户异常,操作人:{},异常信息:{}" , sessionUser.getUserId() , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "失败");
        }
    }


    @ApiOperation(value = "删除-系统用户")
    @ApiImplicitParam(name = "userIds",value = "用户主键Id集合",required = true,dataType = "List")
    @PostMapping(value = "deleteUser")
    public R deleteUser(@RequestParam(value = "userIds") String userIds , HttpServletRequest request){
        SysUser sessionUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        try {
            sysUserService.deleteUser(userIds);
            return new R(SystemConstants.SUCCESS_CODE , null , null);
        }catch (Exception e){
            logger.error("删除用户异常,操作人:{},异常信息:{}" , sessionUser.getUserId() , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "失败");
        }
    }

    @ApiOperation(value = "查询-用户数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "姓名",dataType = "String"),
            @ApiImplicitParam(name = "account",value = "登录账户(8位字母)",dataType = "String")
    })
    @PostMapping(value = "getUserPagingData")
    public R getUserPagingData(@RequestBody UserQuery userQuery , HttpServletRequest request){
        SysUser user = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        return sysUserService.getUserPagingData(userQuery , user);
    }

    @ApiOperation(value = "Id查询-用户详情信息")
    @ApiImplicitParam(name = "id",value = "用户主键ID",required = true,dataType = "Long")
    @GetMapping(value = "getUserById")
    public R getUserById(@RequestParam Long id){
        return sysUserService.getUserById(id);
    }

    public String getRsaDecryStr(String str){
        //将加密字符串解密并返回
        String replaceStr = str.replace(" ", "+");
        return RSAUtils.decryptDataOnJava(replaceStr , privateKey);
    }

    @ApiOperation(value = "修改-用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPassword",value = "旧密码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "newPassword",value = "新密码",required = true,dataType = "String")
    })
    @PostMapping(value = "updatePassword")
    public R updatePassword(@RequestParam String currentPassword , @RequestParam String newPassword , HttpServletRequest request){
        currentPassword = currentPassword.replace(" ", "+");
        newPassword = newPassword.replace(" ", "+");
        SysUser user = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        String userOldPwd = RSAUtils.decryptDataOnJava(user.getPassword(), privateKey);
        String pageUserPwd = RSAUtils.decryptDataOnJava(currentPassword, privateKey);
        if(!userOldPwd.equals(pageUserPwd)){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "旧密码错误!");
        }
        String userNewPwd = RSAUtils.decryptDataOnJava(newPassword, privateKey);
        if(!matchPassword(userNewPwd)){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "密码必须为10-16位,数字及大小写字母组成!");
        }
        try {
            user.setPassword(newPassword);
            user.setUpdateTime(new Date());
            sysUserService.updateById(user);
            return R.ok(null,"修改成功");
        }catch (Exception e){
            logger.error("用户:{}修改自己密码异常,异常信息:{}" , user.getUserId() , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE ,"修改失败" );
        }
    }
    static Boolean matchPassword(String pwd){
        String regex = "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{10,16}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(pwd);
        return matcher.matches();
    }

    @ApiOperation(value = "重置-用户密码")
    @ApiImplicitParam(name = "id",value = "重置用户Id",required = true,dataType = "Long")
    @GetMapping(value = "resetPassword")
    public R resetPassword(@RequestParam Long id, HttpServletRequest request) {
        SysUser sessionUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        SysUser user = sysUserService.getById(id);
        if(user == null){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE , "用户不存在,无法修改!" );
        }
        try{
            String encryptPwd = RSAUtils.encryptedDataOnJava(SystemConstants.DEFAULT_PASSWORD, publicKey);
            user.setPassword(encryptPwd);
            sysUserService.updateById(user);
            return R.ok();
        }catch (Exception e){
            logger.error("管理员{}重置用户:{}密码时异常,异常信息:{}" , sessionUser.getAccount() , user.getAccount(), e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "修改失败" );
        }
    }

    @ApiOperation(value = "查询-当前用户的菜单数据")
    @GetMapping(value = "getUserMenu")
    public R getUserMenu(HttpServletRequest request) {
        SysUser user = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        List<MenuResponse> userMenus = sysMenuService.findUserMenus(user.getUserId());
        return R.ok(userMenus);
    }


    @ApiOperation(value = "查询-当前用户在指定页面的权限")
    @PostMapping(value = "getUserPagePermission")
    public R getUserPagePermission(@RequestParam Long menuId , HttpServletRequest request){
        SysUser user = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        return sysUserService.findUserPagePermission(user.getUserId() , menuId);
    }

}

 

用户模块实体类

 

package com.sf.detectcore.controller.user.model;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @ClassName AddUserModel
 * @Description 新增系统用户请求实体类
 * @Author YangLei
 * @Date 2019/5/14 10:42
 * @Version 1.0
 **/

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AddUserModel {

    @ApiModelProperty(value = "姓名")
    @NotNull(message = "用户姓名不得为空")
    private String name;

    @ApiModelProperty(value = "登录账户(8位字母)")
    @NotNull(message = "登录账户不得为空")
    private String account;

    @ApiModelProperty(value = "角色id集合")
    @NotNull(message = "角色信息不能为空")
    private List<Long> roleIds;

    @ApiModelProperty(value = "实验室Id")
    private Long labId;

}

 

package com.sf.detectcore.controller.user.model;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @ClassName EditUserModel
 * @Description TODO
 * @Author YangLei
 * @Date 2019/5/14 10:44
 * @Version 1.0
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class EditUserModel {

    @ApiModelProperty(value = "自增id")
    private Long userId;

    @ApiModelProperty(value = "姓名")
    @NotNull(message = "用户姓名不得为空")
    private String name;

    @ApiModelProperty(value = "登录账户(8位字母)")
    @NotNull(message = "登录账户不得为空")
    private String account;

    @ApiModelProperty(value = "状态(0-正常;1-不可用)")
    private Integer status = 0;

    @ApiModelProperty(value = "角色id集合")
    @NotNull(message = "请选择角色!")
    private List<Long> roleIds;

    @ApiModelProperty(value = "实验室Id")
    private Long labId;
}
package com.sf.detectcore.controller.user.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.List;

/**
 * @ClassName MenuResponse
 * @Description 菜单响应数据模型
 * @Author huyong
 * @Date 2019/10/14 14:52
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class MenuResponse {

    private Long menuId;

    private String name;

    private String icon;

    private Long parentId;

    private String identity;

   private List<MenuResponse> children;
}

角色模块控制器

 

package com.sf.detectcore.controller.role;

import com.sf.detectcore.config.constant.SystemConstants;
import com.sf.detectcore.controller.query.RoleQuery;
import com.sf.detectcore.controller.role.model.AddRoleModel;
import com.sf.detectcore.controller.role.model.EditRoleModel;
import com.sf.detectcore.controller.role.model.EditRoleVerifyModel;
import com.sf.detectcore.entity.SysRole;
import com.sf.detectcore.entity.SysUser;
import com.sf.detectcore.service.SysRoleService;
import com.sf.detectcore.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @ClassName SysRoleController
 * @Description 角色相关接口
 * @Author huyong
 * @Date 2019/10/14 14:52
 * @Version 1.0
 */
@Api(value="系统角色相关接口",description = "系统角色相关接口")
@RestController
@RequestMapping(value= "role")
public class SysRoleController {

    private final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    private SysRoleService sysRoleService;

    @ApiOperation(value = "新增-角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "角色名称",required = true,dataType = "String"),
            @ApiImplicitParam(name = "permissionIds",value = "权限Id集合",required = true,dataType = "String"),
            @ApiImplicitParam(name = "remarks",value = "备注",dataType = "String")
    })
    @PostMapping(value = "addRole")
    public R addRole(@Valid @RequestBody AddRoleModel roleModel, BindingResult bindingResult, HttpServletRequest request){
        if(bindingResult.hasErrors()){
            return new R(SystemConstants.PARAM_INCORRECT_CODE,Boolean.FALSE ,bindingResult.getFieldError().getDefaultMessage());
        }
        SysRole role = new SysRole();
        BeanUtils.copyProperties(roleModel , role);
        SysUser sessionSysUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        role.setCreateId(sessionSysUser.getUserId());
        role.setUpdateId(sessionSysUser.getUserId());
        role.setCreateTime(new Date());
        //默认可用
        role.setStatus(SystemConstants.ROLE_STATUS_AVAILABLE);
        try{
            return sysRoleService.addRole(role);
        }catch (Exception e){
            logger.error("添加角色异常,操作人:{},异常信息:{}" , sessionSysUser.getUserId() , e);
            return new R(SystemConstants.SERVER_ERROR_CODE,Boolean.FALSE , "失败");
        }
    }

    @ApiOperation(value = "Id查询-角色的详情")
    @ApiImplicitParam(name = "id",value = "角色主键Id",required = true,dataType = "Long")
    @PostMapping(value = "getRoleById")
    public R getRoleById(@RequestParam Long id){
        return sysRoleService.getRoleById(id);
    }


    @ApiOperation(value = "编辑-角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId",value = "主键角色Id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "name",value = "角色名字",required = true,dataType = "String"),
            @ApiImplicitParam(name = "remarks",value = "备注",required = false,dataType = "String"),
            @ApiImplicitParam(name = "permissionIds",value = "权限Id集合",required = true,dataType = "String")
    })
    @PostMapping(value = "editRole")
    public R editRole(@Valid @RequestBody EditRoleModel roleModel, BindingResult bindingResult, HttpServletRequest request){
        if(bindingResult.hasErrors()){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, bindingResult.getFieldError().getDefaultMessage());
        }
        if(roleModel.getRoleId() == null){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, "请传入角色ID");
        }

        SysUser sessionSysUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        SysRole currentRole = sysRoleService.getByRoleId(roleModel.getRoleId());
        currentRole.setName(roleModel.getName());
        currentRole.setRemarks(roleModel.getRemarks());
        currentRole.setUpdateId(sessionSysUser.getUserId());
        currentRole.setUpdateTime(new Date());

        try{
            return sysRoleService.editRole(currentRole);
        }catch (Exception e){
            logger.error("编辑角色异常,操作人:{},异常信息:{}" , sessionSysUser.getUserId() , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "失败");
        }
    }


    @ApiOperation(value = "编辑-角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId",value = "主键角色Id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "name",value = "角色名字",required = true,dataType = "String"),
            @ApiImplicitParam(name = "remarks",value = "备注",required = false,dataType = "String"),
            @ApiImplicitParam(name = "permissionIds",value = "权限Id集合",required = true,dataType = "String")
    })
    @PostMapping(value = "editRoleVerify")
    public R editRoleVerify(@Valid @RequestBody EditRoleVerifyModel roleModel, BindingResult bindingResult, HttpServletRequest request){
        if(bindingResult.hasErrors()){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, bindingResult.getFieldError().getDefaultMessage());
        }
        if(roleModel.getRoleId() == null){
            return R.error(SystemConstants.PARAM_INCORRECT_CODE, "请传入角色ID");
        }

        SysUser sessionSysUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        SysRole currentRole = sysRoleService.getByRoleId(roleModel.getRoleId());
        currentRole.setUpdateId(sessionSysUser.getUserId());
        currentRole.setUpdateTime(new Date());
        currentRole.setPermissionIds(roleModel.getPermissionIds());

        try{
            return sysRoleService.editRole(currentRole);
        }catch (Exception e){
            logger.error("编辑角色权限异常,操作人:{},异常信息:{}" , sessionSysUser.getUserId() , e);
            return R.error(SystemConstants.SERVER_ERROR_CODE , "失败");
        }
    }


    @ApiOperation(value = "删除-角色信息")
    @ApiImplicitParam(name = "ids",value = "角色主键ID",required = true,dataType = "List")
    @PostMapping(value = "deleteRole")
    public R deleteRole(@RequestParam(value = "ids") String ids){
        return sysRoleService.deleteRole(ids);
    }

    @ApiOperation(value = "分页查询-角色列表")
    @ApiImplicitParam(name = "name",value = "角色名称",dataType = "String")
    @PostMapping(value = "getRolePagingData")
    public R getRolePagingData(@RequestBody RoleQuery roleQuery , HttpServletRequest request){
        SysUser SysUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        return sysRoleService.getRolePagingData(roleQuery , SysUser);
    }


    @ApiOperation(value = "查询-系统所有权限")
    @PostMapping(value = "getSystemPermission")
    public R getSystemPermission(){
        return sysRoleService.getSystemPermission();
    }


    @ApiOperation(value = "查询-获取所有系统角色")
    @PostMapping(value = "getSystemRole")
    public R getSystemRole(HttpServletRequest request){
        SysUser SysUser = (SysUser)request.getSession().getAttribute(SystemConstants.SESSION_USER);
        return sysRoleService.getSystemRole(SysUser);
    }


}

 

角色模块参数

 

package com.sf.detectcore.controller.role.model;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @ClassName AddRoleModel
 * @Description 新增角色参数实体类
 * @Author YangLei
 * @Date 2019/5/14 10:31
 * @Version 1.0
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AddRoleModel {

    @ApiModelProperty(value = "角色名称")
    @NotNull(message = "角色名称不能为空")
    private String name;

    @ApiModelProperty(value = "备注")
    private String remarks;

}

 

package com.sf.detectcore.controller.role.model;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;

/**
 * @ClassName EditRoleModel
 * @Description 编辑角色参数实体类
 * @Author YangLei
 * @Date 2019/5/14 10:35
 * @Version 1.0
 **/

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class EditRoleModel implements Serializable {

    @ApiModelProperty(value = "自增id")
    @NotNull(message = "自增id不能为空")
    private Long roleId;

    @ApiModelProperty(value = "角色名称")
    @NotNull(message = "角色名称不能为空")
    private String name;

    @ApiModelProperty(value = "备注")
    private String remarks;


}
package com.sf.detectcore.controller.role.model;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @description:
 * @author: 朱传捷  80004071
 * @date: 2019-10-17 14:37
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class EditRoleVerifyModel {

    @ApiModelProperty(value = "自增id")
    @NotNull(message = "自增id不能为空")
    private Long roleId;

    @ApiModelProperty(value = "角色所拥有的权限id集合")
    private List<Long> permissionIds;
}
package com.sf.detectcore.controller.role.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @ClassName RolePermissionParam
 * @Description TODO
 * @Author YangLei
 * @Date 2019/5/30 10:00
 * @Version 1.0
 **/

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RolePermissionParam {
    /**
     * 权限父id
     */
    private Long parentPermId;

    /**
     * 权限子id集合(包含多个父权限对应的子权限id)
     */
    private List<Long> permIds;
}

获取验证码工具类

 

package com.sf.detectcore.util;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @ClassName R
 * @Description 验证码工具类
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
public class VerifyCodeUtil {

    /**

     * 验证码类型为仅数字,即0~9

     */

    public static final int TYPE_NUM_ONLY = 0;



    /**

     * 验证码类型为仅字母,即大小写字母混合

     */

    public static final int TYPE_LETTER_ONLY = 1;



    /**

     * 验证码类型为数字和大小写字母混合

     */

    public static final int TYPE_ALL_MIXED = 2;



    /**

     * 验证码类型为数字和大写字母混合

     */

    public static final int TYPE_NUM_UPPER = 3;



    /**

     * 验证码类型为数字和小写字母混合

     */

    public static final int TYPE_NUM_LOWER = 4;



    /**

     * 验证码类型为仅大写字母

     */

    public static final int TYPE_UPPER_ONLY = 5;



    /**

     * 验证码类型为仅小写字母

     */

    public static final int TYPE_LOWER_ONLY = 6;



    private VerifyCodeUtil(){}



    /**

     * 生成随机颜色

     */

    private static Color generateRandomColor() {

        Random random = new Random();

        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));

    }





    /**

     * 生成图片验证码

     * @param type           验证码类型,参见本类的静态属性

     * @param length         验证码字符长度,要求大于0的整数

     * @param excludeString  需排除的特殊字符

     * @param width          图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)

     * @param height         图片高度

     * @param interLine      图片中干扰线的条数

     * @param randomLocation 每个字符的高低位置是否随机

     * @param backColor      图片颜色,若为null则表示采用随机颜色

     * @param foreColor      字体颜色,若为null则表示采用随机颜色

     * @param lineColor      干扰线颜色,若为null则表示采用随机颜色

     * @return 图片缓存对象

     */

    public static BufferedImage generateImageCode(int type, int length, String excludeString, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){

        String textCode = generateTextCode(type, length, excludeString);

        return generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor);

    }





    /**

     * 生成验证码字符串

     * @param type          验证码类型,参见本类的静态属性

     * @param length        验证码长度,要求大于0的整数

     * @param excludeString 需排除的特殊字符(无需排除则为null)

     * @return 验证码字符串

     */

    public static String generateTextCode(int type, int length, String excludeString){

        if(length <= 0){

            return "";

        }

        StringBuffer verifyCode = new StringBuffer();

        int i = 0;

        Random random = new Random();

        switch(type){

            case TYPE_NUM_ONLY:

                while(i < length){

                    int t = random.nextInt(10);

                    //排除特殊字符

                    if(null==excludeString || excludeString.indexOf(t+"")<0) {

                        verifyCode.append(t);

                        i++;

                    }

                }

                break;

            case TYPE_LETTER_ONLY:

                while(i < length){

                    int t = random.nextInt(123);

                    if((t>=97 || (t>=65&&t<=90)) && (null==excludeString||excludeString.indexOf((char)t)<0)){

                        verifyCode.append((char)t);

                        i++;

                    }

                }

                break;

            case TYPE_ALL_MIXED:

                while(i < length){

                    int t = random.nextInt(123);

                    if((t>=97 || (t>=65&&t<=90) || (t>=48&&t<=57)) && (null==excludeString||excludeString.indexOf((char)t)<0)){

                        verifyCode.append((char)t);

                        i++;

                    }

                }

                break;

            case TYPE_NUM_UPPER:

                while(i < length){

                    int t = random.nextInt(91);

                    if((t>=65 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){

                        verifyCode.append((char)t);

                        i++;

                    }

                }

                break;

            case TYPE_NUM_LOWER:

                while(i < length){

                    int t = random.nextInt(123);

                    if((t>=97 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){

                        verifyCode.append((char)t);

                        i++;

                    }

                }

                break;

            case TYPE_UPPER_ONLY:

                while(i < length){

                    int t = random.nextInt(91);

                    if((t >= 65) && (null==excludeString||excludeString.indexOf((char)t)<0)){

                        verifyCode.append((char)t);

                        i++;

                    }

                }

                break;

            case TYPE_LOWER_ONLY:

                while(i < length){

                    int t = random.nextInt(123);

                    if((t>=97) && (null==excludeString||excludeString.indexOf((char)t)<0)){

                        verifyCode.append((char)t);

                        i++;

                    }

                }

                break;

        }

        return verifyCode.toString();

    }



    /**

     * 已有验证码,生成验证码图片

     * @param textCode       文本验证码

     * @param width          图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)

     * @param height         图片高度

     * @param interLine      图片中干扰线的条数

     * @param randomLocation 每个字符的高低位置是否随机

     * @param backColor      图片颜色,若为null则表示采用随机颜色

     * @param foreColor      字体颜色,若为null则表示采用随机颜色

     * @param lineColor      干扰线颜色,若为null则表示采用随机颜色

     * @return 图片缓存对象

     */

    public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){

        //创建内存图像

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取图形上下文

        Graphics graphics = bufferedImage.getGraphics();

        //画背景图

        graphics.setColor(null==backColor ? generateRandomColor() : backColor);

        graphics.fillRect(0, 0, width, height);

        //画干扰线

        Random random = new Random();

        if(interLine > 0){

            int x = 0, y = 0, x1 = width, y1 = 0;

            for(int i=0; i<interLine; i++){

                graphics.setColor(null==lineColor ? generateRandomColor() : lineColor);

                y = random.nextInt(height);

                y1 = random.nextInt(height);

                graphics.drawLine(x, y, x1, y1);

            }

        }

        //字体大小为图片高度的80%

        int fsize = (int)(height * 0.8);

        int fx = height - fsize;

        int fy = fsize;

        //设定字体

        graphics.setFont(new Font("Default", Font.PLAIN, fsize));

        //写验证码字符

        for(int i=0; i<textCode.length(); i++){

            fy = randomLocation ? (int)((Math.random()*0.3+0.6)*height) : fy;

            graphics.setColor(null==foreColor ? generateRandomColor() : foreColor);

            //将验证码字符显示到图象中

            graphics.drawString(textCode.charAt(i)+"", fx, fy);

            fx += fsize * 0.9;

        }

        graphics.dispose();

        return bufferedImage;

    }
}

 

redis工具类

package com.sf.detectcore.util.redis;

import com.sf.detectcore.config.constant.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtil
 * @Description RedisUtil工具类
 * @Author huyong
 * @Date 2019/10/14 18:23
 * @Version 1.0
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * @Description:  指定缓存失效时间
     * @param key
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key,long time){
        try {
            if(time>0){
                redisTemplate.expire(SystemConstants.REDIS_KEY_PREFIX+key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 根据key 获取过期时间
     * @param key
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(SystemConstants.REDIS_KEY_PREFIX+key,TimeUnit.SECONDS);
    }

    /**
     * @Decription: 判断key是否存在
     * @param key
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(SystemConstants.REDIS_KEY_PREFIX+key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Decription: 删除缓存
     * @param key 可以传一个值 或多个
     */
    public void del(String ... key){
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(SystemConstants.REDIS_KEY_PREFIX+key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(SystemConstants.REDIS_KEY_PREFIX+key));
            }
        }
    }

    /**
     * @DesCription: 普通缓存获取
     * @param key
     * @return
     */
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(SystemConstants.REDIS_KEY_PREFIX+key);
    }

    /**
     * @Description: 普通缓存放入
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(SystemConstants.REDIS_KEY_PREFIX+key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 普通缓存放入并设置时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(SystemConstants.REDIS_KEY_PREFIX+key, value, time, TimeUnit.SECONDS);
            }else{
                redisTemplate.opsForValue().set(SystemConstants.REDIS_KEY_PREFIX+key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     * @param key 键
     * @param by 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(SystemConstants.REDIS_KEY_PREFIX+key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param by 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(SystemConstants.REDIS_KEY_PREFIX+key, -delta);
    }

    //================================Map=================================
    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return*/
    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(SystemConstants.REDIS_KEY_PREFIX+key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object,Object> hmget(String key){
        return redisTemplate.opsForHash().entries(SystemConstants.REDIS_KEY_PREFIX+key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String,Object> map){
        try {
            redisTemplate.opsForHash().putAll(SystemConstants.REDIS_KEY_PREFIX+key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String,Object> map, long time){
        try {
            redisTemplate.opsForHash().putAll(SystemConstants.REDIS_KEY_PREFIX+key, map);
            if(time>0){
                expire(SystemConstants.REDIS_KEY_PREFIX+key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value) {
        try {
            redisTemplate.opsForHash().put(SystemConstants.REDIS_KEY_PREFIX+key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value,long time) {
        try {
            redisTemplate.opsForHash().put(SystemConstants.REDIS_KEY_PREFIX+key, item, value);
            if(time>0){
                expire(SystemConstants.REDIS_KEY_PREFIX+key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item){
        redisTemplate.opsForHash().delete(SystemConstants.REDIS_KEY_PREFIX+key,item);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item){
        return redisTemplate.opsForHash().hasKey(SystemConstants.REDIS_KEY_PREFIX+key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key 键
     * @param item 项
     * @param by 要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(SystemConstants.REDIS_KEY_PREFIX+key, item, by);
    }

    /**
     * hash递减
     * @param key 键
     * @param item 项
     * @param by 要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(SystemConstants.REDIS_KEY_PREFIX+key, item,-by);
    }

    //============================set=============================
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key){
        try {
            return redisTemplate.opsForSet().members(SystemConstants.REDIS_KEY_PREFIX+key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key,Object value){
        try {
            return redisTemplate.opsForSet().isMember(SystemConstants.REDIS_KEY_PREFIX+key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object...values) {
        try {
            return redisTemplate.opsForSet().add(SystemConstants.REDIS_KEY_PREFIX+key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key,long time,Object...values) {
        try {
            Long count = redisTemplate.opsForSet().add(SystemConstants.REDIS_KEY_PREFIX+key, values);
            if(time>0) {
                expire(SystemConstants.REDIS_KEY_PREFIX + key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(SystemConstants.REDIS_KEY_PREFIX+key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object ...values) {
        try {
            Long count = redisTemplate.opsForSet().remove(SystemConstants.REDIS_KEY_PREFIX+key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end){
        try {
            return redisTemplate.opsForList().range(SystemConstants.REDIS_KEY_PREFIX+key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(SystemConstants.REDIS_KEY_PREFIX+key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(SystemConstants.REDIS_KEY_PREFIX+key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(SystemConstants.REDIS_KEY_PREFIX+key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(SystemConstants.REDIS_KEY_PREFIX+key, value);
            if (time > 0) {expire(key, time);}
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(SystemConstants.REDIS_KEY_PREFIX+key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(SystemConstants.REDIS_KEY_PREFIX+key, value);
            if (time > 0) {expire(key, time);}
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index,Object value) {
        try {
            redisTemplate.opsForList().set(SystemConstants.REDIS_KEY_PREFIX+key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key,long count,Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(SystemConstants.REDIS_KEY_PREFIX+key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}

项目配置文件

#RSA公私钥
RSA:
  privateKey: *****
  publicKey: ******

#shiro超时时间
shiro:
  timeout: 7200000

 

项目maven依赖

 

  <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
     <!-- SpringBoot AOP包,用于Shiro授权 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--Shiro核心包 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
<!-- RSA加解密时BASE64相关jar包 -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.60</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
 <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

posted on 2019-11-20 14:42  追风筝的人123  阅读(654)  评论(0编辑  收藏  举报

导航