本节介绍利用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 Listchildren; 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 getChildren() { return children; } public void setChildren(List 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 ListpermissionIds; /** * 角色所拥有的权限集合 */ @TableField(exist = false) private List 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 getPermissionIds() { return permissionIds; } public void setPermissionIds(List permissionIds) { this.permissionIds = permissionIds; } public List getPermissions() { return permissions; } public void setPermissions(List 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 ListroleIds; /** * 角色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 getRoleIds() { return roleIds; } public void setRoleIds(List 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
SELECT LAST_INSERT_ID() insert into m_menu (`name`, icon, parent_id, `status`) values (#{name,jdbcType=VARCHAR}, #{icon,jdbcType=VARCHAR}, #{parentId,jdbcType=BIGINT}, #{status,jdbcType=TINYINT})
SELECT LAST_INSERT_ID() 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})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} delete from sys_role where role_id = #{roleId,jdbcType=BIGINT}
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} delete from sys_user where user_id = #{userId,jdbcType=BIGINT}
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{ /** * 插入一条数据 * @param record * @return */ @Override int insert(SysMenu record); /** * 根据用户id查询他拥有所有菜单 * @param userId * @return List */ List getMenusByUserId(Long userId); /** * 根据父Id(parentId) 查询二级菜单 * @param parentId * @return */ List 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{ /** * 根据用多个角色id查询拥有的权限 * @param roleIds * @return List */ List getPermissionsByRoles(@Param("roleIds")List roleIds); /** * 查询系统所有有效权限 * @return List */ List getAllPermissions(); /** * 根据主键Id查询权限 * @param permissionId * @return */ SysPermission selectByPrimaryKey(Long permissionId); /** * 查询用户的角色id * @param userId * @return Long */ Long getUserRoleId(Long userId); /** * 查询用户对应角色拥有的权限id * @param roleId * @return List */ List getUserPermIds(Long roleId); /** * 根据权限id查询一条权限数据(二级菜单权限) * @param permId * @return SysPermission */ SysPermission getTwoMenuPermById(Long permId); /** * 查询一条权限的所有子权限数据 * @param param * @return List */ List 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{ /** * 插入一条数据 * @param record * @return */ @Override int insert(SysRole record); /** * 根据用户自增id查询他拥有的角色 * @param id * @return List */ List 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 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{ /** * 根据主键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{ List 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 findUserPagePermission(Map 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{ }
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{ /** * 根据用户id查询他拥有的菜单 * @param userId * @returist */ List 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{ /** * 根据用户的多个角色查询拥有的权限 * @param roles * @return */ List findPermissionsByRoles(List roles); /** * 查询系统所有有效权限 * @return List */ List 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{ }
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{ /** * 根据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{ }
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{ /** * 根据账号查询用户 * @param account * @return SysUser */ SysUser findUserByAccount(String account); /** * 根据用户自增id查询他拥有的角色 * @param * @return List */ List 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 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 ServiceImplimplements SysMenuService { private final Logger logger = LoggerFactory.getLogger(SysMenuServiceImpl.class); @Autowired private SysMenuMapper sysMenuMapper; @Override public List findUserMenus(Long userId) { List list = new ArrayList<>(); //所有菜单 List sysMenus = sysMenuMapper.getMenusByUserId(userId); if(sysMenus != null && sysMenus.size() != 0) { for(MenuResponse menuResponse: sysMenus) { List 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 ServiceImplimplements SysPermissionService { private final Logger logger = LoggerFactory.getLogger(SysPermissionServiceImpl.class); @Autowired SysPermissionMapper sysPermissionMapper; @Override public List findPermissionsByRoles(List roles) { List 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 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 ServiceImplimplements 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 ServiceImplimplements 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 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 wrapper = new QueryWrapper<>(); wrapper.eq("role_id" ,sysRole.getRoleId()); sysRolePermissionMapper.delete(wrapper); List 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 wrapper = new QueryWrapper<>(); wrapper.eq("role_id" , id); List relations = sysRolePermissionMapper.selectList(wrapper); logger.info("relations:{}",relations); List 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 urWrapper = new QueryWrapper<>(); urWrapper.in("role_id" , ids.split(",")); List relations = sysUserRoleMapper.selectList(urWrapper); if(relations != null && relations.size() >= 1){ return R.error(SystemConstants.PARAM_INCORRECT_CODE,"所选角色有系统用户使用,不能删除!"); } for (String id : ids.split(",")) { //删除角色-权限数据 QueryWrapper 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 wrapper = new QueryWrapper<>(); if(roleQuery.getName() != null && !roleQuery.getName().isEmpty()){ wrapper.like("name" , roleQuery.getName()); } //角色列表,不展示超级管理员,数据库表统一配置为自增id为1 wrapper.notIn("role_id",1); IPage 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 permission = new ArrayList<>(); try{ //查询出所有父权限Id QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("parent_id",0); List sysPermissions1 = sysPermissionMapper.selectList(queryWrapper); permission.addAll(sysPermissions1); for (SysPermission sysPermission1:sysPermissions1){ QueryWrapper queryWrapper1 = new QueryWrapper<>(); queryWrapper1.eq("parent_id",sysPermission1.getPermissionId()); List sysPermissions2 = sysPermissionMapper.selectList(queryWrapper1); sysPermission1.setChildren(sysPermissions2); for (SysPermission sysPermission2:sysPermissions2){ QueryWrapper queryWrapper2 = new QueryWrapper<>(); queryWrapper2.eq("parent_id",sysPermission2.getPermissionId()); List 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 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 ServiceImplimplements 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 ServiceImplimplements 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 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 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 wrapper = new QueryWrapper<>(); wrapper.eq("user_id" , user.getUserId()); sysUserRoleMapper.delete(wrapper); List 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 wrapper = new QueryWrapper<>(); wrapper.eq("user_id" , userId); sysUserRoleMapper.delete(wrapper); } } @Override public R getUserPagingData(UserQuery userQuery, SysUser user) { QueryWrapper 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 pageData = sysUserMapper.selectPage(new Page<>(userQuery.getPageNum(), userQuery.getPageSize()), wrapper); List users = pageData.getRecords(); for (SysUser userd : users) { if(userd.getLabId() != null){ Lab lab = labMapper.selectById(userd.getLabId()); userd.setLabName(lab.getName()); } //默认一个 用户仅存在一个角色 List 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 wrapper = new QueryWrapper<>(); wrapper.eq("user_id" , id); List relationList = sysUserRoleMapper.selectList(wrapper); List 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 getUsersByStationId(Long stationId) { // QueryWrapperwrapper = 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); Mapmap = new HashMap<>(); map.put("roleId" , roleId); map.put("menuId" , menuId); List 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 listQueryByLabId(Long id) { QueryWrapper 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 , "密码错误!"); } Listroles = 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
登录参数模块
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); ListuserMenus = 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 ListroleIds; @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 ListroleIds; @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 Listchildren; }
角色模块控制器
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 ListpermissionIds; }
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 ListpermIds; }
获取验证码工具类
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){ 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 ){ 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 Maphmget(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 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 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 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 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 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 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依赖
org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-aop org.apache.shiro shiro-spring 1.4.0 org.apache.shiro shiro-core 1.4.0 org.bouncycastle bcprov-jdk15on 1.60 org.springframework.security spring-security-crypto 5.1.2.RELEASE com.baomidou mybatis-plus-boot-starter 3.1.1 org.projectlombok lombok 1.18.2 provided