之前,在做用户管理的时候,并未处理“用户”与“角色”的关系,因为那个时候,还没有涉及到角色的实现。我们在做角色-权限管理的时候,也并没有处理 角色 和 用户 之间的关系。如今,再回过头来实现“用户”和 “角色”之间的联系。
“用户”和“角色”之间的关系是多对多的关系,这个关系可以分成两个:(1)“用户”与“用户角色”的一对多的关系、(2)“角色”与“用户角色”的一对多的关系。此刻,我们只实现“用户”与“用户角色”的一对多关系,而不去实现“角色”与“用户角色”。因此,我们需要在用户的添加和编辑页面能够对当前处理的用户的角色进行选择。
1、entity层
UserRole.java
package com.rk.tax.entity; import java.io.Serializable; public class UserRole implements Serializable { private UserRoleId id; public UserRole() { } public UserRole(UserRoleId id) { this.id = id; } public UserRoleId getId() { return id; } public void setId(UserRoleId id) { this.id = id; } }
UserRoleId.java
package com.rk.tax.entity; import java.io.Serializable; import org.apache.commons.lang3.StringUtils; public class UserRoleId implements Serializable { private Role role; private String userId; public UserRoleId() { } public UserRoleId(Role role, String userId) { this.role = role; this.userId = userId; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; UserRoleId other = (UserRoleId) obj; if(!StringUtils.equals(this.userId, other.userId)) return false; if (this.role == null && other.role != null) { return false; } else if (!this.role.equals(other.role)){ return false; } return true; } }
UserRole.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.rk.tax.entity" auto-import="true"> <class name="UserRole" table="R_User_Role"> <composite-id name="id" class="UserRoleId"> <key-many-to-one name="role" column="role_id" class="Role" lazy="false"></key-many-to-one> <key-property name="userId" column="user_id" type="string" length="32"></key-property> </composite-id> </class> </hibernate-mapping>
User.java 添加一个userRoles变量,用来维护 用户 和 用户角色 之间的关系,但不需要对User.hbm.xml(User类的映射文件)进行修改。
private List<UserRole> userRoles; public List<UserRole> getUserRoles() { return userRoles; } public void setUserRoles(List<UserRole> userRoles) { this.userRoles = userRoles; }
2、action层
这个时候,我们不是从entity->dao->service->action->config的方式去写,因此我们已经拥有了User、Role相关的dao、service、action层的代码,只需要对现有的代码进行修改就可以了。修改,应该从action层开始修改,再向service修改,最后向dao层修改。
在UserAction.java中主要修改的代码有:
//添加 //用户角色 private String[] userRoleIds; @Resource private RoleService roleService; //修改 //跳转到新增页面 public String addUI() //保存新增 public String add() //跳转到编辑页面 public String editUI() //保存编辑 public String edit()
UserAction.java
package com.rk.tax.action; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import com.rk.core.action.BaseAction; import com.rk.core.exception.ActionException; import com.rk.tax.entity.Role; import com.rk.tax.entity.User; import com.rk.tax.entity.UserRole; import com.rk.tax.entity.UserRoleId; import com.rk.tax.service.RoleService; import com.rk.tax.service.UserService; @Controller("userAction") @Scope("prototype") public class UserAction extends BaseAction { /***** 1、业务数据 *****/ private List<User> userList; //用于显示用户列表 private User user; //用于添加、修改和删除单个用户 //用户头像 private File headImg; private String headImgContentType; private String headImgFileName; //导入Excel private File userExcel; private String userExcelContentType; private String userExcelFileName; //用户角色 private String[] userRoleIds; /***** 2、业务实现类 *****/ @Resource private UserService userService; @Resource private RoleService roleService; /***** 3、页面响应操作 *****/ //跳转到新增页面 public String addUI() { //加载角色列表 ActionContext.getContext().getContextMap().put("roleList", roleService.findAll()); return "addUI"; } //保存新增 public String add() { try { if(user != null) { if(headImg != null) { //1、保存头像到upload/user String filePath = ServletActionContext.getServletContext().getRealPath("upload/user/"); String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf(".")); FileUtils.copyFile(headImg, new File(filePath,fileName)); //2、设置用户头像路径 user.setHeadImg("user/" + fileName); } // userService.save(user); userService.saveUserAndRole(user,userRoleIds); } } catch (Exception e) { e.printStackTrace(); } return "list"; } //跳转到编辑页面 public String editUI() { //加载角色列表 ActionContext.getContext().getContextMap().put("roleList", roleService.findAll()); if(user != null && user.getId() != null) { user = userService.findById(user.getId()); //处理角色回显 List<UserRole> list = userService.findUserRolesByUserId(user.getId()); if(list != null && list.size()>0){ userRoleIds = new String[list.size()]; for(int i=0;i<list.size();i++){ userRoleIds[i] = list.get(i).getId().getRole().getRoleId(); } } } return "editUI"; } //保存编辑 public String edit() { try { if(user != null) { //更新用户头像信息 if(headImg != null) { //1、保存头像到upload/user String filePath = ServletActionContext.getServletContext().getRealPath("upload/user/"); String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf(".")); FileUtils.copyFile(headImg, new File(filePath,fileName)); //2、设置用户头像路径 user.setHeadImg("user/" + fileName); } userService.updateUserAndUserRole(user,userRoleIds); } } catch (Exception e) { e.printStackTrace(); } return "list"; } // {{ Properties public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public File getHeadImg() { return headImg; } public void setHeadImg(File headImg) { this.headImg = headImg; } public String getHeadImgContentType() { return headImgContentType; } public void setHeadImgContentType(String headImgContentType) { this.headImgContentType = headImgContentType; } public String getHeadImgFileName() { return headImgFileName; } public void setHeadImgFileName(String headImgFileName) { this.headImgFileName = headImgFileName; } public File getUserExcel() { return userExcel; } public void setUserExcel(File userExcel) { this.userExcel = userExcel; } public String getUserExcelContentType() { return userExcelContentType; } public void setUserExcelContentType(String userExcelContentType) { this.userExcelContentType = userExcelContentType; } public String getUserExcelFileName() { return userExcelFileName; } public void setUserExcelFileName(String userExcelFileName) { this.userExcelFileName = userExcelFileName; } public String[] getUserRoleIds() { return userRoleIds; } public void setUserRoleIds(String[] userRoleIds) { this.userRoleIds = userRoleIds; } // }} }
addUI.jsp页面中的角色部分
<s:checkboxlist name="userRoleIds" list="#roleList" listKey="roleId" listValue="name"></s:checkboxlist>
editUI.jsp页面中的角色部分
<s:checkboxlist name="userRoleIds" list="#roleList" listKey="roleId" listValue="name"></s:checkboxlist>
3、service层
UserService.java
void saveUserAndRole(User user, String... userRoleIds); List<UserRole> findUserRolesByUserId(Serializable userId); void updateUserAndUserRole(User user, String... roleIds);
UserServiceImpl.java
public void saveUserAndRole(User user, String... roleIds) { userDao.save(user); if(roleIds != null && roleIds.length>0){ for(String roleId : roleIds){ Role role = new Role(roleId); UserRole userRole = new UserRole(new UserRoleId(role, user.getId())); userDao.saveUserRole(userRole); } } } public List<UserRole> findUserRolesByUserId(Serializable userId) { return userDao.findUserRolesByUserId(userId); } public void updateUserAndUserRole(User user, String... roleIds) { //1、更新用户信息 update(user); //2、更新用户角色信息 //2.1、删除用户原有的角色 userDao.deleteUserRoleByUserId(user.getId()); //2.2、为用户添加新的角色 if(roleIds != null && roleIds.length>0){ for(String roleId : roleIds){ Role role = new Role(roleId); UserRole userRole = new UserRole(new UserRoleId(role, user.getId())); userDao.saveUserRole(userRole); } } }
4、dao层
UserDao.java
void saveUserRole(UserRole userRole); List<UserRole> findUserRolesByUserId(Serializable userId); void deleteUserRoleByUserId(Serializable userId);
UserDaoImpl.java
public void saveUserRole(UserRole userRole) { getHibernateTemplate().save(userRole); } @SuppressWarnings("unchecked") public List<UserRole> findUserRolesByUserId(Serializable userId) { Query query = getSession().createQuery("from UserRole where id.userId=?"); query.setParameter(0, userId); return query.list(); } public void deleteUserRoleByUserId(Serializable userId) { Query query = getSession().createQuery("delete from UserRole where id.userId=?"); query.setParameter(0, userId); query.executeUpdate(); }
时间: 2024-12-13 11:22:57