用户关联角色操作-代码实现

用户角色关联

用户与角色之间是多对多关系,我们要建立它们之间的关系,只需要在中间表user_role插入数据即可。

用户角色关联相关页面

在user-list.jsp页面上添加链接

<a href="${pageContext.request.contextPath}/user/findUserByIdAndAllRole.do?id=${user.id}"
class="btn bg-olive btn-xs">添加角色</a>

UserController

findUserByIdAndAllRole(Long id)方法

此方法用于查找要操作的用户及可以添加的角色,参数是要操作的用户id

@RequestMapping("/findUserByIdAndAllRole.do")
public ModelAndView findUserByIdAndAllRole(Long id) throws Exception {
	UserInfo user = userService.findById(id);
	List<Role> roleList = roleService.findOtherRole(id);
	ModelAndView mv = new ModelAndView();
	mv.addObject("user", user);
	mv.addObject("roleList", roleList);
	mv.setViewName("user-role-add");
	return mv;
}

调用IUserService的findById方法获取要操作的User

调用IRoleService的findOtherRole方法用于获取可以添加的角色信息

addRoleToUser(Long userId,Long[] ids)方法

些方法用于在用户与角色之间建立关系,参数userId代表要操作的用户id,参数ids代表的是角色id数组

@RequestMapping("/addRoleToUser.do")
public String addRoleToUser(Long userId, Long[] ids) throws Exception {
	userService.addRoleToUser(userId,ids);
	return "redirect:findAll.do";
}

Dao

IRoleDao

@Select("select * from role where id not in( select roleId from user_role where userId=#
{id})")
public List<Role> findOtherRole(Long id);

用于查找可以添加的角色

IUserDao

@Insert("insert into user_role(userId,roleId) value(#{userId},#{roleId})")
public void addRoleToUser(@Param("userId") Long userId, @Param("roleId") Long roleId);

用于添加用户与角色关系

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值