新建项目&&配置pom.xml导入包

新建maven java project项目;

修改pom.xml:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.dx.spring.shiro</groupId>
  5. <artifactId>shiro-02</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <name>Archetype - shiro-02</name>
  8. <url>http://maven.apache.org</url>
  9. <dependencies>
  10. <dependency>
  11. <groupId>org.apache.shiro</groupId>
  12. <artifactId>shiro-core</artifactId>
  13. <version>1.2.4</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.slf4j</groupId>
  17. <artifactId>slf4j-log4j12</artifactId>
  18. <version>1.7.13</version>
  19. </dependency>
  20. </dependencies>
  21. </project>

新建shiro.ini和log4j日志配置文件log4j.properties

在项目的src/main/java下新建shiro.ini和log4j.properties文件

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

拷贝,shiro.ini文件内容为:

  1. # -----------------------------------------------------------------------------
  2. # Users and their assigned roles
  3. # -----------------------------------------------------------------------------
  4. [users]
  5. # user 'root' with password 'secret' and the 'admin' role
  6. root = secret, admin
  7. # user 'guest' with the password 'guest' and the 'guest' role
  8. guest = guest, guest
  9. # user 'presidentskroob' with password '12345' ("That's the same combination on my luggage!!!" ;)), and role 'president'
  10. presidentskroob = 12345, president
  11. # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
  12. darkhelmet = ludicrousspeed, darklord, schwartz
  13. # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
  14. lonestarr = vespa, goodguy, schwartz
  15.  
  16. # -----------------------------------------------------------------------------
  17. # Roles with assigned permissions
  18. # -----------------------------------------------------------------------------
  19. [roles]
  20. # 'admin' role has all permissions, indicated by the wildcard '*'
  21. admin = *
  22. # The 'schwartz' role can do anything (*) with any lightsaber:
  23. schwartz = lightsaber:*
  24. # The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with license plate 'eagle5' (instance specific id)
  25. goodguy = winnebago:drive:eagle5

修改log4j.properties

  1. log4j.rootLogger=INFO, stdout
  2.  
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
  6.  
  7. # General Apache libraries
  8. log4j.logger.org.apache=INFO
  9.  
  10. # Spring
  11. log4j.logger.org.springframework=INFO
  12.  
  13. # Default Shiro logging
  14. log4j.logger.org.apache.shiro=INFO
  15.  
  16. # Disable verbose logging
  17. log4j.logger.org.apache.shiro.util.ThreadContext=INFO
  18. log4j.logger.org.apache.shiro.cache.ehcache.EhCache=INFO

新建com.dx.spring.shiro包,把

