Shiro-集成Spring

1.加入Spring 和 shiro 的jar包

2.配置Spring及SpringMVC

3.参照:Apache Shiroshiro-root-1.2.3-source-releaseshiro-root-1.2.3samplesspring配置web.xml文件和Spring的配置文件。

4.首先,配好Spring和SpringMVC,详细信息如下:

applicationContext.xml:

 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     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9 
10    
11    <context:component-scan base-package="com.hk.shiro"></context:component-scan>
12    
13    
14    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
15       <property name="prefix" value="/"></property>
16       <property name="suffix" value=".jsp"></property>
17    </bean>
18    
19    <mvc:annotation-driven></mvc:annotation-driven>
20    <mvc:default-servlet-handler/>
21 </beans>

spring-servlet.xml:

 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:mvc="http://www.springframework.org/schema/mvc"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9     
10     <context:component-scan base-package="com.atguigu.shiro"></context:component-scan>
11     
12     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
13         <property name="prefix" value="/"></property>
14         <property name="suffix" value=".jsp"></property>
15     </bean>
16     
17     <mvc:annotation-driven></mvc:annotation-driven>
18     <mvc:default-servlet-handler/>
19 
20 </beans>

web.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     id="WebApp_ID" version="2.5">
 6     
 7     <!-- needed for ContextLoaderListener -->
 8     <context-param>
 9         <param-name>contextConfigLocation</param-name>
10         <param-value>classpath:applicationContext.xml</param-value>
11     </context-param>
12 
13     <!-- Bootstraps the root web application context before servlet initialization -->
14     <listener>
15         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
16     </listener>
17     
18     <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
19     <servlet>
20         <servlet-name>spring</servlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22         <load-on-startup>1</load-on-startup>
23     </servlet>
24 
25     <!-- Map all requests to the DispatcherServlet for handling -->
26     <servlet-mapping>
27         <servlet-name>spring</servlet-name>
28         <url-pattern>/</url-pattern>
29     </servlet-mapping>
30 </web-app>

user.jsp:

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     
11     <h4>User Page</h4>
12     
13 </body>
14 </html>

运行结果:

所以,配置成功。

附:

5.和shiro集成

附:

ShiroRealm.java:

 1 package com.hk.shiro.realms;
 2 
 3 import org.apache.shiro.authc.AuthenticationException;
 4 import org.apache.shiro.authc.AuthenticationInfo;
 5 import org.apache.shiro.authc.AuthenticationToken;
 6 import org.apache.shiro.realm.Realm;
 7 
 8 public class ShiroRealm implements Realm {
 9 
10     @Override
11     public AuthenticationInfo getAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
12         // TODO Auto-generated method stub
13         return null;
14     }
15 
16     @Override
17     public String getName() {
18         // TODO Auto-generated method stub
19         return null;
20     }
21 
22     @Override
23     public boolean supports(AuthenticationToken arg0) {
24         // TODO Auto-generated method stub
25         return false;
26     }
27 
28 }

