登录与角色
一. 密码加密
我们现在数据库中的密码还没有加密,现在做个统一加密。
1.1 MD5Utils工具类
public class MD5Utils {
/**
* 加密工具
*/
public static final String ALGORITHMNAME = "MD5";
public static final String SALT ="itsource";
public static final int HASHITERATIONS =10;
//密码加密后返回
public static String createPwd(String password){
SimpleHash hash = new SimpleHash(ALGORITHMNAME,password,SALT,HASHITERATIONS);
return hash.toString();
}
}
1.2 测试修改
@Test
public void testUpdatePwd() throws Exception{
//拿到所有数据
List<Employee> employeeList = employeeService.findAll();
//遍历,修改密码
employeeList.forEach(e->{
//拿到用户名
String username = e.getUsername();
e.setPassword(MD5Util.createMd5Str(username));
employeeService.save(e);
});
}
1.3 添加数据时密码加密
EmployeeServiceImpl 中重写save()方法
@Override
public void save(Employee employee) {
//添加的时候才进行密码加密
if(employee.getId()==null){
employee.setPassword(MD5Utils.createPwd(employee.getPassword()));
}
super.save(employee);
}
二. 登录功能
2.1 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>login</title>
<link rel="stylesheet" type="text/css" href="/login/css/normalize.css" />
<link rel="stylesheet" type="text/css" href="/login/css/demo.css" />
<!--必要样式-->
<link rel="stylesheet" type="text/css" href="/login/css/component.css" />
<!--[if IE]>
<script src="/js/html5.js"></script>
<![endif]-->
<script type="text/javascript" src="/login/js/jquery-1.11.2.js"></script>
<script type="text/javascript">
function submitForm() {
var username = $("#username").val();
var password = $("#password").val();
$.post("/login",{username: username,password:password},function (result) {
console.debug("请求成功")
if (result.success){
console.debug("success")
window.location.href = "main";
}else{
alert("登录失败");
}
})
//回车登录
$(document).keyup(function(event) {
var keyCode = event.keyCode;
console.debug("keyCode"+keyCode);
if (keyCode === 13) { // 捕获回车
submitForm(); // 提交表单
}
});
}
</script>
</head>
<body>
<div class="container demo-1">
<div class="content">
<div id="large-header" class="large-header">
<canvas id="demo-canvas"></canvas>
<div class="logo_box">
<h3>请登录</h3>
<form action="/login" name="f" method="post">
<div class="input_outer">
<span class="u_user"></span>
<input id="username" name="username" class="text" style="color: #FFFFFF !important" type="text" placeholder="请输入账户">
</div>
<div class="input_outer">
<span class="us_uer"></span>
<input id="password" name="password" class="text" style="color: #FFFFFF !important; position:absolute; z-index:100;"value="" type="password" placeholder="请输入密码">
</div>
<div class="mb2"><a class="act-but submit" href="javascript:;" style="color: #FFFFFF" onclick="submitForm();">登录</a></div>
</form>
</div>
</div>
</div>
</div><!-- /container -->
<script src="/login/js/TweenLite.min.js"></script>
<script src="/login/js/EasePack.min.js"></script>
<script src="/login/js/rAF.js"></script>
<script src="/login/js/demo-1.js"></script>
</body>
</html>
2.2 后台登录支持
1) 根据get与post不同的请求访问不同的方法(RESTful风格)
2) @ResponseBody 返回json格式数据
@Controller
public class LoginController {
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String index(){
return "login";
}
@RequestMapping(value = "/login",method = RequestMethod.POST)
@ResponseBody
public JsonResult index(String username,String password){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
try {
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
subject.login(token);
} catch (UnknownAccountException e) {
System.out.println("账号不存在!!!");
e.printStackTrace();
return new JsonResult(false,"账号不存在");
} catch (IncorrectCredentialsException e) {
System.out.println("用户名或密码错误!!!");
e.printStackTrace();
return new JsonResult(false,"用户名或密码错误!!!");
} catch (AuthenticationException e) {
System.out.println("未知错误!!!");
e.printStackTrace();
return new JsonResult(false,"未知错误");
}
return new JsonResult();
}
@RequestMapping("/loginout")
public String loginout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/s/login.jsp";
}
}
三. 角色与权限
3.1 Role 角色
配置多对多关系
@Entity
@Table(name = "role")
public class Role extends BaseDomain{
private String name;
private String sn;
@ManyToMany
@JoinTable(name = "role_permission",joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "permission_id"))
private List<Permission> permissions = new ArrayList<>();
......set get方法...
}
3.2 Permission权限
@Entity
@Table(name = "permission")
public class Permission extends BaseDomain{
private String name;
private String url;
private String descs;
private String sn;
private Long menu_id;
...
set get 方法
...
3.3 用户
配置多对多关系
@Entity
@Table(name = "employee")
public class Employee extends BaseDomain {
.....
@ManyToMany
@JoinTable(name = "employee_role",joinColumns = @JoinColumn(name = "employee_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles = new ArrayList<>();
......
set get方法
四. 角色权限crud
4.1 权限显示
权限是List集合,所以加上formatter来转换一下
<th data-options="field:'permissions',width:100,formatter:permsFormat">权限</th>
js
//权限数据显示
function permsFormat(v){
var ps ="";
for(var p of v){
ps += p.name+" ";
}
return ps;
}
4.2 添加和修改权限双击事件
添加和修改时用了数据表格
rolePermsGrid是当前角色拥有的权限
allPermsGrid是所有权限
双击allPermsGrid中的一行添加数据到rolePermsGrid
如果rolePermsGrid中有这个数据了,就不在重复添加
双击rolePermsGrid中的一行,删除数据
//添加修改grid
//当前角色拥有的权限
rolePermsGrid.datagrid({
fitColumns:true,
singleSelect:true,
fit:true,
onDblClickRow:crudMethod.removePerms
})
//index:当前行,当前行数据
addPerms(index,row){
//获取当前角色权限行数据
var rows = rolePermsGrid.datagrid("getRows");
//遍历所有行数据,判断有没有重复的
for(var r of rows){
if(r.id == row.id){
$.messager.show({
title:'错误',
msg:'<h2 style="color: red;">数据已经存在,请不要重复选择</h2>',
showType:'slide',
style:{
right:'',
top:document.body.scrollTop+document.documentElement.scrollTop,
bottom:''
}
});
return;
}
}
//把相应的数据追加进去
rolePermsGrid.datagrid("appendRow",row);
}
所有权限
//所有权限
allPermsGrid.datagrid({
url:'/permission/list',
fitColumns:true,
singleSelect:true,
fit:true,
//双击添加事件
onDblClickRow:crudMethod.addPerms
})
//删除权限数据
removePerms(index,row){
rolePermsGrid.datagrid("deleteRow",index);
}
4.3 添加是清空数据
datagrid是用来装的,所以我们放一个空数组
//清空datagrid中的数据
rolePermsGrid.datagrid("loadData",[]);
4.4 修改时回显数据
复制一份后给grid,不让他们是同一个数据
//回显权限,复制一份
var perms = [...row.permissions];
rolePermsGrid.datagrid("loadData",perms);
4.5 提交权限时参数格式
提交额外数据
需要的是 permission.id=id 的格式
onSubmit: function(param){
//添加权限
//获取所有行
var rows = rolePermsGrid.datagrid("getRows");
//遍历,拼接格式 后台需要的格式:permissions[0].id = 1
for(var i=0;i<rows.length;i++){
var p = rows[i];
param[`permissions[${i}].id`] = p.id;
}
//验证
return $(this).form('validate');
}