用户角色关联
用户与角色之间是多对多关系,我们要建立它们之间的关系,只需要在中间表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);
用于添加用户与角色关系