applicationContext.xml:

  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     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  9 
 10     <!-- =========================================================
 11          Shiro Core Components - Not Spring Specific
 12          ========================================================= -->
 13     <!-- Shiro's main business-tier object for web-enabled applications
 14          (use DefaultSecurityManager instead when there is no web environment)-->
 15     <!-- 
 16       1.配置SecurityManager。
 17      -->
 18     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
 19         <property name="cacheManager" ref="cacheManager"/>
 20         <property name="realm" ref="jdbcRealm"/>
 21     </bean>
 22 
 23     <!-- Let's use some enterprise caching support for better performance.  You can replace this with any enterprise
 24          caching framework implementation that you like (Terracotta+Ehcache, Coherence, GigaSpaces, etc -->
 25     <!-- 
 26         2.配置CacheManager 
 27         2.1配置ehchace的jar包及配置文件
 28      -->
 29     <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
 30         <!-- Set a net.sf.ehcache.CacheManager instance here if you already have one.  If not, a new one
 31              will be creaed with a default config:
 32              <property name="cacheManager" ref="ehCacheManager"/> -->
 33         <!-- If you don't have a pre-built net.sf.ehcache.CacheManager instance to inject, but you want
 34              a specific Ehcache configuration to be used, specify that here.  If you don't, a default
 35              will be used.:-->
 36         <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
 37     </bean>
 38 
 39     <!-- Used by the SecurityManager to access security data (users, roles, etc).
 40          Many other realm implementations can be used too (PropertiesRealm,
 41          LdapRealm, etc. -->
 42     <!-- 
 43         3.配置Realm 
 44         3.1直接配置实现了org.apache.shiro.realm.Realm接口的bean
 45     -->
 46     <bean id="jdbcRealm" class="com.hk.shiro.realms.ShiroRealm"></bean>
 47 
 48     <!-- =========================================================
 49          Shiro Spring-specific integration
 50          ========================================================= -->
 51     <!-- Post processor that automatically invokes init() and destroy() methods
 52          for Spring-configured Shiro objects so you don't have to
 53          1) specify an init-method and destroy-method attributes for every bean
 54             definition and
 55          2) even know which Shiro objects require these methods to be
 56             called. -->
 57     <!-- 
 58        4.配置LifecycleBeanPostProcessor。可以自动的来配置调用Spring IOC容器中生命周期方法
 59      -->
 60     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
 61 
 62     <!-- Enable Shiro Annotations for Spring-configured beans.  Only run after
 63          the lifecycleBeanProcessor has run: -->
 64     <!-- 
 65      5.启用IOC容器中使用shiro的注解。但必须在配置了lifecycleBeanProcessor 之后才可以使用
 66      -->
 67     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
 68           depends-on="lifecycleBeanPostProcessor"/>
 69     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
 70         <property name="securityManager" ref="securityManager"/>
 71     </bean>
 72 
 73     <!-- Define the Shiro Filter here (as a FactoryBean) instead of directly in web.xml -
 74          web.xml uses the DelegatingFilterProxy to access this bean.  This allows us
 75          to wire things with more control as well utilize nice Spring things such as
 76          PropertiesPlaceholderConfigurer and abstract beans or anything else we might need: -->
 77     <!-- 
 78      6.配置shiroFilter。
 79      6.1id必须和web.xml文件中配置的DelegatingFilterProxy的<filter-name>一致。
 80      -->
 81     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
 82         <property name="securityManager" ref="securityManager"/>
 83         <property name="loginUrl" value="/login.jsp"/>
 84         <property name="successUrl" value="/list.jsp"/>
 85         <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
 86         <!-- 
 87                               配置哪些页面需要受保护. 
 88             以及访问这些页面需要的权限. 
 89             1). anon 可以被匿名访问
 90             2). authc 必须认证(即登录)后才可能访问的页面. 
 91             3). logout 登出.
 92             4). roles 角色过滤器
 93          -->
 94         <property name="filterChainDefinitions">
 95             <value>
 96                 /login.jsp = anon
 97                 # everything else requires authentication:
 98                 /** = authc
 99             </value>
100         </property>
101     </bean>
102 </beans>

ehcache.xml:

  1 <ehcache>
  2 
  3     <!-- Sets the path to the directory where cache .data files are created.
  4 
  5          If the path is a Java System Property it is replaced by
  6          its value in the running VM.
  7 
  8          The following properties are translated:
  9          user.home - User's home directory
 10          user.dir - User's current working directory
 11          java.io.tmpdir - Default temp file path -->
 12     <diskStore path="java.io.tmpdir"/>
 13     
 14     <cache name="authorizationCache"
 15            eternal="false"
 16            timeToIdleSeconds="3600"
 17            timeToLiveSeconds="0"
 18            overflowToDisk="false"
 19            statistics="true">
 20     </cache>
 21 
 22     <cache name="authenticationCache"
 23            eternal="false"
 24            timeToIdleSeconds="3600"
 25            timeToLiveSeconds="0"
 26            overflowToDisk="false"
 27            statistics="true">
 28     </cache>
 29 
 30     <cache name="shiro-activeSessionCache"
 31            eternal="false"
 32            timeToIdleSeconds="3600"
 33            timeToLiveSeconds="0"
 34            overflowToDisk="false"
 35            statistics="true">
 36     </cache>
 37 
 38     <!--Default Cache configuration. These will applied to caches programmatically created through
 39         the CacheManager.
 40 
 41         The following attributes are required for defaultCache:
 42 
 43         maxInMemory       - Sets the maximum number of objects that will be created in memory
 44         eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
 45                             is never expired.
 46         timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
 47                             if the element is not eternal. Idle time is now - last accessed time
 48         timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
 49                             if the element is not eternal. TTL is now - creation time
 50         overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
 51                             has reached the maxInMemory limit.
 52 
 53         -->
 54     <defaultCache
 55         maxElementsInMemory="10000"
 56         eternal="false"
 57         timeToIdleSeconds="120"
 58         timeToLiveSeconds="120"
 59         overflowToDisk="true"
 60         />
 61 
 62     <!--Predefined caches.  Add your cache configuration settings here.
 63         If you do not have a configuration for your cache a WARNING will be issued when the
 64         CacheManager starts
 65 
 66         The following attributes are required for defaultCache:
 67 
 68         name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
 69         maxInMemory       - Sets the maximum number of objects that will be created in memory
 70         eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
 71                             is never expired.
 72         timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
 73                             if the element is not eternal. Idle time is now - last accessed time
 74         timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
 75                             if the element is not eternal. TTL is now - creation time
 76         overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
 77                             has reached the maxInMemory limit.
 78 
 79         -->
 80 
 81     <!-- Sample cache named sampleCache1
 82         This cache contains a maximum in memory of 10000 elements, and will expire
 83         an element if it is idle for more than 5 minutes and lives for more than
 84         10 minutes.
 85 
 86         If there are more than 10000 elements it will overflow to the
 87         disk cache, which in this configuration will go to wherever java.io.tmp is
 88         defined on your system. On a standard Linux system this will be /tmp"
 89         -->
 90     <cache name="sampleCache1"
 91         maxElementsInMemory="10000"
 92         eternal="false"
 93         timeToIdleSeconds="300"
 94         timeToLiveSeconds="600"
 95         overflowToDisk="true"
 96         />
 97 
 98     <!-- Sample cache named sampleCache2
 99         This cache contains 1000 elements. Elements will always be held in memory.
100         They are not expired. -->
101     <cache name="sampleCache2"
102         maxElementsInMemory="1000"
103         eternal="true"
104         timeToIdleSeconds="0"
105         timeToLiveSeconds="0"
106         overflowToDisk="false"
107         /> -->
108 
109     <!-- Place configuration for your caches following -->
110 
111 </ehcache>

spring-servlet.xml和web.xml没有变。

list.jsp:

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 3 <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>    
 4     
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 9 <title>Insert title here</title>
10 </head>
11 <body>
12     
13     <h4>List Page</h4>
14     
15     Welcome: <shiro:principal></shiro:principal>
16     
17     <shiro:hasRole name="admin">
18     <br><br>
19     <a href="admin.jsp">Admin Page</a>
20     </shiro:hasRole>
21     
22     <shiro:hasRole name="user">
23     <br><br>
24     <a href="user.jsp">User Page</a>
25     </shiro:hasRole>
26     
27     <br><br>
28     <a href="shiro/testShiroAnnotation">Test ShiroAnnotation</a>
29     
30     <br><br>
31     <a href="shiro/logout">Logout</a>
32     
33 </body>
34 </html>

login.jsp:

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     
11     <h4>Login Page</h4>
12     
13     <form action="shiro/login" method="POST">
14         username: <input type="text" name="username"/>
15         <br><br>
16         
17         password: <input type="password" name="password"/>
18         <br><br>
19         
20         <input type="submit" value="Submit"/>
21     </form>
22     
23 </body>
24 </html>

unauthorized.jsp:

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     
11     <h4>Unauthorized Page</h4>
12     
13 </body>
14 </html>

 运行结果:

注:只有login.jsp才能访问,其他的不行。

注意:未完待续。。。

每接触一个新领域,我就像一块掉进水里的海绵,四面八方的养分都让我不断充实。O(∩_∩)O~
原文地址:https://www.cnblogs.com/zhzcode/p/9676754.html