Shiro 進階之從資料庫讀取過濾器鏈
我們之前使用過濾器鏈都是在 XML 中手動新增和維護的,本章我們來介紹下如何從資料庫讀取這些過濾器配置,這樣做的好處是便於維護,且可以通過程式來新增過濾器配置,因為我們只需要新增一條記錄到資料庫即可。
回顧下,之前我們是這樣配置的:
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <!-- 登入頁面, 未認證時訪問需要認證或授權的資源會自動跳轉到此頁面 --> <property name="loginUrl" value="/login.jsp"/> <!-- 登入成功頁面 --> <property name="successUrl" value="/index.jsp"/> <!-- 登入後, 訪問未授權的資源會跳轉到此頁面 --> <property name="unauthorizedUrl" value="/unauthorized.jsp"/> <property name="filterChainDefinitions"> <value> /login.jsp = anon /login = anon /user.jsp = anyRoles[user, admin] /userList.jsp = perms[select:delete] /logout = logout /** = authc </value> </property> </bean>
主要是filterChainDefinitions
屬性,現在我們將其修改為:
<property name="filterChainDefinitionMap" ref=""/>
我們點開ShiroFilterFactoryBean
的filterChainDefinitionMap
屬性來看下,它是 Map 型別的:
public void setFilterChainDefinitionMap(Map<String, String> filterChainDefinitionMap) { this.filterChainDefinitionMap = filterChainDefinitionMap; }
這樣我們就可以建立一個類,他從資料庫讀取許可權資料組成一個 Map 型別作為返回值即可,這裡我們用例項工廠來實現:
import java.util.LinkedHashMap; public class FilterChainDefinitionMapBuilder { public LinkedHashMap<String, String> buildFilterChainDefinitionMap() { LinkedHashMap<String, String> map = new LinkedHashMap<>(); // 這裡根據自己使用的資料庫查詢, 將值 put 到 Map 中. return map; } }
使用LinkedHashMap
的原因是為了保證插入順序有序,具體連線資料庫和查詢程式碼這裡就不在演示了,自行根據專案使用的 ORM 框架來實現。
最後的配置檔案是這樣的:
<!-- shiro 過濾器, 要與 web.xml 中的 Filter Name 相同--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <!-- 登入頁面, 未認證時訪問需要認證或授權的資源會自動跳轉到此頁面 --> <property name="loginUrl" value="/login.jsp"/> <!-- 登入成功頁面 --> <property name="successUrl" value="/index.jsp"/> <!-- 登入後, 訪問未授權的資源會跳轉到此頁面 --> <property name="unauthorizedUrl" value="/unauthorized.jsp"/> <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"/> </bean> <bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapBuilder" factory-method="buildFilterChainDefinitionMap"/> <bean id="filterChainDefinitionMapBuilder" class="im.zhaojun.factory.FilterChainDefinitionMapBuilder"/>
本章程式碼地址 :ofollow,noindex">https://github.com/zhaojun1998/Premission-Study/tree/master/Permission-Shiro-12/