当我们根据角色id,获取该角色拥有的所有的权限,然后使用zTree控件进行展示,这个zTree控件可以对当前角色的权限进行维护,那么我们如何保存该角色的权限信息呢?
JSP页面
<div style="margin:1px;padding-left:45px;">
<input type="hidden" id="editAuthRoleId" value="${editAuthRoleId }"/>
<input type="button" onclick="addRoleAuth()" value="保存" class="btn btn-primary">
</div>
JS代码
/**
* 保存角色菜单权限
*/
function addRoleAuth(){
var roleid = $("#editAuthRoleId").val();
if(roleid==""){
showMessageDialog("保存失败,请选择角色进行编辑");
return false;
}
nodes=zTree.getCheckedNodes(true);
var authIds="";
for(var i=0;i<nodes.length;i++){
if(i+1<nodes.length){
authIds+=nodes[i].id+",";
}else{
authIds+=nodes[i].id;
}
}
$.ajax({
url: webContext+"/platform/role/editRoleAuth/"+roleid,
type: 'POST',
dataType:"json",
data:{
authIds:authIds
},
error: function(){
showMessageDialog("请求错误,保存失败!");
},
success: function(result){
if(result.success){
showMessageDialog("角色权限保存成功!",function(){
getAuthTreeByRole(roleid);
});
}else{
showMessageDialog("角色权限保存失败!!");
}
}
});
}
Controller
/**
*
* 方法说明:编辑角色权限信息
* @param roleid 角色id
* @param authIds 权限id字符串,逗号分隔
* @return
* @author wangchaojie 2015年9月25日
*
*/
@RequestMapping(value = "/editRoleAuth/{roleid}")
@ResponseBody
public AjaxResult editRoleAuth(@PathVariable("roleid") long roleid, @RequestParam String authIds) {
AjaxResult ajaxResult = AjaxResult.errorResult("");
if(roleid == 0){
return ajaxResult;
}
try{
List<Long> authIdList = StrUtils.splitToListLong(authIds, ",");
roleAuthService.editRoleAuth(roleid,authIdList);
}catch(Exception e){
e.printStackTrace();
return ajaxResult;
}
return AjaxResult.successResult();
}
Service层
/**
*
* 方法说明:编辑角色权限信息
* @param roleid 角色id
* @param authIdList 权限idList
* @author wangchaojie 2015年9月25日
*
*/
@Transactional
public void editRoleAuth(long roleid, List<Long> authIdList) {
roleAuthDao.deleteByRoleidFk(roleid);
for(Long authId : authIdList){
RoleAuth roleAuth = new RoleAuth(authId,roleid);
roleAuthDao.save(roleAuth);
}
}
Dao层,持久层使用spring data jpa
@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity
* @return the saved entity
*/
<S extends T> S save(S entity);