[shiro学习笔记]使用eclipse/myeclipse搭建你的第一个shiro程序遇到问题解决

本文地址:http://blog.csdn.net/sushengmiyan/article/details/39519509

shiro官网: http://shiro.apache.org/

shiro中文手册:http://wenku.baidu.com/link?url=ZnnwOHFP20LTyX5ILKpd_P94hICe9Ga154KLj_3cCDXpJWhw5Evxt7sfr0B5QSZYXOKqG_FtHeD-RwQvI5ozyTBrMAalhH8nfxNzyoOW21K

本文作者:sushengmiyan

------------------------------------------------------------------------------------------------------------------------------------

  最近想做个简单的extjs5的登录跳转,之前做了一个,但是extjs又没有跳转链接,每次刷新都需要重新登录,实现的不好,现在想实现登录用户的认证,于是看到了shiro这个框架,看起来还是比较好用的,于是开始研究。

  刚开始搭建,发现官网给的hello world程序需要maven支持对pom文件研究又不深入,只能抛弃这种方式了。自己安装官方参考手册,下载了quickstart文件源码,但是这是maven文件,不会用,只能手动的新建了一个文件这样的,运行的时候报了好多错误,跑了好久,终于把hello world给运行出来了,现在分享一下可以运行的程序的创建的整个过程:

1.使用eclipse/myeclipse新建shirodemo工程

2.新建lib文件夹,将shiro-all-1.1.0.jar、slf4j-api-1.7.7.jar、slf4j-log4j12-1.7.7.jar、log4j-1.2.16.jar这些jar包添加进来。

3.build path---config build path将这些jar包添加到libraries中

4.新建自己的程序包,例如我新建com.susheng包,将quickstart中Quickstart.java中代码复制一份来。

5.添加shiro.ini和log4j.properties文件到src目录下。

6.运行程序:


程序正常运行。


之前遇到错误列表:

1.没有添加shiro.ini文件

错误信息:Exception in thread "main" org.apache.shiro.config.ConfigurationException: java.io.IOException: Resource [classpath:shiro.ini] could not be found.


原因是没有添加shiro.ini文件,解决方法,将shiro.ini放在src目录下即可解决。


2.没有正确添加self4j-log4j12.jar包

错误信息:SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".


self4j的包没有添加完成,这个问题真是弄得我好久都郁闷着。看实例代码,我引入slf4j-api-1.7.7.jar包之后,都可以正常些代码,没有错误提示了,但是居然这个jar包还依赖其他jar包才可以,这相当让我不舒服啊。引入其他self4j的jar包(slf4j-log4j12-1.7.7.jar)即可解决。


3.没有引入log4j的jar包

错误信息: java.lang.NoClassDefFoundError: org/apache/log4j/Level



4.没有log4j的配置文件

错误信息:log4j:WARN No appenders could be found for logger (org.apache.shiro.io.ResourceUtils).


添加log4j.properties到src目录下即可解决问题。

最终的程序目录结构如下:


代码都是shiro例子的,也粘贴一下吧。

package com.susheng;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple Quickstart application showing how to use Shiro‘s API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {
	private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
	public static void main(String[] args) {

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We‘ll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn‘t do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we‘ll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let‘s see what you can do:

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // let‘s login the current user so we can check against roles and permissions:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:weild")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to ‘drive‘ the winnebago with license plate (id) ‘eagle5‘.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren‘t allowed to drive the ‘eagle5‘ winnebago!");
        }

        //all done - log out!
        currentUser.logout();

        System.exit(0);
    }
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。