[Shiro Study notes] using Eclipse/myeclipse to build your first Shiro program encountered problem solving

Source: Internet
Author: User
Tags log4j

This address: http://blog.csdn.net/sushengmiyan/article/details/39519509

Shiro Official Website: http://shiro.apache.org/

Shiro Chinese Manual: Http://wenku.baidu.com/link?url=ZnnwOHFP20LTyX5ILKpd_P94hICe9Ga154KLj_ 3ccdxpjwhw5evxt7sfr0b5qszyxokqg_fthed-rwqvi5ozytbrmaalhh8nfxnzyoow21k

This article Sushengmiyan

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

Recently want to do a simple extjs5 login jump, before doing a, but ExtJS and no jump link, each refresh need to re-login, the implementation of the bad, now want to realize the authentication of the login user, so see the Shiro this framework, it seems to be more useful, so began to study.

Just started to build, found the official website to the Hello World program needs maven support for POM file research and not deep, can only abandon this way. Install their own official reference manual, download the QuickStart file source code, but this is Maven file, will not be used, can only manually create a new file such, run the time reported a lot of errors, ran a long, finally put Hello world to run out, Now share the entire process of creating a program that you can run:

1. New Shirodemo project using Eclipse/myeclipse

2. Create a new Lib folder, add Shiro-all-1.1.0.jar, Slf4j-api-1.7.7.jar, Slf4j-log4j12-1.7.7.jar, Log4j-1.2.16.jar these jar packages.

3.build Path---Config build path adds these jar packages to libraries

4. Create your own package, for example I create a new Com.susheng package and copy the code from Quickstart.java in QuickStart.

5. Add the Shiro.ini and log4j.properties files to the SRC directory.

6. Run the program:


The program runs correctly.


Before encountering the Error list:

1. shiro.ini file not added

Error message: Exception in thread "main" Org.apache.shiro.config.ConfigurationException:java.io.IOException:Resource [ Classpath:shiro.ini] could not being found.


The reason is that the Shiro.ini file is not added, the workaround is to put the Shiro.ini in the SRC directory can be resolved.


2. Self4j-log4j12.jar package not added correctly

Error message: slf4j:failed to load Class "Org.slf4j.impl.StaticLoggerBinder".


SELF4J's package has not been added to complete, this problem really made me depressed for a long time. Look at the instance code, I introduced the Slf4j-api-1.7.7.jar package, can be normal code, no error hint, but incredibly this jar is also dependent on other jar package can be, which makes me uncomfortable ah. The introduction of additional self4j jar packages (Slf4j-log4j12-1.7.7.jar) can be resolved.


3. No jar package with log4j introduced

Error message: Java.lang.noclassdeffounderror:org/apache/log4j/level



4. No log4j configuration file

Error message: Log4j:warn No appenders could is found for logger (org.apache.shiro.io.ResourceUtils).


Add log4j.properties to the SRC directory to resolve the issue.

The final program directory structure is as follows:


The code is Shiro example, also paste a bit of it.

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 ' s API. * * @since 0.9 RC2 */public class Quickstart {private static final transient Logger log = Loggerfactory.getlogger (quickst Art.class);p ublic static void Main (string[] args) {//The easiest-to-create a Shiro SecurityManager with Confi        Gured//Realms, users, roles and permissions are to use the Simple INI config.  We'll do the 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 the-example QuickStart, make the SecurityManager//accessible as a JVM singleton. Most applications wouldn ' t does this//and instead rely on their container configuration or Web. XML for//We  Bapps. That's outside the scope of this simple QuickStart, so//We'll just do the bare minimum so you can continue to GE        T a feel//for things.        Securityutils.setsecuritymanager (SecurityManager);        Now this a simple Shiro environment are set up and let's see how 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.isauthenti            cated ()) {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 () + "W As incorrect! ");} catch (Lockedaccountexception Lae) {Log.info ("The account for username" + token.getprincipal () + "is Loc  ked. "+" 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 is://print their identifying principal (in this case, a username): log.in        Fo ("User [" + currentuser.getprincipal () + "] logged in successfully.");        Test a role:if (Currentuser.hasrole ("Schwartz")) {Log.info ("May the Schwartz is with you!");        } else {log.info ("Hello, mere mortal.");            }//test a typed permission (not instance-level) if (currentuser.ispermitted ("Lightsaber:weild")) {  Log.info ("may use a lightsaber ring. Use it wisely. ");        else {log.info ("Sorry, lightsaber rings is for Schwartz Masters only."); }//a (very powerful) Instance level permission:if (currentuser.ispermitted ("Winnebago:drive:eagLe5 ")) {Log.info (" You is permitted to ' drive ', the Winnebago with license plate (ID) ' Eagle5 '. "+" Here is 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 Study notes] using Eclipse/myeclipse to build your first Shiro program encountered problem solving

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.