shiro入门案例项目结构:采用maven管理
pom文件
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
3 新建shiro.ini配置文件
[users]
sunny=1127
jack=123
package com.sun.shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* shiro入门案例
* @author suntan
* @dade 2017年3月3日下午6:59:58
* @version v1.0
*/
public class Demo1 {
/**
* 日志
*/
private Logger logger = LoggerFactory.getLogger(Demo1.class);
@Test
public void test1() {
//1.通过工厂对象加载配置文件
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2.通过工厂获取实例securityManager对象
SecurityManager securityManager = factory.getInstance();
//3.绑定对象
SecurityUtils.setSecurityManager(securityManager);
//4.获取token
Subject subject = SecurityUtils.getSubject();
//5根据用户名和密码登陆
UsernamePasswordToken token = new UsernamePasswordToken("sunny1", "1127");
try {
logger.info("========>执行登陆操作");
subject.login(token);
logger.info("========>登陆成功");
} catch (Exception e) {
logger.error("登陆失败:" + e);
}
//6.登出
subject.logout();
}
}