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";
}
}
- 添加角色前
- 添加角色後