角色的新增

1,打开新增页面时,需要使用xml文件中的内容来初始化复选框

2,保存时要将名称存入角色表,将选择的权限存入到角色权限中间表


DAO:

public void insert(Role role) throws DAOException {
	if(role==null){
		return;
	}
	
	String sql = "insert into role_info values(role_seq.nextval, ?)";
	Connection con = DBUtil.getConnection();
	
	try {
		con.setAutoCommit(false);
		
		String[] columnNames = new String[]{"id"};
		//插入角色表,插入时指定要返回的列名,插入后可以得到该列的值
		PreparedStatement ps = con.prepareStatement(sql, columnNames);
		ps.setObject(1, role.getName());
		ps.executeUpdate();
		
		//取到插入的id列
		ResultSet rs = ps.getGeneratedKeys();
		Integer roleId = null;
		if(rs.next()){
			roleId = rs.getInt(1);
		}
		
		//插入中间表
		List pids = role.getPrivilegeIds();
		if(pids!=null && pids.size()>0){
			String sql2 = "insert into role_privilege values (?,?)";
			PreparedStatement ps2 = con.prepareStatement(sql2);
			for(Integer pid: pids){
				ps2.setObject(1, roleId);
				ps2.setObject(2, pid);
				ps2.addBatch();
			}
			ps2.executeBatch();
		}
		con.commit();
	} catch (SQLException e) {
		e.printStackTrace();
		try {
			con.rollback();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		throw new DAOException("新增角色失败!", e);
	} finally{
		DBUtil.close();
	}
}

Action:

public class ToAddRoleAction {
	
	public String execute(){
		
		privileges = PrivilegeReader.getPrivileges();
		return "success";
	}
	
	//output,权限集合用于初始化复选框
	private List privileges;

	public List getPrivileges() {
		return privileges;
	}

	public void setPrivileges(List privileges) {
		this.privileges = privileges;
	}
	
}

public class AddRoleAction {
	
	public String execute(){
		IRoleDAO dao = DAOFactory.getRoleDAO();
		try {
			dao.insert(role);
		} catch (DAOException e) {
			e.printStackTrace();
			return "error";
		}
		
		return "success";
	}
	//input
	private Role role;

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	
}

struts.xml



	
		/WEB-INF/role/addRole.jsp
	



	
		findRole
	

Jsp:

角色名称:
*
不能为空,且为20长度的字母、数字和汉字的组合
设置权限:
*
至少选择一个权限


你可能感兴趣的:(Java)