下Quickstart.java拷贝到com.dx.spring.shiro包下:

  1. package com.dx.spring.shiro;
  2.  
  3. import org.apache.shiro.SecurityUtils;
  4. import org.apache.shiro.authc.*;
  5. import org.apache.shiro.config.IniSecurityManagerFactory;
  6. import org.apache.shiro.mgt.SecurityManager;
  7. import org.apache.shiro.session.Session;
  8. import org.apache.shiro.subject.Subject;
  9. import org.apache.shiro.util.Factory;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12.  
  13. public class Quickstart {
  14. private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
  15.  
  16. public static void main(String[] args) {
  17. // The easiest way to create a Shiro SecurityManager with configured
  18. // realms, users, roles and permissions is to use the simple INI config.
  19. // We'll do that by using a factory that can ingest a .ini file and
  20. // return a SecurityManager instance:
  21.  
  22. // Use the shiro.ini file at the root of the classpath (file: and url:
  23. // prefixes load from files and urls respectively):
  24. Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
  25. SecurityManager securityManager = factory.getInstance();
  26.  
  27. // for this simple example quickstart, make the SecurityManager
  28. // accessible as a JVM singleton.
  29. // Most applications wouldn't do this and instead rely on their
  30. // container configuration or web.xml for webapps.
  31. // That is outside the scope of this simple quickstart, so we'll just do
  32. // the bare minimum so you can continue to get a feel for things.
  33. SecurityUtils.setSecurityManager(securityManager);
  34.  
  35. // 获取当前环境下的一个Subject操作对象
  36. // Now that a simple Shiro environment is set up, let's see what you can
  37. // do: get the currently executing user:
  38. Subject currentUser = SecurityUtils.getSubject();
  39.  
  40. // 将一个对象存储到shiro的Session对象中,并验证是否有操作权限。
  41. // Do some stuff with a Session (no need for a web or EJB container!!!)
  42. Session session = currentUser.getSession();
  43. session.setAttribute("someKey", "aValue");
  44. String value = (String) session.getAttribute("someKey");
  45. if (value.equals("aValue")) {
  46. log.info("Retrieved the correct value! [" + value + "]");
  47. }
  48.  
  49. // let's login the current user so we can check against roles and
  50. // permissions:
  51. if (!currentUser.isAuthenticated()) {
  52. UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
  53. token.setRememberMe(true);
  54. try {
  55. currentUser.login(token);
  56. } catch (UnknownAccountException uae) {
  57. log.info("There is no user with username of " + token.getPrincipal());
  58. } catch (IncorrectCredentialsException ice) {
  59. log.info("Password for account " + token.getPrincipal() + " was incorrect!");
  60. } catch (LockedAccountException lae) {
  61. log.info("The account for username " + token.getPrincipal() + " is locked. "
  62. + "Please contact your administrator to unlock it.");
  63. }
  64. // ... catch more exceptions here (maybe custom ones specific to
  65. // your application?
  66. catch (AuthenticationException ae) {
  67. // unexpected condition? error?
  68. }
  69. }
  70.  
  71. // say who they are:
  72. // print their identifying principal (in this case, a username):
  73. log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
  74.  
  75. // test a role:
  76. if (currentUser.hasRole("schwartz")) {
  77. log.info("May the Schwartz be with you!");
  78. } else {
  79. log.info("Hello, mere mortal.");
  80. }
  81.  
  82. // test a typed permission (not instance-level)
  83. if (currentUser.isPermitted("lightsaber:weild")) {
  84. log.info("You may use a lightsaber ring. Use it wisely.");
  85. } else {
  86. log.info("Sorry, lightsaber rings are for schwartz masters only.");
  87. }
  88.  
  89. // 验证当前认证用户是否拥有某个具体操作:商品管理:删除:商品ID为5的记录
  90. // a (very powerful) Instance Level permission:
  91. if (currentUser.isPermitted("winnebago:drive:eagle5")) {
  92. log.info(
  93. "You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!");
  94. } else {
  95. log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
  96. }
  97.  
  98. // all done - log out!
  99. currentUser.logout();
  100.  
  101. System.exit(0);
  102. }
  103. }

编译运行,打印信息如下:

  1. 2018-06-13 19:54:00,673 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler...
  2. 2018-06-13 19:54:01,441 INFO [com.dx.spring.shiro.Quickstart] - Retrieved the correct value! [aValue]
  3. 2018-06-13 19:54:01,443 INFO [com.dx.spring.shiro.Quickstart] - User [lonestarr] logged in successfully.
  4. 2018-06-13 19:54:01,444 INFO [com.dx.spring.shiro.Quickstart] - May the Schwartz be with you!
  5. 2018-06-13 19:54:01,445 INFO [com.dx.spring.shiro.Quickstart] - You may use a lightsaber ring. Use it wisely.
  6. 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的更多相关文章

  1. Java EE : 二、图解 Cookie(小甜饼)

    目录 Java EE : 一.图解Http协议 Java EE : 二.图解 Cookie(小甜饼) Java EE : 三.图解Session(会话) 概述 一.概述 二.详细介绍Cookie 传输 ...

  2. 利用JAVA生成二维码

    本文章整理于慕课网的学习视频<JAVA生成二维码>,如果想看视频内容请移步慕课网. 维基百科上对于二维码的解释. 二维条码是指在一维条码的基础上扩展出另一维具有可读性的条码,使用黑白矩形图 ...

  3. java实现二维码

    说起二维码,微信好像最先启用,随后各类二维码就开始流行起来了.那什么是二维码呢. 1.什么是二维码?百度一下即可 http://baike.baidu.com/view/132241.htm?fr=a ...

  4. Java 设计模式(二)-六大原则

    Java 设计模式(二)-六大原则 单一职责原则(Single Responsibility Principle) 定义: 不要存在多余一个原因导致类变更,既一个类只负责一项职责. 问题由来: 当类A ...

  5. Java进阶(二十五)Java连接mysql数据库(底层实现)

    Java进阶(二十五)Java连接mysql数据库(底层实现) 前言 很长时间没有系统的使用java做项目了.现在需要使用java完成一个实验,其中涉及到java连接数据库.让自己来写,记忆中已无从搜 ...

  6. 20175212童皓桢 Java实验二-面向对象程序设计实验报告

    20175212童皓桢 Java实验二-面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设 ...

  7. java 多线程二

    java 多线程一 java 多线程二 java 多线程三 java 多线程四 线程中断: /** * Created by root on 17-9-30. */ public class Test ...

  8. Linux -- 基于zookeeper的java api(二)

    Linux -- 基于zookeeper的java api(二) 写一个关于基于集群的zookeeper的自定义实现HA 基于客户端和监控器:使用监控的方法查看每个注册过的节点的状态来做出操作. Wa ...

  9. 浅谈Java代理二:Cglib动态代理-MethodInterceptor

    浅谈Java代理二:Cglib动态代理-MethodInterceptor CGLib动态代理特点: 使用CGLib实现动态代理,完全不受代理类必须实现接口的限制,而且CGLib底层采用ASM字节码生 ...

  10. 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- ...

