Spring Boot与Shiro实现权限管理04

本文档详细介绍了如何在SpringBoot项目中使用Shiro实现用户管理,包括用户列表查询、角色分配以及通知功能的创建。通过创建DTO、Controller、Service、Mapper各层实现CRUD操作,并提供了相应的权限控制。此外,还展示了如何为用户分配角色,以及创建通知的完整流程,涉及Service和Mapper的事务处理。最后,给出了部分SQL语句示例,用于权限分配和数据插入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.实现用户管理

1.1 用户列表

首先创建dto,用于请求与响应数据的传输。在common包下创建dto包,在该包下创建UserDto.java类。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto implements Serializable {

    private Integer id;
    private String username;
}
创建Controller层

在controller包下的UserController.java类添加用户查询控制器。

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;


    @RequiresPermissions("user:list")
    @ApiOperation("用户列表")
    @GetMapping("/users")
    public ResponseEntity<PageModel<UserDto>> list(@RequestParam(required = false) Integer pageSize,
                                                   @RequestParam(required = false) Integer pageNum) {
        PageCondition pc = new PageCondition(pageNum, pageSize);
        PageModel<UserDto> pageModel = userService.listAllUser(pc);
        return Results.success(pageModel);
    }
}
创建Service层

在service包下的UserService.java类添加查询用户列表方法。

    /**
     * 查询用户列表
     * @param condition
     * @return
     */
    PageModel<UserDto> listAllUser(PageCondition condition);
    @Override
    public PageModel<UserDto> listAllUser(PageCondition condition) {
        PageHelper.startPage(condition.getPageNum(), condition.getPageSize());
        PageInfo<UserDto> pageInfo = new PageInfo<>(sysUserMapper.findAll());
        return Results.pageModel(pageInfo);
    }
创建Mapper层
    /**
     * 查询用户列表
     * @return
     */
    List<UserDto> findAll();
  <select id="findAll" resultType="com.picacho.springbootshiro.common.dto.UserDto">
    select
        id,
        username
    from sys_user
  </select>
测试一下

在这里插入图片描述
后面对用户的新增,删除和修改等功能,其实现方式和流程与上面的流程基本一致,这里就不一一详细介绍了。

2.实现用户角色分配

前面已经创建了一个新的角色:“角色分配管理员A”,同时这个角色已经被分配了三个权限,接着在用户管理模块创建picachoA用户,为这个用户指定角色,角色被分配了一组权限,这就决定了这个用户访问系统时拥有这组权限。

完成Controller层
   @RequiresPermissions("user:assign-role")
    @ApiOperation("用户角色分配")
    @PutMapping("/user/{id}/role")
    public ResponseEntity assignRole(@RequestBody List<Integer> roleIdList, @PathVariable Integer id) {
        userService.assignRole(id, roleIdList);
        return Results.success();
    }
完成Service层
   /**
     * 用户角色分配
     * @param id
     * @param roleIdList
     */
    void assignRole(Integer id, List<Integer> roleIdList);
    @Transactional
    @Override
    public void assignRole(Integer userId, List<Integer> roleIdList) {
        if (sysUserMapper.find(userId) == null) {
            throw Errors.badRequest("用户不存在");
        }
        if (!CollectionUtils.isEmpty(roleIdList)) {
            int count = sysRoleMapper.countByIds(roleIdList);
            if (count != roleIdList.size()) {
                throw Errors.badRequest("角色不存在");
            }
        }
        sysUserRoleMapper.deleteByUserId(userId);
        if (!CollectionUtils.isEmpty(roleIdList)) {
            List<SysUserRole> rps = roleIdList.stream().map(p -> {
                SysUserRole rp = new SysUserRole();
                rp.setRoleId(p);
                rp.setUserId(userId);
                return rp;
            }).collect(Collectors.toList());
            if (sysUserRoleMapper.insertBatch(rps) != roleIdList.size()) {
                throw Errors.db();
            }
        }
    }
完成mapper层

