我用的是5张表 分别是:
用户表:
角色表:
用户角色表:
资源表:
角色资源表:
==========================================================================树形插件是ztree: (下载地址:)https://gitee.com/zTree/zTree_v3;
主要代码:这是我写的代码,(总结,仅供参考)
(用户管理)
/**
* 跳转到index页面
* @return
*/
@RequestMapping("toindex")
public String toindex() {
return "sys_manager/user/index";
}
/**
* 跳转到添加页面
* @return
*/
@RequestMapping("toadd")
public String toadd(ModelMap map) {
List<User> id = userService.orderById();//查询id的值
if(id!=null&&id.size()>0) {
String str = id.get(0).getId();
Integer j = Integer.valueOf(str.substring(0, str.length()))+1;//截取后让他递增
map.addAttribute("str", String.valueOf(j));
}else {
map.addAttribute("str","1");
}
List<Role> roles = roleService.findAll();
map.addAttribute("roles", roles);
return "sys_manager/user/add";
}
@RequestMapping("save")
public @ResponseBody MsgUtil save(User user,String mb001) {
try {
//给密码加密
if(IsNotNullUtil.isNotNull(user.getPassword())) {
String pwd = user.getPassword();
String pass = Salt.generate(pwd);
user.setPassword(pass);
}
//设置是否启用
//设置是否可以删除
//设置创建时间
//先执行添加用户的操作
userService.save(user);
//根据该对象获取该角色id
String[] areArr = mb001.split(",");
//截取增加,通过,分开
for (int i = 0; i < areArr.length; i++) {
UserAndRole ur= new UserAndRole();
ur.setId(user.getId());
ur.setUid(user.getId());
ur.setRid(areArr[i]);
userService.insertUserAndRole(ur);
}
return MsgUtil.result(true, "添加成功");
} catch (Exception e) {
return MsgUtil.result(false, "添加失败");
}
}
@RequestMapping("login")
public @ResponseBody MsgUtil login(User admma,ModelMap map,HttpSession session) throws UnknownHostException {
Admma ads = userService.selectByUserName(admma.getMa001());
String ma003 = ads.getPassword();
if(IsNotNullUtil.isNotNull(admma.getPassword())) {
boolean verify = Salt.verify(admma.getPassword(), ma003);
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateString = format.format(date);
if(verify==true) {
if(IsNotNullUtil.isNotNull(ads)) {
Set<String> selectResourcesList = resourceService.selectResourcesList(ads.getMa001());
UserSession userSession = new UserSession();
//用户id
userSession.setMa001(ads.getId());
//用户名称
userSession.setMa002(ads.getName());
//设置到期时间
userSession.setMa014(ads.getPassword());
//用户的资源
userSession.setResourceList(selectResourcesList);
//左边的菜单栏
List<Admmd> selectMenu = resourceService.selectMenu(ads.getMa001());
userSession.setResources(resourceService.selectMenu(ads.getMa001()));
//用户拥有的角色
session.setAttribute("userSession", userSession);
}
}
return MsgUtil.result(true, "登录成功");
}
}
return MsgUtil.result(false, "登录失败!!!!(用户名或者密码错误!!)");
}
/**
* 退出登录
* @param session
* @return
*/
@RequestMapping("logOut")
public @ResponseBody MsgUtil logOut(HttpSession session) {
session.removeAttribute("userSession");
return MsgUtil.result(true, "已经注销!!!");
}
@RequestMapping("delete/{id}")
public @ResponseBody MsgUtil delete(@PathVariable()String id) {
try {
//删除用户的同时删除他的用户角色表的数据
userService.deleteById(id);
userService.delete(id);
return MsgUtil.result(true, "删除成功!!");
} catch (Exception e) {
return MsgUtil.result(false, "系统繁忙请稍后再试!!!!!!!!!!");
}
}
角色管理
/**
* 跳转到添加
* @param map
* @return
*/
@RequestMapping("toadd")
public String toadd(ModelMap map) {
List<Admmb> id = roleService.orderById();
if(id!=null&&id.size()>0) {
String str = id.get(0).getId();
int j = Integer.valueOf(str.substring(0, str.length()))+1;
map.addAttribute("str",String.valueOf(j));
}else {
map.addAttribute("str","1");
}
return "sys_manager/role/add";
}
@RequestMapping("save")
public @ResponseBody MsgUtil save(Role admmb) {
try {
//设置创建时间
Date date = new Date();
admmb.setCreatetime(date);
roleService.save(admmb);
return MsgUtil.result(true, "添加成功");
} catch (Exception e) {
return MsgUtil.result(false, "系统繁忙,请稍后再试!!!");
}
}
@RequestMapping("toUpdate/{id}")
public String toUpdate(@PathVariable("id")String id,ModelMap map) {
Role role= roleService.selectById(id);
map.addAttribute("role", role);
return "sys_manager/role/edit";
}
@RequestMapping("update")
public @ResponseBody MsgUtil update(Role role) {
try {
roleService.update(role);
return MsgUtil.result(true, "修改成功!!");
} catch (Exception e) {
return MsgUtil.result(false, "修改失败!!");
}
}
//删除
@RequestMapping(value="delete",method=RequestMethod.DELETE)
public @ResponseBody MsgUtil delete(String[] id) {
try {
roleService.delete2(id);
return MsgUtil.result(true, "删除成功!!");
} catch (Exception e) {
return MsgUtil.result(false, "删除失败!!");
}
}
/**
* 查询资源树
* @return
*/
@RequestMapping(value="tree",method=RequestMethod.GET)
public @ResponseBody List<Resource> tree() {
return resourceService.findAll();//查询所有
}
/**
* 跳转到授权页面
*/
@RequestMapping("togrant/{id}")
public String togrant(@PathVariable("id")String id ,ModelMap map) {
//跳转到授权页面
List<RoleAndResource> resourceIds = roleService.selectById(id);
String resourceids="";
for (int i = 0; i < resourceIds.size(); i++) {
if(i<resourceIds.size()-1) {
resourceids+=resourceIds.get(i)+",";
}else {
resourceids+=resourceIds.get(i);
}
}
System.out.println(resourceids);
map.addAttribute("resourceids", resourceids);
map.addAttribute("roleId", id);
return "sys_manager/role/grant";
}
/**
* 实现授权
* @return
*/
@RequestMapping("grant")
public @ResponseBody MsgUtil grant(String roleId ,String rids) {
try {
System.out.println("rids="+rids);
roleService.deletById(roleId);//表示删除是成功的
List<Resource> list = new ArrayList<resource>();
if(rids!=null&&!rids.equalsIgnoreCase("")) {
//循环插入数据到角色表
for (String resourceId : rids.split(",")) {
RoleAndResource re= new RoleAndResource();
re.setId(roleId);re.setRid(roleId);re.setReid(resourceId);roleService.grant(re);}}return MsgUtil.result(true, "授权成功!!!!");} catch (Exception e){return MsgUtil.result(false, "授权失败!!!!!");}}
资源管理:
/**
* 查询出资源网格视图表
* @return
*/
@RequestMapping(value="select",method=RequestMethod.GET)
@ResponseBody
public BootstrapDataTable treeGrid(){
BootstrapDataTable treeGrid = resourceService.treeGrid();
return resourceService.treeGrid();
}
@RequestMapping(value="tree",method=RequestMethod.GET)
public @ResponseBody List<Resource> tree(){
System.out.println("是否到了tree里面");
return resourceService.findAll();
}
@RequestMapping("add")
public @ResponseBody MsgUtil add(Resource re) {
try {re.setState("0");
re.setSeq("0");
re.setCreatetime(new Date());
if(re.getPid().equals("")) {
re.setPid(null);
}
resourceService.save(re);
return MsgUtil.result(true, "添加成功");
} catch (Exception e) {
return MsgUtil.result(false, "添加失败");
}
}
/**
* 跳转到修改
*
*/
@RequestMapping("toUpdate/{id}")
public String toUpdate(@PathVariable String id,ModelMap map) {
Resource resource = resourceService.selectByMd001(id);
if(IsNotNullUtil.isNotNull(resource.getMd007())) {
resource.setpName(resourceService.selectByMd001(resource.getPid()).getName());
}
map.addAttribute("resource", resource);
return "sys_manager/resource/edit";
}
@RequestMapping("update")
public @ResponseBody MsgUtil update(Resource re) {
try {
if(re.getPid().equals("")) {
re.setPid(null);
}
re.setState("0");
resourceService.update(re);
return MsgUtil.result(true, "修改成功!!!");
} catch (Exception e) {
return MsgUtil.result(false, "修改失败!!!");
}
}
@RequestMapping(value="delete/{id}",method = RequestMethod.DELETE)
public @ResponseBody MsgUtil delete(@PathVariable String id) {
try {
resourceService.deletes(id);
return MsgUtil.result(true, "删除成功!!!!");
} catch (Exception e) {
return MsgUtil.result(false, "删除失败!!!!");
}
}
授权的树的js代码:
<script type="text/javascript">
//配置
var setting = {
view : {
dblClickExpand : true,
selectedMulti : true, //是否允许多选
txtSelectedEnable : true, //是否允许选中节点的文字
autoCancelSelected : true, //不允许按下Ctrl键取消节点选中状态
},
//复选框打开显示
check : {
enable : true
},
data : {
simpleData : {
enable : true
}
},
callback : {
onClick : onClick
}
};
//点击节点时
function onClick(e, treeId, treeNode) {
//获取树
var zTree = $.fn.zTree.getZTreeObj("role_grant_Tree");
//获取所有的节点
var nodes = zTree.getSelectedNodes(), v = "";
id = "";
nodes.sort(function compare(a, b) {
return a.id- b.id;
});
for (var i = 0, l = nodes.length; i < l; i++) {
v += nodes[i].name + ",";
id += nodes[i].id + ",";
}
if (id.length > 0)
id = id.substring(0, id.length - 1);
if (v.length > 0)
v = name.substring(0, v.length - 1);
return false;
}
//获得选中值
function fun_getCheckValue() {
var nodes = treeObj.getChangeCheckedNodes(true);
var result = '';
if (nodes.length == 0) {
layer.msg("请选择资源后,再提交!", {
time : 1500,
icon : 2
});
return false;
}
for (var i = 0; i < nodes.length; i++) {
var halfCheck = nodes[i].getCheckStatus();
result += nodes[i].id+ ',';
}
result = result.substring(0, result.lastIndexOf(","));
return result;
}
//tree对象
var treeObj;
//加载时发生
$(function() {
//获取数据
$.getJSON('roleController/tree.do', function(data) {
//初始化tree
$.fn.zTree.init($("#role_grant_Tree"), setting, data);
//先遍历各种节点
treeObj = $.fn.zTree.getZTreeObj("role_grant_Tree");
treeObj.checkAllNodes(false);
treeObj.expandAll(true);
var ids = $("#resourceids").val();
if (ids.trim() != "") {
var strs = ids.split(",");
for (var j = 0; j < strs.length; j++) {
var node = treeObj.getNodeByParam("md001",strs[j]);
//根据资源id选中节点
treeObj.checkNode(node, true);
}
}
});
//重置所有勾选
$("#reset").click(function() {
treeObj.checkAllNodes(false);
})
//全部选中节点
$("#selectNodes").click(function() {
treeObj.checkAllNodes(true);
});
});
//开始授权,首先获得选中的资源id,然后发送ajax请求.
function grant() {
//调用fun_getCheckValue()方法获得选中的所有id,返回是以逗号隔开的字符串id
var rids = fun_getCheckValue();
//请求修改角色
$.ajax({
type : "post",
url : "roleController/grant.do",
dataType : 'json',
data : {
"roleId" : $("#roleId").val(),
"rids" : rids
},
success : function(result) {
if (result.flag) {
layer.msg(result.msg, {
icon : 1,
time : 1000
});
setTimeout(referParent, 1000);
} else {
layer.msg(result.msg, {
icon : 2,
time : 1000
});
$.fn.zTree.getZTreeObj("role_grant_Tree")
.checkAllNodes(true);
}
}
});
}
</script>
逻辑总结:
角色表主要做的就是实现给角色授权,授权就是通过查询资源表的数据,获取资源id同时获取角色id添加到角色资源表中, 当然授权的同时要先删除角色资源表中对应的数据,添加角色的同时也是把角色id以及用户id添加到用户角色表中,这样查询的时候就可以通过联立表来查询这个用户对应的角色所拥有的资源,也就是权限。