随机推荐

  1. j.u.c系列(10)---之并发工具类:Semaphore

    写在前面 Semaphore是一个计数信号量,它的本质是一个"共享锁". 信号量维护了一个信号量许可集.线程可以通过调用acquire()来获取信号量的许可:当信号量中有可用的许可 ...

  2. centos docker compose安装

    docker compose离线安装 通过联网机器下载docker-compose离线安装包(参见Downloads部分) https://github.com/docker/compose/rele ...

  3. JavaScript正则表达式在不同浏览器中可能遇到的问题

    这两天在用正则表达式搞一个稍微有点复杂的东西,但是不同浏览器之间的差异可浪费了我不少的人参. 现在我把正则表达式在五大主流浏览器(IE.firefox.Chrome.Safari.Opera,以当前版 ...

  4. JavaScript基础之运算符及全面的运算符优先级总结

    算数运算符: 加+,减—,乘*,除/,求余%,加加++,减减——, 加减乘除求余运算与数学上的用法完全一样. 不过,加号+还有连接字符串的作用,其他运算符还可以将字符串数字转换成数值型,参见JavaS ...

  5. [原创]互联网金融App测试介绍

    [原创]互联网金融App测试介绍 前端时间非常忙,终于非常忙的时间过去了,抽时间总结下我现在所在公司理财软件App测试,也各位分享下,也欢迎大家提建议,谢谢! 先介绍下我所在公司的产品特点,公司所研发 ...

  6. 安装node.js / npm / express / KMC

    http://www.cnblogs.com/seanlv/archive/2011/11/22/2258716.html 1. 下载Node.js官方Windows版程序: http://nodej ...

  7. STM32F4xx -- Cortex M4

    STM32F4xx official page: http://www.st.com/internet/mcu/subclass/1521.jspIntroductionFPU - Floating ...

  8. Unity3D实践系列11, 组件的添加和访问

    当把一个脚本附加到一个GameObject上的时候,这个GameObject就有了脚本组件. 通过GameObject的属性获取组件 比如如下: [RequireComponent(typeof(Ri ...

  9. DotNetty的通道处理细节

    第一,客户端如何向服务器主动发送消息: 第二,服务器如何向指定客户端发送消息: 第三,在哪里做报文的拆包和组包. public partial class FrmMain : Form { publi ...

  10. python测试开发django-31.admin后台一对多操作ForeignKey

    前言 平常的网页上有很多一对多的场景,比如填写银行卡信息的时候,会从银行列表下拉框选择对应的银行信息.一般会建两张表,一张表放银行的信息,一张表放银行卡信息. 每个银行可以对应多个银行卡,每个银行卡只 ...