[shiro學習筆記]使用eclipse/myeclipse搭建你的第一個shiro程式遇到問題解決

來源:互聯網
上載者:User

標籤:apache shiro   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);    }}



[shiro學習筆記]使用eclipse/myeclipse搭建你的第一個shiro程式遇到問題解決

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.