一、面向对象思想简化数据库操作
public List<Role> getObjectsByIds(List<AdminRole> adminRoles) {
List<Role> roles=new ArrayList<Role>();
for(AdminRole ar:adminRoles){
roles.add(findById(ar.getRole().getId()));
}
return roles;
}
等同于:
private List<Role> tests(List<AdminRole> adminRoles){
if(adminRoles!=null){
StringBuffer sb=new StringBuffer();
int len=adminRoles.size();
sb.append("(");
for(int i=0;i<len;i++){
AdminRole ar=adminRoles.get(i);
System.out.println(ar.getId()+"---------------"+ar.getRole().getId());
if(i==0){
sb.append(ar.getRole().getId());
}else{
sb.append(","+ar.getRole().getId());
}
}
sb.append(")");
System.out.println(sb.toString());
String sql="select id,name,description from role where id in "+sb.toString();
return jdbcTemplate.query(sql,new RowMapper<Role>(){
@Override
public Role mapRow(ResultSet rs, int arg1)
throws SQLException {
Role role=new Role();
role.setId(rs.getInt("id"));
role.setName(rs.getString("name"));
role.setDescription(rs.getString("description"));
return role;
}});
}else{
return null;
}
}
二、选择授予角色的操作
if("grant".equals(oper)){
String aid=request.getParameter("aid");
Integer id=Integer.valueOf(aid);
Admin admin=adminService.findById(id);
//查询用户对应的角色信息
List<Role> adminRoles=roleService.getObjectsByIds(adminRoleService.getObjectsByAid(id));
//查询系统角色
List<Role> roles=roleService.getObjects();
request.setAttribute("admin", admin);//存储用户信息
request.setAttribute("adminRoles", adminRoles);//存储用户角色信息
request.setAttribute("roles", roles);//存储系统角色信息
request.getRequestDispatcher("./user/admin_role.jsp").forward(request, response);
}
三、授予角色过程
if("role".equals(oper)){
String aid=request.getParameter("aid");
int id=Integer.valueOf(aid);
List<AdminRole> adminRoles=adminRoleService.getObjectsByAid(id);
//创建一个集合,存储该用户已存在的角色值
List<Integer> lids=new ArrayList<Integer>();
if(adminRoles!=null){
for(AdminRole ar:adminRoles){
lids.add(ar.getId());
}
}
//获取用户新赋予的角色值
String[] rids=request.getParameterValues("rids");
if(rids!=null&&rids.length>0){
for(int i=0;i<rids.length;i++){
int rid=Integer.parseInt(rids[i]);
if(lids.contains(rid)){
System.out.println("已经存在就不处理");
lids.remove(rid);
}else{
//第一种情况,数据库本身没有
Admin admin=new Admin();
admin.setId(id);
Role role=new Role();
role.setId(rid);
adminRoleService.insertObject(new AdminRole(admin, role));
}
}
//把没有赋予的角色,但本来存在的角色删除掉
if(lids.size()>0){
for(Integer did:lids){
adminRoleService.deleteObjectById(did);
}
}
}else{
//如果为null,说明该用户不再被赋予角色
//判断已有角色是否为空
if(adminRoles!=null){
for(AdminRole ar:adminRoles){
adminRoleService.deleteObjectById(ar.getId());
}
}
}
request.getRequestDispatcher("./admin.do?oper=select").forward(request, response);
}