本文主要是介绍Shiro HelloWorld,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Maven工程结构图如下:
pom.xml中依赖如下:
<span style="white-space:pre"> </span><dependencies><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.4</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.13</version></dependency></dependencies>
log4j.properties
log4j.rootLogger=INFO, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n# General Apache libraries
log4j.logger.org.apache=WARN# Default Shiro logging
log4j.logger.org.apache.shiro=TRACE# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro.ini
[users]
zhang=1234
wang=123
HelloWorld.java
package com.trekiz.shiro;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
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;public class HelloWorld {public static void main(String[] args) {//获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");//获得SecurityManager实例SecurityManager securityManager =factory.getInstance();//绑定给SecurityUtils SecurityUtils.setSecurityManager(securityManager);//得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证) Subject currentUser = SecurityUtils.getSubject();UsernamePasswordToken token = new UsernamePasswordToken("zhang", "1234");try{currentUser.login(token);System.out.println("Succeed!");}catch(AuthenticationException e){e.printStackTrace();System.out.println("fail");}currentUser.logout();}}
运行即可
这篇关于Shiro HelloWorld的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!