使用静态shiro.ini文件完成认证
创建项目到爆
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.1</version> </dependency> <!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding in this example app. See http://www.slf4j.org for more info. --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.21</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.21</version> <scope>test</scope> </dependency>
核心的shiro和log4j依赖
顺便创建log4j文件
创建shiro.ini
import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; public class TestAuthenticationApp { //日志输出工具 private static final transient Logger log = LoggerFactory.getLogger(TestAuthenticationApp.class); public static void main(String[] args) { String username = "zhangsan"; String password = "123456"; log.info("My First Apache Shiro Application"); //1 创建安全管理器的工厂对象 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //2 使用工厂创建安全管理器 SecurityManager securityManager = factory.getInstance(); //3 把当前的安全管理器绑定到线程 SecurityUtils.setSecurityManager(securityManager); //4 使用SecurityUtils.getSubject() 得到主体 Subject currentUser = SecurityUtils.getSubject(); //5 封装用户名 AuthenticationToken arg0 = new UsernamePasswordToken(username, password); currentUser.login(arg0); System.out.println("认证通过"); } }
当用户名或者密码不正确时,会抛出相应的异常
使用cry cateh 抛出相应的中文提示即可