shiro讲解之 SpringMVC 集成Shiro
本章节将通过实例来学习下SpringMVC+Spring+Shiro如何集成并用一个精简的例子说明。
整合
新建一个完整的Spring+SpringMVC 框架
- 关于Spring整个SpringMVC的例子已在SpingMVC模块有分享,可移步至SpringMVC。
项目目录
整合 Shiro 步骤
下载 Shiro 及相关jar包
pom.xml新增以下依赖
<!-- Shiro --> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.3.2</version> </dependency> <!-- Shiro end --> <!-- Ehcache --> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.4</version> </dependency> <!-- Ehcahche end -->
配置web.xml
Shiro web.xml配置信息参考 Shiro Web App。这里我们的整合将直接参考Spring Example中的web.xml的配置信息。
<!-- 配置Shiro Filter --> <!-- 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>
web.xml文件中配置Shiro 的DelegatingFilterProxy,该Filter的核心作用点就是用户拦截和过滤请求的URL,之于如何处理URL将在Shiro配置文件的 shiroFilter中有具体的说明。
新建ehcache.xml缓存
在整合Shiro的过程中我们在使用shiro的缓存机制时会使用到缓存,这一点在pom.xml的依赖有提现,另外在后续的篇章中我们也将详细说明Shiro的缓存机制,这里做初步了解。
在classpath(一般建议,也可以自定义)下新建一个ehcache.xml,配置信息如下,如有必要可全部复制<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir" /> <!-- 缓存存放目录(此目录为放入系统默认缓存目录),也可以是”D:/cache“ java.io.tmpdir --> <!-- 登录记录缓存 锁定10分钟 --> <cache name="passwordRetryCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cache name="authorizationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cache name="authenticationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600"