1 用户和角色和资源的绑定问题
1.1 用户绑定角色
1. 1. 1 页面
$("#bindResBtn").click(function(){
var rows = $("#list").datagrid("getSelections");
if(rows.length!=1){
$.messager.alert("提示","只能绑定一个角色","warning");
return;
}
var content = "";
$("#bindResWin").window({
content:content
});
$("#bindResWin").window("open");
});
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>角色管理title>
<script type="text/javascript" src="../../js/easyui/jquery.min.js">script>
<link rel="stylesheet" type="text/css" href="../../js/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../js/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../../css/default.css">
<script type="text/javascript" src="../../js/easyui/jquery.easyui.min.js">script>
<script type="text/javascript" src="../../js/easyui/locale/easyui-lang-zh_CN.js">script>
<script type="text/javascript" src="../../js/form.js">script>
head>
<body>
<table id="list">table>
<div id="toolbar">
<a id="bindRoleBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'">绑定a>
div>
<script type="text/javascript">
var action = "role";
var columns = [ [ {
field : "id",
checkbox : true
}, {
field : "name",
title : "角色名",
width : 120,
align : "center"
}, {
field : "keyword",
title : "角色关键字",
width : 120,
align : "center"
}, {
field : "description",
title : "备注",
width : 120,
align : "center"
} ] ];
$("#list").datagrid({
url:"../../"+action+"/listByPage.action",
columns:columns,
pagination:true,
toolbar:"#toolbar"
});
$("#bindRoleBtn").click(function(){
var userId = "${param.userId}";
var rows = $("#list").datagrid("getSelections");
var roleIdArray=new Array();
$(rows).each(function(i){
roleIdArray.push(rows[i].id);
});
var roleIds = roleIdArray.join(",");
$.post("../../user/bindRoleToUser.action",{userId:userId,roleIds:roleIds},function(data){
if(data.success){
window.parent.$.messager.alert("提示","用户绑定角色成功","info");
window.parent.$("#bindRoleWin").window("close");
}else{
$.messager.alert("提示","用户绑定角色失败"+data.msg,"error");
}
},"json");
});
script>
body>
html>
1. 1. 2 Action
private String validCode;
pubulic String getValidCode(){
return validCode;
}
public void setValidCode(String validCode ){
this.validCode=validCode;
}
@Action("login")
public void login(){
User user = this.getModel();
String key= ActionContext.getContext.getSession.get0("key");
if(! key.equals(validCode)){
result.put("success",false);
result.put("msg","验证码有误");
}else {
try{
User loginUser = userService.login(user);
result.put("success",true);
ActionContext.getContext.getSession.put("user",loginUser);
} catch (UnknownUserException e){
result.put("success",false);
result.put("msg","用户名不存在");
}catch ( IncorrectPasswordException e){
result.put("success",false);
result.put("msg","密码错误");
}catch (Exception e){
result.put("success",false);
result.put("msg",e.getMessage);
}
}
writeJson(result);
}
1. 1. 3 Service
1. 1. 3. 1接口
USer login(User user)throws UnknownUserException, IncorrectPasswException;
1. 1. 3. 2 service实现类
@Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Override
public void bindRoleToUser(Long userId, String roleIds) {
User user =userDao.findOne(userId);
Setroles =new HashSet();
if(StringUtils.isNoneBlank(roleIds)) {
String[] roleIdArray =roleIds.split(",");
for (String roleId : roleIdArray) {
roles.add( roleDao.findOne(Long.parseLong(roleId)) );
}
}
user.setRoles(roles);
}
1. 2 回显绑定过用户的角色列表
1. 2. 1 修改Role实体类
@Transient
private Boolean checked=false;
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
1. 2. 2 修改 bindRole.jsp
$("#list").datagrid({
url:"../../"+action+"/listByPageAndChecked.action?userId=${param.userId}",
columns:columns,
pagination:true,
toolbar:"#toolbar"
});
1. 2. 3 RoleAction
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 角色列表,带回显功能
* @throws IOException
*/
@Action("listByPageAndChecked")
public void listByPageAndChecked() throws Exception {
Pageable pageable = new PageRequest(this.getPage() - 1, this.getRows());
Specification spec = buildSpecification();
Page pageBean = roleService.findAll(spec, pageable,Long.parseLong(userId));
List content = pageBean.getContent();
long total = pageBean.getTotalElements();
result.put("total", total);
result.put("rows", content);
writeJson(result);
}
1. 2. 4 角色业务层
1. 2. 4. 1 RoleService
Page findAll(Specification spec, Pageable pageable, Long userId);
1. 2. 4. 2 RoleServiceImpl
@Override
public Page findAll(Specification spec, Pageable pageable, Long roleId) {
PagePageBean = roleDao.findAll(spec,pageable);
User user = userDao.findOne(roleId);
Set roles = user.getRoles();
SetroleIdSet = new HashSet();
for (Role role : roles) {
roleIdSet.add(role.getId());
System.out.println(role);
}
for(Role role :PageBean) {
role.setChecked(roleIdSet.contains( role.getId() ));
}
return PageBean;
}
- 当绑定角色时,回显的是整行变色的,是以整行变色为基准的,不是以每行前面的√为基准,所有要修复页面以√为基准.
1. 2. 5 修复页面
$("#list").datagrid({
url:"../../"+action+"/listByPageAndChecked.action?userId=${param.userId}",
columns:columns,
pagination:true,
toolbar:"#toolbar",
onLoadSuccess:function(data){
$(data.rows).each(function(i){
if(data.rows[i].checked){
$("#list").datagrid("selectRow",i);
}
});
}
});
1. 3 修复修改用户,角色,资源时丢失中间表数据
- 原因:修改User对象时,在表单没有回传Role相关的数据,导致User对象的role为 null,在 hibernate最终保存用户的时候,把中间表的关联数据清空了.
- 解决方案:
1. 3. 1 UserServiceImpl重写save方法
/**
* 修复修改用户和角色时中间表数据丢失问题
* 重写save方法
*/
@Override
public void save(User model) {
if(model.getId() != 0) {
User dBUser =userDao.findOne(model.getId());
model.setRoles(dBUser.getRoles());
}
super.save(model);
}
1. 3. 2 RoleServiceImpl 重写save()方法
/**
* 修复修改角色对象和资源对象时中间表数据丢失问题
* 重写save()方法
*/
@Override
public void save(Role model) {
if(model.getId() != 0) {
Role dbRole =roleDao.findOne(model.getId());
model.setResources(dbRole.getResources());
}
super.save(model);
}
2 用户登录
2. 1 用户登录
2. 1 .1 jsp页面
$(function(){
$("#loginBtn").click(function(){
$.post("user/login.action",$("#loginform").serialize(),function(data){
if(data.success){
window.location.href="index.jsp";
}else {
alert("登录失败:"+data.msg);
}
},"json");
});
});
2. 1. 2 Action
/**
* 用户登录
* @throws IOException
*/
@Action("login")
public void login() throws IOException {
String key=(String)ActionContext.getContext().getSession().get("key");
if(! key.equals(validCode)) {
result.put("success", false);
result.put("msg", "验证码输入有误");
writeJson(result);
return ;
}
try {
User user =userService.login(this.getModel());
ActionContext.getContext().getSession().put("user", user);
result.put("success", true);
} catch (NoneUsernameException e) {
result.put("success", false);
result.put("msg","用户不存在");
}catch (ErrorPasswordException e) {
result.put("success", false);
result.put("msg","密码错误");
}catch (Exception e) {
e.printStackTrace();
result.put("success", false);
result.put("msg",e.getMessage());
}finally {
writeJson(result);
}
}
2. 1. 3 业务层
User login(User model) throws NoneUsernameException, ErrorPasswordException;
@Override
public User login(User model) throws NoneUsernameException, ErrorPasswordException {
User user = userDao.findByUsername(model.getUsername());
if(user == null) {
throw new NoneUsernameException();
}
if(! model.getPassword().equals(user.getPassword())) {
throw new ErrorPasswordException();
}
return user;
}
2. 1. 4 持久层
User findByUsername(String username);
2. 1. 5 修改显示页面
<div id="sessionInfoDiv" style="position: absolute;right: 5px;top:10px;">
[<strong>${user.nickname}strong>],欢迎你!您使用[<strong><%=request.getRemoteHost() %>strong>]IP登录!
div>
window.setTimeout(function(){
$.messager.show({
title:"消息提示",
msg:'欢迎登录,${user.nickname}! " onclick="top.showAbout();">联系管理员',
timeout:5000
});
},3000);
2. 2 根据登录用户绑定的角色展示动态菜单
2. 2. 1 index.jsp页面
$.post("user/findMyMenu.action",function(data){
$.fn.zTree.init($("#menuTree"), setting, data);
},"json");
2. 2. 3 控制层
/**
* 加载页面时,加载对应用户的菜单
* @throws IOException
*/
@Action("findMyMenu")
public void findMyMenu() throws IOException{
User loginUser = (User)ActionContext.getContext().getSession().get("user");
if(loginUser != null) {
ListmenuList =userService.findMyMenu(loginUser.getId());
removeDuplicateWithOrder(menuList);
writeJson(menuList);
}
}
2. 2. 4 业务层
List findMyMenu(long id);
/**
* 获取登录用户的资源列表
*/
@Override
public List findMyMenu(long userId) {
Listlists =userDao.findById(userId);
return lists;
}
2. 2. 5 持久层
@Query("select res from User user "
+ "inner join user.roles role "
+ "inner join role.resources res "
+ "where user.id =? and res.resourceType='0'")
List findById(long userId);
- 当业务写完后启动项目后,我们发现显示不出资源菜单列表
2. 2. 6 修复显示不出资源菜单问题
- 原因:前端jsp页面显示的id为pid,而后台输入的id为”_parentId”
- 解决方案
var setting = {
data:{
simpleData:{
enable:true,
pIdKey:"_parentId "
}
},
callback:{
onClick:clickTree
}
};