[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);
    }
}
时间: 2024-08-29 07:13:18

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

【知了堂学习笔记】Eclipse,Myeclipse连接MySQL数据库和Oracle数据库

一.连接MySQL数据库 1.由于Eclipse,Myeclipse都没有连接MySQL数据的架包,我们需要自行下载MySQL连接架包 mysql-connector(官方链接:http://dev.mysql.com/downloads/connector/j/5.0.html),下载版本最好是最新版. 2.下载好后,复制到你的项目里任何位置,然后右键架包选择 Build path -> add to Build path,然后点击项目的Libraries里的Referenced Librar

OpenCV学习笔记(一)安装及运行第一个OpenCV程序

1.下载及安装 OpenCV是一套开源免费的图形库,主要有C/C++语言编写,官网: http://opencv.org/ .在 http://opencv.org/downloads.html 可以找到个版本和各种平台的程序包.OpenCV的Windows平台安装包是放在SourceForge.net网站. 我下了2.4.4版,大概217M.安装包其实就是一个压缩包,安装过程就是解压到某个文件夹.我是安装到 E:\Soft\opencv 目录,安装后文件夹如下: 我们只需要关注“build”文

Cocos2dx 学习笔记整理----开发环境搭建

最近在学习cocos2dx,预备将学习过程整理成笔记. 需要的工具和环境整理一下: 使用的版本 cocos2dx目前已经出到了v3.1.1,学习和项目的话还是用2.2.3为宜,毕竟不大想做小白鼠,并且学习了几天之后才发出3.X版本的,版本内容变动比较大. 开发环境 1 jdk 1.6以上 2 python 2.7为宜(创建项目要用的) 3 NDT+Android SDK 4 Cygwin或者MinGW 开发工具 1 Eclipse + CDT + ADT 2 VS2010 3 Sublime T

shiro学习笔记_0600_自定义realm实现授权

博客shiro学习笔记_0400_自定义Realm实现身份认证 介绍了认证,这里介绍授权. 1,仅仅通过配置文件来指定权限不够灵活且不方便.在实际的应用中大多数情况下都是将用户信息,角色信息,权限信息 保存到了数据库中.所以需要从数据库中去获取相关的数据信息.可以使用 shiro 提供的JdbcRealm来实现,,也可以自定义realm来实现.使用jdbcRealm往往也不够灵活.所以在实际应用中大多数情况都是自定义Realm来实现. 2,自定义Realm 需要继承 AuthorizingRea

Apache Shiro学习笔记(六)FilterChain

鲁春利的工作笔记,好记性不如烂笔头 Apache Shiro学习笔记(七)IniWebEnvironment

Hadoop学习笔记(3)——分布式环境搭建

Hadoop学习笔记(3) ——分布式环境搭建 前面,我们已经在单机上把Hadoop运行起来了,但我们知道Hadoop支持分布式的,而它的优点就是在分布上突出的,所以我们得搭个环境模拟一下. 在这里,我们采用这样的策略来模拟环境,我们使用3台ubuntu机器,1台为作主机(master),另外2台作为从机(slaver).同时,这台主机,我们就用第一章中搭建好的环境来. 我们采用与第一章中相似的步骤来操作: 运行环境搭建 在前面,我们知道,运行hadoop是在linux上运行的.所以我们单机就在

Shiro学习笔记(5)——web集成

Web集成 shiro配置文件shiroini 界面 webxml最关键 Servlet 測试 基于 Basic 的拦截器身份验证 Web集成 大多数情况.web项目都会集成spring.shiro在普通web项目和spring项目中的配置是不一样的.关于spring-shiro集成,能够參考Shiro学习笔记(3)--授权(Authorization) 中的JSP标签授权部分演示样例代码 本次介绍普通的web项目,不使用不论什么框架. shiro配置文件(shiro.ini) 创建web项目.

NodeJS学习笔记(一)——搭建开发框架Express,实现Web网站登录验证

JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需要独立运行的JS,NodeJS就是一个解析器.每一种解析器都是一个运行环境,不但允许JS定义各种数据结构,进行各种计算,还允许JS使用运行环境提供的内置对象和方法做一些事情.例如运行在浏览器中的JS的用途是操作DOM,浏览器就提供了document之类的内置对象.而运行在NodeJS中的JS的用途是操作磁盘文件或搭建HTTP服务器,NodeJS就相应提供了fs.http等内置对象.E

Shiro 学习笔记(一)——shiro简介

Apache Shiro 是一个安全框架.说白了,就是进行一下 权限校验,判断下这个用户是否登录了,是否有权限去做这件事情. Shiro 可以帮助我们完成:认证.授权.加密.会话管理.与web 集成.缓存等. 其基本功能点 如下图: Authentication  : 身份认证/登录,验证用户是不是拥有相应的身份 Authorization : 授权,即权限验证,验证某个已认证的用户是否拥有某个权限:即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色,或者 细粒度的验证某个用户对某个