返回 登录
4

IDEA创建基于maven javaSE的shiro入门实例

Shiro入门实例源码下载
项目结构如下
图片描述
pom.xml文件

<!--?xml version="1.0" encoding="UTF-8"?-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelversion>4.0.0</modelversion><groupid>com.zhenqi.shiro</groupid><artifactid>ShiroEx</artifactid><version>1.0-SNAPSHOT</version><dependencies><dependency><groupid>org.apache.shiro</groupid><artifactid>shiro-core</artifactid><version>1.2.1</version></dependency><dependency><groupid>org.slf4j</groupid><artifactid>slf4j-log4j12</artifactid><version>1.7.2</version></dependency></dependencies></project>

HelloShiro.java文件如下

package com.zhenqi.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.*;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * Created by jo on 2017/3/28.
 */
public class HelloShiro {

    public static void main(String[] args){
        //读取配置文件  初始化factory
        Factory<securitymanager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager=factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject=SecurityUtils.getSubject();

        UsernamePasswordToken token=new UsernamePasswordToken("zhenqi","123456");

        try{
            subject.login(token);
            System.out.println("用户认证成功!");
        }catch(AuthenticationException e){
            System.out.println("认证失败!");
        }

    }
}

shiro.ini配置文件如下

[users]
zhenqi=123456
qicai=1234

log4j.properties文件如下

“`
log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

Pattern to output: date priority [category] - message

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

Spring logging level is WARN

log4j.logger.org.springframework=WARN

General Apache libraries is WARN

log4j.logger.org.apache=WARN

log4j.logger.net.sf.ehcache=WARN

log4j.logger.org.apache.shiro=TRACE
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
“`

评论