SSM案例-企业权限系统(17)- 用户关联角色

1 用户关联角色

在这里插入图片描述

1.1 页面

在这里插入图片描述
在这里插入图片描述

1.2 DAO

public interface IUserDao {

@Select("select * from role where id not in" +
            "(select roleId from users_role where userId = #{userId})")
    List<Role> findOtherRoles(String userId) throws Exception;

    // 多个参数,参数前要加注解
    @Insert("insert into users_role(userId,roleId) values (#{userId},#{roleId})")
    void addRoleToUser(@Param("userId") String userId,@Param("roleId") String roleId);
}

1.3 Service

  • 接口
public interface IUserService extends UserDetailsService {

    List<UserInfo> findAll() throws Exception;

    void save(UserInfo userInfo) throws Exception;

    UserInfo findById(String id) throws Exception;

    List<Role> findOtherRoles(String userId) throws Exception;

    void addRoleToUser(String userId, String[] roleIds);
}

  • 实现类
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

   
    @Override
    public List<Role> findOtherRoles(String userId) throws Exception {
        return userDao.findOtherRoles(userId);
    }

    @Override
    public void addRoleToUser(String userId, String[] roleIds) {
        for (String roleId : roleIds) {
            userDao.addRoleToUser(userId, roleId);
        }
    }
}

1.4 Controller

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询用户以及用户可以添加的角色
     *
     * @param userId
     * @throws Exception
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userId) throws Exception {
        ModelAndView mv = new ModelAndView();
        // 1.根据用户 id 查询用户
        UserInfo userInfo = userService.findById(userId);

        // 2.根据用户 id 查询可以添加的角色
        List<Role> otherRoles = userService.findOtherRoles(userId);

        mv.addObject("user", userInfo);
        mv.addObject("roleList", otherRoles);

        mv.setViewName("user-role-add");
        return mv;
    }

    @RequestMapping("/addRoleToUser")
    public String addRoleToUser(@RequestParam(name = "userId",required = true) String userId,
                             @RequestParam(name="ids",required = true) String[] roleIds) throws Exception{
        userService.addRoleToUser(userId, roleIds);

        return "redirect:findAll.do";
    }

}


  • 添加角色前
    在这里插入图片描述
    在这里插入图片描述

  • 添加角色后
    在这里插入图片描述
    在这里插入图片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章