SysRoleMapper

    int countByIds(@Param("roleIdList") List<Integer> roleIdList);
  <select id="countByIds" resultType="java.lang.Integer">
    select COUNT(*)
    FROM sys_role sp
    WHERE sp.id IN
    <foreach collection="roleIdList" item="k" open="(" separator="," close=")">#{k}</foreach>
  </select>

SysUserRoleMapper

    void deleteByUserId(Integer userId);

    int insertBatch(@Param("rps") List<SysUserRole> rps);
  <delete id="deleteByUserId">
    delete
    from sys_user_role
    where user_id = #{userId}
  </delete>

  <insert id="insertBatch">
    insert into sys_user_role (role_id, user_id)
    values
    <foreach collection="rps" item="t" separator=",">
      (#{t.roleId},#{t.userId})
    </foreach>
  </insert>
测试一下

登陆超级管理员为用户picachoA分配角色分配管理员A,接着使用用户picachoA登陆查看其拥有的权限。

首先给超级管理员添加用户角色分配权限。

INSERT INTO `sys_permission`(id, permission_code, permission_name)
    VALUE (901, 'user:assign-role', '用户角色分配');

INSERT INTO `sys_role_permission`(role_id, permission_id)
VALUES (1, 901);

在这里插入图片描述
此时为picachoA用户添加了“角色分配管理员A”的角色,这个用户就拥有了这个角色对应的权限了。

3.实现通知

3.1 实现新建通知

完成Controller层

在controller包下创建NotifyController.java类。

@RestController
@RequestMapping("api")
public class NotifyController {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserService userService;


    @RequiresPermissions("notify:add")
    @ApiOperation("创建通知")
    @PostMapping("/notify")
    public ResponseEntity<NotifyDto> add(@RequestBody String content) {
        if (StringUtils.isBlank(content)) {
            return Results.userInputError("通知内容不能为空");
        }

        String username = (String) SecurityUtils.getSubject().getPrincipal();
        Integer userID = userService.findUserID(username);
        NotifyDto dto = notifyService.create(userID, content);
        return Results.success(dto);
    }
}
完成Service层

UserService

    /**
     * 查询用户
     * @param username
     * @return
     */
    Integer findUserID(String username);
    @Override
    public Integer findUserID(String username) {
        SysUser user = sysUserMapper.findByUsername(username);
        if (user == null) {
            return null;
        }

        return user.getId();
    }

NotifyService

public interface NotifyService {

    NotifyDto create(Integer userId, String content);
}

@Service
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    private NotifyMapper notifyMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Transactional
    @Override
    public NotifyDto create(Integer userId, String content) {
        if (sysUserMapper.find(userId) == null) {
            throw Errors.badRequest("用户不存在");
        }

        Notify sr = new Notify();
        sr.setUserId(userId);
        sr.setContent(content);
        if (1 != notifyMapper.insert(sr)) {
            throw new ServiceException("无法新增通知记录到数据库");
        }

        return notifyMapper.findById(sr.getId());
    }

}
完成mapper层
NotifyDto findById(Integer id);
  <select id="findById" resultType="com.picacho.springbootshiro.common.dto.NotifyDto">
    select n.id, su.id as userId, su.username, n.content
    from notify n
           left join sys_user su on su.id = n.user_id
    where n.id = #{id}
  </select>
测试一下

添加一个通知管理员用户

INSERT INTO `sys_role`(id, role_name)
    VALUE (3, '通知管理员');

INSERT INTO `sys_role_permission`(role_id, permission_id)
VALUES (3, 101),
       (3, 102),
       (3, 103),
       (3, 104);

INSERT INTO `sys_user`(id, username, password)
    VALUE (10003, 'picacho', '123456');

INSERT INTO `sys_user_role`(user_id, role_id)
    VALUE (10003, 3);

在这里插入图片描述
还有通知的查询,编辑,删除就不一一实现,这个demo项目到这里就基本结束了。
源码下载地址:源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

picacho_pkq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值