今天了一节讲shiro的视频 先记这
先建个java工程 再建个lib文件夹 把暂时需要的4个jar包粘上去再build path
下载jar包链接
https://download.csdn.net/download/qq_35653822/10916400
工程目录结构如下图
之前我用其他的jar运行报错 可能因为版本不对
工程就是仿照shiro的开源代码做的 shiro.ini log4j.properties都是直接粘过来的 然后Quickstart是粘过来改的 但是开源代码下载地址我没找到 这是我的工程的下载地址
https://download.csdn.net/download/qq_35653822/10916415
然后ini文件平时我都不看的也没研究过打开方式 右键 打开方式text文件
shiro中 subject相当于当前用户 securitymanager管理所有用户 realm相当于dao层
然后粘一些常用的代码
// 获取当前用户 shiro中subject就相当于当前用户
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//通过subject的getsession方法获取session
Session session = currentUser.getSession();
//调用subject的isAuthenticated方法 测试当前用户是否登录
if (!currentUser.isAuthenticated()) {
//把用户名密码封装为对象
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
// rememberme
token.setRememberMe(true);
try {
//调用subject的login方法执行登录
//在没有数据库的情况下 会和shiro.ini进行对比 找[users]有没有lonestarr=vespa
currentUser.login(token);
}
catch (UnknownAccountException uae) {//没有这个用户名时 抛这个异常 UnknownAccountException
log.info("----> There is no user with username of " + token.getPrincipal());
return;
}
catch (IncorrectCredentialsException ice) {//密码错误时抛IncorrectCredentialsException
log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
return;
}
catch (LockedAccountException lae) {//用户被锁定时抛这个异常 LockedAccountException
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
//相当于shiro中的exception 其他异常的爸
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//调用subject的hasrole方法 查是否有这个角色权限
if (currentUser.hasRole("schwartz")) {
log.info("----> May the Schwartz be with you!");
} else {
log.info("----> Hello, mere mortal.");
return;
}
//test a typed permission (not instance-level)
//在没配置数据库时 在shiro.ini中找[roles]
//是否具备某个行为
if (currentUser.isPermitted("lightsaber:weild")) {
log.info("----> You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//退出登录
currentUser.logout();