根据尚硅谷Shiro视频学习Shiro集成Spring、授权、认证、密码比对、多Realms、会话管理、缓存、记住我相关功能实现。
目录
这边文章主要讲的是Shiro集成Spring。实现过程如下:
一、创建 spring+spring mvc 项目
在使用Myeclipse创建 spring+spring mvc 项目 文里已经详细介绍了,这里不再累赘。
二、shiro集成spring
• Shiro 提供了与 Web 集成的支持,其通过一个ShiroFilter 入口来拦截需要安全控制的URL,然后进行相应的控制
• ShiroFilter 类似于如 Strut2/SpringMVC 这种web 框架的前端控制器,是安全控制的入口点,其负责读取配置(如ini 配置文件),然后判断URL 是否需要登录/权限等工作。
1.引入 shiro的jar 包
下载shiro必要的jar,并把如下四个.jar文件复制到项目lib文件夹下:
下载地址:https://github.com/katie1221/installation-package下的CodeTools-shiro.rar
2.配置shiro
到shiro官网下载shiro(以1.3.2为例),
2.1 在web.xml中配置shiroFilter过滤器
下载完成,解压打开,打开如下目录下的web.xml文件,并其中的shiroFilter过滤器复制粘贴到自己项目中的web.xml中
web.xml:
<!--
3.配置shiroFilter
3.1 DelegatingFilterProxy实际上是Filter的一个代理对象。默认情况下,spring 会到IOC容器中查找
和 <filter-name>对应的filter bean。也可以通过targetBeanName的初始化参数来设置filter bean 的id。
-->
<!-- Shiro Filter is defined in the spring application context: -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.2 在spring配置文件applicationContext.xml里配置shiro
把如下图目录中的applicationContext.xml里面的内容
复制粘贴到项目中的applicationContext.xml里:
然后进行如下修改:
2.2.1.配置securityManager
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="realm" ref="jdbcRealm"/>
</bean>
2.2.2.配置 cacheManager
<!--
2.配置 cacheManager
2.1需要加入ehcache的jar和配置文件
-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- Set a net.sf.ehcache.CacheManager instance here if you already have one. If not, a new one