Shiro+Spring+Struts2集成演示权限控制

一、新建工程,导入依赖包

asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-fileupload-1.3.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
ehcache-core-2.4.3.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.15.jar
log4j-1.2.17.jar
ognl-3.0.6.jar
shiro-aspectj-1.2.2.jar
shiro-cas-1.2.2.jar
shiro-core-1.2.2.jar
shiro-ehcache-1.2.2.jar
shiro-guice-1.2.2.jar
shiro-quartz-1.2.2.jar
shiro-spring-1.2.2.jar
shiro-tools-hasher-1.2.2-cli.jar
shiro-web-1.2.2.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
struts2-core-2.3.15.3.jar
struts2-spring-plugin-2.3.15.3.jar
xwork-core-2.3.15.3.jar

二、配置web.xml 必不可少

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <!-- 1.配置springIOC容器监听器 -->  
  4.     <context-param>  
  5.         <param-name>contextConfigLocation</param-name>  
  6.         <param-value>classpath:application.xml</param-value>  
  7.     </context-param>  
  8.   
  9.     <!-- Bootstraps the root web application context before servlet initialization -->  
  10.     <listener>  
  11.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  12.     </listener>  
  13.     
  14.   <!--2.配置shiro过滤器  -->  
  15.    <filter>  
  16.         <filter-name>shiroFilter</filter-name>  
  17.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  18.         <init-param>  
  19.             <param-name>targetFilterLifecycle</param-name>  
  20.             <param-value>true</param-value>  
  21.         </init-param>  
  22.     </filter>  
  23.     <filter-mapping>  
  24.         <filter-name>shiroFilter</filter-name>  
  25.         <url-pattern>/*</url-pattern>  
  26.     </filter-mapping>  
  27.       
  28.     <!--3.配置struts2过滤器  -->  
  29.     <filter>  
  30.         <filter-name>struts2</filter-name>  
  31.         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  32.     </filter>  
  33.     <filter-mapping>  
  34.         <filter-name>struts2</filter-name>  
  35.         <url-pattern>/*</url-pattern>  
  36.     </filter-mapping>    
  37.     
  38. </web-app>  

三、配置spring配置文件application.xml更为重要!

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  6.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
  7.   
  8.     <!-- 1.配置要扫描的包 -->  
  9.     <context:component-scan base-package="com.tan.shiro"></context:component-scan>  
  10.       
  11.     <!--2.配置CacheManager实例:管理Shiro相关缓存操作  -->  
  12.     <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">   
  13.         <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"></property>  
  14.     </bean>  
  15.       
  16.     <!--3.配置realm实例,实际的认证和授权都是由Realm实例来完成的!  -->  
  17.     <bean id="myRealm" class="com.tan.shiro.realm.MyRealm"></bean>  
  18.   
  19.     <!-- 4.配置 SecurityManager 实例. SecurityManager 是 Shiro 最核心的组件 -->  
  20.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  21.         <property name="cacheManager" ref="cacheManager"/>  
  22.         <property name="realm" ref="myRealm"/>  
  23.     </bean>  
  24.       
  25.     <!--5.配置bean的后置处理器来自动调用Shiro中的bean的init和destroy方法。  -->  
  26.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>  
  27.       
  28.       
  29.     <!--6.配置使shiro注解起作用的bean,需要放在 lifecycleBeanPostProcessor后面 -->  
  30.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"></bean>      
  31.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  32.         <property name="securityManager" ref="securityManager"></property>  
  33.     </bean>  
  34.       
  35.     <!--  
  36.         7.配置哪些页面需要被拦截,以及访问这些页面所需的权限 。  
  37.         该bean中的id 属性值必须和 web.xml 文件中配置的 filter 的 filter-name 值一致  
  38.     -->  
  39.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  40.         <property name="securityManager" ref="securityManager"></property>  
  41.       
  42.         <!--①配置登陆页面  -->  
  43.         <property name="loginUrl" value="/login.jsp"></property>  
  44.         <property name="successUrl" value="/list.jsp"></property>  
  45.         <property name="unauthorizedUrl" value="/unauthorize.jsp"></property>  
  46.         <!--②配置需要被拦截的资源 以及访问权限 -->  
  47.         <property name="filterChainDefinitions">  
  48.             <value>  
  49.                 <!-- anon: 表示匿名的, 即任何人都可以访问 -->  
  50.                 /login.jsp=anon  
  51.                 /login=anon  
  52.                 /logout=logout  
  53.                   
  54.                 <!--③设置访问具体资源的权限  -->  
  55.                 /admin.jsp=roles[admin]  
  56.                 /user.jsp=roles[user]  
  57.                   
  58.                 <!-- authc 表示必须经过认证之后才可以访问的页面 -->  
  59.                 /**=authc  
  60.             </value>  
  61.         </property>  
  62.     </bean>  
  63. </beans>  


四、新建自定义Realm来实现自定义的认证和授权

[java] view plain copy
  1. package com.tan.shiro.realm;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. import org.apache.shiro.authc.AuthenticationException;  
  8. import org.apache.shiro.authc.AuthenticationInfo;  
  9. import org.apache.shiro.authc.AuthenticationToken;  
  10. import org.apache.shiro.authc.IncorrectCredentialsException;  
  11. import org.apache.shiro.authc.LockedAccountException;  
  12. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  13. import org.apache.shiro.authc.UnknownAccountException;  
  14. import org.apache.shiro.authc.UsernamePasswordToken;  
  15. import org.apache.shiro.authz.AuthorizationInfo;  
  16. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  17. import org.apache.shiro.realm.AuthorizingRealm;  
  18. import org.apache.shiro.subject.PrincipalCollection;  
  19.   
  20. public class MyRealm extends AuthorizingRealm implements Serializable {  
  21.     private static final long serialVersionUID = 1L;  
  22.   
  23.     //一、认证 (自定义认证)  
  24.     @Override  
  25.     protected AuthenticationInfo doGetAuthenticationInfo(  
  26.             AuthenticationToken arg0) throws AuthenticationException {  
  27.         //强转为UsernamePasswordToken类型  
  28.         UsernamePasswordToken token=(UsernamePasswordToken)arg0;   
  29.           
  30.         //获取用户名和密码(密码要转为字符串类型)  
  31.         String username = token.getUsername();  
  32.         String password = new String(token.getPassword());  
  33.           
  34.         //测试一下,看是否得到了用户名和密码  
  35.          System.out.println("username: " + username + ", password: " + password);  
  36.           
  37.         //模拟查询数据库进行登录操作  
  38.          if("a".equals(username)){  
  39.              throw new UnknownAccountException("没有这个账号");   
  40.          }  
  41.          if("a".equals(password)){  
  42.              throw new IncorrectCredentialsException("密码错误");   
  43.          }  
  44.          if("b".equals(username)){  
  45.              throw new LockedAccountException("账号被锁定!");   
  46.          }  
  47.          //利用新建的类来创建对象  
  48.          ShiroUser user=new ShiroUser();  
  49.          user.setUsername(username); //将页面中的username值设置进去  
  50.            
  51.          //模拟设置权限部分:要分别来判断  
  52.         if("admin".equals(username)){  
  53.             //如果用户名为:admin,则为其增加2个角色 admin和user  
  54.             user.getRoles().add("admin");  
  55.             user.getRoles().add("user");  
  56.         }else if("user".equals(username)){  
  57.             //如果用户名为:user,则为其增加user角色  
  58.             user.getRoles().add("user");  
  59.         }  
  60.         return new SimpleAuthenticationInfo(user, password,getName());  
  61.     }  
  62.       
  63.     //二、授权(自定义)  
  64.      @Override  
  65.         protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {  
  66.         //arg0.getPrimaryPrincipal(): 实际上是在认证时返回的 SimpleAuthenticationInfo 的第一个参数!  
  67.             Object principal = arg0.getPrimaryPrincipal();  
  68.             ShiroUser user = (ShiroUser) principal;  
  69.             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(user.getRoles());  
  70.             return info;  
  71.         }  
  72.        
  73.   
  74.     //新建一个类定义用户角色和权限  
  75.     class ShiroUser implements Serializable{  
  76.         private static final long serialVersionUID = 1L;  
  77.         private String username;  
  78.         private Set<String>roles=new HashSet<String>();  
  79.           
  80.         public String getUsername() {  
  81.             return username;  
  82.         }  
  83.         public void setUsername(String username) {  
  84.             this.username = username;  
  85.         }  
  86.         public Set<String> getRoles() {  
  87.             return roles;  
  88.         }  
  89.         public void setRoles(Set<String> roles) {  
  90.             this.roles = roles;  
  91.         }  
  92.     }  
  93.       
  94. }  


五、利用Struts2新建Controller来控制登陆

[java] view plain copy
  1. package com.tan.shiro.action;  
  2.   
  3. import org.apache.shiro.authc.AuthenticationException;  
  4. import org.apache.shiro.SecurityUtils;  
  5. import org.apache.shiro.authc.IncorrectCredentialsException;  
  6. import org.apache.shiro.authc.LockedAccountException;  
  7. import org.apache.shiro.authc.UnknownAccountException;  
  8. import org.apache.shiro.authc.UsernamePasswordToken;  
  9. import org.apache.shiro.subject.Subject;  
  10. import org.springframework.context.annotation.Scope;  
  11. import org.springframework.stereotype.Controller;  
  12. @Controller  
  13. @Scope("prototype")  
  14. public class LoginAction {  
  15.     private String username;  
  16.     private String password;  
  17.      public void setUsername(String username) {  
  18.         this.username = username;  
  19.     }  
  20.      public void setPassword(String password) {  
  21.         this.password = password;  
  22.     }  
  23.      public String login(){  
  24.          System.out.println("[login...]");  
  25.           
  26.          //1.获取当前的用户  
  27.          Subject currentUser = SecurityUtils.getSubject();  
  28.          //2.把登录信息封装为一个 UsernamePasswordToken 对象  
  29.          UsernamePasswordToken token=new UsernamePasswordToken(this.username,this.password);  
  30.          //3.设置"记住我"功能  
  31.          token.setRememberMe(true);  
  32.             try {  
  33.                 // *登录操作!  
  34.                 currentUser.login(token);  
  35.             } catch (UnknownAccountException uae) {  
  36.                 System.out.println("用户名不存在: " + uae);  
  37.                 return "input";  
  38.             } catch (IncorrectCredentialsException ice) {  
  39.                 System.out.println("用户名存在,但密码和用户名不匹配: " + ice);  
  40.                 return "input";  
  41.             } catch (LockedAccountException lae) {  
  42.                 System.out.println("用户被锁定: " + lae);  
  43.                 return "input";  
  44.             } catch (AuthenticationException ae) {  
  45.                 System.out.println("其他异常: " + ae);  
  46.                 return "input";  
  47.             }  
  48.    
  49.          return "success";  
  50.      }  
  51. }  

六、配置struts.xml 来渲染视图

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5. <struts>  
  6.   
  7.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  8.     <constant name="struts.devMode" value="true" />  
  9.   
  10.     <package name="default" namespace="/" extends="struts-default">  
  11.           
  12.         <action name="login" class="loginAction" method="login">  
  13.             <result>/list.jsp</result>  
  14.             <result name="input">/login.jsp</result>  
  15.         </action>  
  16.         <action name="page" class="loginAction" method="getPage">  
  17.             <result name="success"></result>  
  18.         </action>  
  19.           
  20.     </package>  
  21.   
  22. </struts>  


七、在webContent下新建几个简单的跳转页面 


     admin.jsp  | list.jsp  |  login.jsp  |user.jsp | unauthorize.jsp


【补充】

  ehcache-shiro.xml文件可以从源码中获取,为了大家方便还是粘出来O(∩_∩)O~

[html] view plain copy
  1. <ehcache>  
  2.     <diskStore path="java.io.tmpdir/shiro-spring-sample"/>  
  3.     <defaultCache  
  4.             maxElementsInMemory="10000"  
  5.             eternal="false"  
  6.             timeToIdleSeconds="120"  
  7.             timeToLiveSeconds="120"  
  8.             overflowToDisk="false"  
  9.             diskPersistent="false"  
  10.             diskExpiryThreadIntervalSeconds="120"  
  11.             />  
  12.   
  13.     <cache name="shiro-activeSessionCache"  
  14.            maxElementsInMemory="10000"  
  15.            eternal="true"  
  16.            overflowToDisk="true"  
  17.            diskPersistent="true"  
  18.            diskExpiryThreadIntervalSeconds="600"/>  
  19.   
  20.     <cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization"  
  21.            maxElementsInMemory="100"  
  22.            eternal="false"  
  23.            timeToLiveSeconds="600"  
  24.            overflowToDisk="false"/>  
  25. </ehcache>  
原文地址:https://www.cnblogs.com/hzcya1995/p/13317688.html