Java-Shiro(二):HelloWord
新建项目&&配置pom.xml导入包
新建maven java project项目;
修改pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dx.spring.shiro</groupId>
<artifactId>shiro-02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Archetype - shiro-02</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.13</version>
</dependency>
</dependencies>
</project>
新建shiro.ini和log4j日志配置文件log4j.properties
在项目的src/main/java下新建shiro.ini和log4j.properties文件

shiro.ini和log4j.properties文件可以从

拷贝,shiro.ini文件内容为:
# -----------------------------------------------------------------------------
# Users and their assigned roles
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz # -----------------------------------------------------------------------------
# Roles with assigned permissions
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
修改log4j.properties
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n # General Apache libraries
log4j.logger.org.apache=INFO # Spring
log4j.logger.org.springframework=INFO # Default Shiro logging
log4j.logger.org.apache.shiro=INFO # Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=INFO
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=INFO
新建com.dx.spring.shiro包,把

下Quickstart.java拷贝到com.dx.spring.shiro包下:
package com.dx.spring.shiro; 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; 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); // 获取当前环境下的一个Subject操作对象
// 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(); // 将一个对象存储到shiro的Session对象中,并验证是否有操作权限。
// 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.");
} // 验证当前认证用户是否拥有某个具体操作:商品管理:删除:商品ID为5的记录
// 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);
}
}
编译运行,打印信息如下:
2018-06-13 19:54:00,673 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler...
2018-06-13 19:54:01,441 INFO [com.dx.spring.shiro.Quickstart] - Retrieved the correct value! [aValue]
2018-06-13 19:54:01,443 INFO [com.dx.spring.shiro.Quickstart] - User [lonestarr] logged in successfully.
2018-06-13 19:54:01,444 INFO [com.dx.spring.shiro.Quickstart] - May the Schwartz be with you!
2018-06-13 19:54:01,445 INFO [com.dx.spring.shiro.Quickstart] - You may use a lightsaber ring. Use it wisely.
2018-06-13 19:54:01,445 INFO [com.dx.spring.shiro.Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!
Java-Shiro(二):HelloWord的更多相关文章
- Java EE : 二、图解 Cookie(小甜饼)
目录 Java EE : 一.图解Http协议 Java EE : 二.图解 Cookie(小甜饼) Java EE : 三.图解Session(会话) 概述 一.概述 二.详细介绍Cookie 传输 ...
- 利用JAVA生成二维码
本文章整理于慕课网的学习视频<JAVA生成二维码>,如果想看视频内容请移步慕课网. 维基百科上对于二维码的解释. 二维条码是指在一维条码的基础上扩展出另一维具有可读性的条码,使用黑白矩形图 ...
- java实现二维码
说起二维码,微信好像最先启用,随后各类二维码就开始流行起来了.那什么是二维码呢. 1.什么是二维码?百度一下即可 http://baike.baidu.com/view/132241.htm?fr=a ...
- Java 设计模式(二)-六大原则
Java 设计模式(二)-六大原则 单一职责原则(Single Responsibility Principle) 定义: 不要存在多余一个原因导致类变更,既一个类只负责一项职责. 问题由来: 当类A ...
- Java进阶(二十五)Java连接mysql数据库(底层实现)
Java进阶(二十五)Java连接mysql数据库(底层实现) 前言 很长时间没有系统的使用java做项目了.现在需要使用java完成一个实验,其中涉及到java连接数据库.让自己来写,记忆中已无从搜 ...
- 20175212童皓桢 Java实验二-面向对象程序设计实验报告
20175212童皓桢 Java实验二-面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设 ...
- java 多线程二
java 多线程一 java 多线程二 java 多线程三 java 多线程四 线程中断: /** * Created by root on 17-9-30. */ public class Test ...
- Linux -- 基于zookeeper的java api(二)
Linux -- 基于zookeeper的java api(二) 写一个关于基于集群的zookeeper的自定义实现HA 基于客户端和监控器:使用监控的方法查看每个注册过的节点的状态来做出操作. Wa ...
- 浅谈Java代理二:Cglib动态代理-MethodInterceptor
浅谈Java代理二:Cglib动态代理-MethodInterceptor CGLib动态代理特点: 使用CGLib实现动态代理,完全不受代理类必须实现接口的限制,而且CGLib底层采用ASM字节码生 ...
- java 生成二维码、可带LOGO、可去白边
1.准备工作 所需jar包: JDK 1.6: commons-codec-1.11.jar core-2.2.jar javase-2.2.jar JDK 1.7: commons-codec- ...
随机推荐
- 黑群晖NAS安装方法(收集)/物理机/VMware虚拟机/KVM虚拟机(转)
群晖NAS系统的特点: 1.正版的群晖分为两部分,启动引导和系统文件,其中启动引导是一个闪盘,镶嵌在群晖的主板上,而系统文件是现成下载然后倒入的pat文件. 2.黑群晖破解的主要是启动引导,其实能兼容 ...
- CentOS 7下KVM支持虚拟化/嵌套虚拟化配置
开启虚拟化: cat << EOF > /etc/modprobe.d/kvm-nested.conf options kvm-intel nested=1 options kvm- ...
- MikroTik RouterOS授权级别
抄了一份来自淘宝代理商的说明: P系列许可级别(适用于联网的虚拟机,如:云主机,虚拟机,VPS等) 您必须在MikroTik官网 https://mikrotik.com/client/ 上拥有一个帐 ...
- CAT架构的应用与实践 IT大咖说 - 大咖干货,不再错过
CAT架构的应用与实践 IT大咖说 - 大咖干货,不再错过 http://www.itdks.com/dakashuo/new/dakalive/detail/594
- [原创]App性能测试指标篇
[原创]App性能测试指标篇 目前由于苹果,三星等大厂对智能手机的研发及投入,使的智能手机发展非常迅速,每个人手中都有一些离不开生活的App,如:微信,微博,百度或是各游戏App等,但是到底App性能 ...
- HTML一些标签注意事项
最近在IE10下运行一个以前的做web系统发现了两个小问题: 一.图片上使用"alt"属性来添加一些文字提示信息在IE10下无法正常显示出来 上网查了一下原因:原来是现在一些较新的 ...
- Odoo9发行说明
2015年10月1日,期待已久的Odoo9正式发布.本文是Odoo9正式版发行说明,基于官网资料翻译. 译者: 苏州-微尘原文地址:https://www.odoo.com/page/odoo-9-r ...
- Objective-C中的一些特殊的数据类及NSLog的输出格式
NSLog的格式如下所示: %@ 对象 %d, %i 整数 %u 无符整形 %f 浮点/双字 %x, %X 二进制整数 %o 八进制整数 %zu size_t % ...
- Android 4.4 Kitkat Phone工作流程浅析(八)__Phone状态分析
本文来自http://blog.csdn.net/yihongyuelan 转载请务必注明出处 本文代码以MTK平台Android 4.4为分析对象.与Google原生AOSP有些许差异.请读者知悉. ...
- mysql递归查询从子类ID查询所有父类
先来看数据表的结构如下: id name parent_id --------------------------- 1 Home 0 2 About ...