Shiro学习
01 helloworld
Shiro官网:
shiro.apache.org/introduction.html
怎么学习:
查看doc
使用maven管理jar包
1:创建maven项目
New时候创建maven项目
2:在创建好的maven项目中添加需要的jar包
2.1:可以访问
http://mvnrepository.com/
这个网站查询想要的jar
2.2 添加shiro核心jar包
注意:在pom.xml文件中添加依赖的时候先要添加:
<dependencies>
</dependencies>
<dependencies> <!-- shiro核心包 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.4</version> </dependency> <!-- 添加slf4j实现类 以防止只添加slf4j-api儿提示警告 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.18</version> </dependency> </dependencies> |
3:创建shiro.ini配置文件
在配置文件中设置用户名密码:
[users] kaigejava=123456 joo=123 |
4:创建java类
步骤:
1使用工厂来类获取到配置文件中信息,初始化工厂类
代码:
//1:创建工厂类获取配置信息 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); |
2 使用工厂获取到实例
代码:
//2:获取工厂实例 SecurityManager securityManager = factory.getInstance(); |
3 把实例绑定到utils中
代码:
//3:将工厂实例对象绑定到securityUtils对象中。方便使用 SecurityUtils.setSecurityManager(securityManager); |
4 通过utils获取到当前用户
代码:
// 4: 通过utils类获取到subject 即使当前用户对象 Subject curtUser = SecurityUtils.getSubject(); |
5 使用最简单的认证方式。创建token使用的是用户名密码
代码:
//5:通过用户名密码获取认证需要的token UsernamePasswordToken token = new UsernamePasswordToken("kaigejava", "123456"); |
6 执行登录。身份认证
异常:
代码:
//6 通过当前用户对象根据获取到的token进行登录 try { currUser.login(token); System.out.println("登录成功!"); } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("登录异常!"); } |
7 退出登录
登录成功:
使用错误的密码提示登录失败。
注意:如果想看日志详情。请添加log4j.properties
总结:
创建步骤
1 创建工厂类获取指定位置的配置文件
2 由工厂类获取到实例
3 将实例绑定到工具类中
4 通过工具类获取到对象
5 通过认证方式获取token
6 由4的对象登录token
7 退出登录