博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hello Shiro
阅读量:7238 次
发布时间:2019-06-29

本文共 6778 字,大约阅读时间需要 22 分钟。

【HelloWorld Shiro】

1.搭建开发环境-加入jar包

 

2.步骤(前提:已下载好Shiro资源包):

①找到shiro-root-1.2.3-source-release包,

 

②按Apache Shiro\shiro-root-1.2.3-source-release\shiro-root-1.2.3\samples\quickstart\src\main\resources路径找到,将log4j.properties,shiro.ini文件加入到类路径(src)下,

 

③创建一个包,将Apache Shiro\shiro-root-1.2.3-source-release\shiro-root-1.2.3\samples\quickstart\src\main\java下的Quickstart.java文件放入包中。(注意:在该java代码中要添加包名代码)

 

3.运行结果:一大堆东西

 

附:

 

Quickstart.java:

1 package com.hk.shiro.hello;  2   3 /*  4  * Licensed to the Apache Software Foundation (ASF) under one  5  * or more contributor license agreements.  See the NOTICE file  6  * distributed with this work for additional information  7  * regarding copyright ownership.  The ASF licenses this file  8  * to you under the Apache License, Version 2.0 (the  9  * "License"); you may not use this file except in compliance 10  * with the License.  You may obtain a copy of the License at 11  * 12  *     http://www.apache.org/licenses/LICENSE-2.0 13  * 14  * Unless required by applicable law or agreed to in writing, 15  * software distributed under the License is distributed on an 16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17  * KIND, either express or implied.  See the License for the 18  * specific language governing permissions and limitations 19  * under the License. 20  */ 21  22 import org.apache.shiro.SecurityUtils; 23 import org.apache.shiro.authc.*; 24 import org.apache.shiro.config.IniSecurityManagerFactory; 25 import org.apache.shiro.mgt.SecurityManager; 26 import org.apache.shiro.session.Session; 27 import org.apache.shiro.subject.Subject; 28 import org.apache.shiro.util.Factory; 29 import org.slf4j.Logger; 30 import org.slf4j.LoggerFactory; 31  32  33 /** 34  * Simple Quickstart application showing how to use Shiro's API. 35  * 这是一个简单地快速开始,来演示怎么用Shiro 的API。 36  * @since 0.9 RC2 37  */ 38 public class Quickstart { 39  40     private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); 41  42     public static void main(String[] args) { 43  44         // The easiest way to create a Shiro SecurityManager with configured 45         // realms, users, roles and permissions is to use the simple INI config. 46         // We'll do that by using a factory that can ingest a .ini file and 47         // return a SecurityManager instance: 48  49         // Use the shiro.ini file at the root of the classpath 50         // (file: and url: prefixes load from files and urls respectively): 51         Factory
factory = new IniSecurityManagerFactory("classpath:shiro.ini"); 52 SecurityManager securityManager = factory.getInstance(); 53 54 // for this simple example quickstart, make the SecurityManager 55 // accessible as a JVM singleton. Most applications wouldn't do this 56 // and instead rely on their container configuration or web.xml for 57 // webapps. That is outside the scope of this simple quickstart, so 58 // we'll just do the bare minimum so you can continue to get a feel 59 // for things. 60 SecurityUtils.setSecurityManager(securityManager); 61 62 // Now that a simple Shiro environment is set up, let's see what you can do: 63 64 // get the currently executing user: 65 //获取当前的subject,调用SecurityUtils.getSubject() 66 Subject currentUser = SecurityUtils.getSubject(); 67 68 // Do some stuff with a Session (no need for a web or EJB container!!!) 69 //测试使用session 70 //获取Session,调用subject的getSession()方法 71 Session session = currentUser.getSession(); 72 session.setAttribute("someKey", "aValue"); 73 String value = (String) session.getAttribute("someKey"); 74 if (value.equals("aValue")) { 75 log.info("Retrieved the correct value! [" + value + "]"); 76 } 77 78 // let's login the current user so we can check against roles and permissions: 79 //测试当前的用户是否已经被认证,即是否登录 80 //调用subject的isAuthenticated() 81 if (!currentUser.isAuthenticated()) { 82 //把用户名和密码封装成UsernamePasswordToken对象 83 UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); 84 //rememberme 85 token.setRememberMe(true); 86 try { 87 //执行登录 88 currentUser.login(token); 89 //若没有指定账户,Shiro则抛出UnknownAccountException异常 90 } catch (UnknownAccountException uae) { 91 log.info("There is no user with username of " + token.getPrincipal()); 92 //若账户存在,密码不匹配,则Shiro抛出IncorrectCredentialsException 93 } catch (IncorrectCredentialsException ice) { 94 log.info("Password for account " + token.getPrincipal() + " was incorrect!"); 95 //用户被锁定的异常 96 } catch (LockedAccountException lae) { 97 log.info("The account for username " + token.getPrincipal() + " is locked. " + 98 "Please contact your administrator to unlock it."); 99 }100 // ... catch more exceptions here (maybe custom ones specific to your application?101 //所有认证时异常的父类102 catch (AuthenticationException ae) {103 //unexpected condition? error?104 }105 }106 107 //say who they are:108 //print their identifying principal (in this case, a username):109 log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");110 111 //test a role:112 //测试是否有某一个角色,调用subject的hasRole方法113 if (currentUser.hasRole("schwartz")) {114 log.info("May the Schwartz be with you!");115 } else {116 log.info("Hello, mere mortal.");117 }118 119 //test a typed permission (not instance-level)120 //测试用户是否具备某一个行为121 if (currentUser.isPermitted("lightsaber:weild")) {122 log.info("You may use a lightsaber ring. Use it wisely.");123 } else {124 log.info("Sorry, lightsaber rings are for schwartz masters only.");125 }126 127 //a (very powerful) Instance Level permission:128 if (currentUser.isPermitted("winnebago:drive:eagle5")) {129 log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +130 "Here are the keys - have fun!");131 } else {132 log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");133 }134 135 //all done - log out!136 //执行登出,调用subject的logout()方法137 currentUser.logout();138 139 System.exit(0);140 }141 }

 

转载于:https://www.cnblogs.com/zhzcode/p/9673522.html

你可能感兴趣的文章
PHP——0126最初
查看>>
求最小的k个数
查看>>
Sequence operation(线段树区间多种操作)
查看>>
怎样解决Ubuntu发热严重地问题
查看>>
申请付费苹果开发者账号 注意事项及流程 (转)
查看>>
ThinkPHP 3.2.3 数据缓存与静态缓存
查看>>
2-7-集合运算(A-B)∪(B-A)-线性表-第2章-《数据结构》课本源码-严蔚敏吴伟民版
查看>>
Linux中设置服务自启动的三种方式
查看>>
友盟新功能介绍:在线参数-备用
查看>>
RAC object remastering ( Dynamic remastering )
查看>>
Log4net使用(一)
查看>>
[Android][Android Studio] *.jar 与 *.aar 的生成与*.aar导入项目方法
查看>>
PopUpWindow使用详解(二)——进阶及答疑
查看>>
史上最完整的Android开发工具集合
查看>>
Pythonn new-style class and old-style class
查看>>
Java中对象构造
查看>>
Linq一对多联合查询
查看>>
CYQ.Data 从入门到放弃ORM系列:开篇:自动化框架编程思维
查看>>
在设计DJANGO用户更改密码时,出现NoReverseMatch at /account/password-change/这种妖精如何办?...
查看>>
android中保存一个ArrayList到SharedPreferences的方法
查看>>