shiro註解,初始化資源和許可權,會話管理
有具體問題的可以參考之前的關於shiro的博文,關於shiro的博文均是一次工程的內容
註解:
新建一個類:
此時需要有admin的許可權才可以執行下面的程式碼
public class ShiroService { @RequiresRoles({"admin"}) public void testMethod(){ System.out.println("test。。。。。"); } }
把新建的類注入到spring容器中
<beanclass="com.MrChengs.shiro.service.ShiroService"></bean>
ShiroHandler .java中加入
@Controller @RequestMapping("/shiro") public class ShiroHandler { @Autowired private ShiroService shiroService; @RequestMapping("/testMethod") public String testMethod(){ shiroService.testMethod(); return "redirect:/list.jsp"; } .... }
list.jsp中加入測試超連結
<a href="shiro/testMethod">Test Method</a>
此時我們登陸admin可以成功測試
當我們登陸user再點選測試的時候
UnauthorizedException
初始化資源和許可權
點選看原始碼可知
其配置的檔案的內容最終被封裝成一個map
新建一個初始化檔案的類:
在map的方法體裡面可以寫我們需要在資料庫中查詢等程式碼
LinkedHashMap一定是這個
package com.MrChengs.shiro.Factory; import java.util.LinkedHashMap; public class FilterChainDefinitionMapperBUilder { public LinkedHashMap<String, String>builderFilterChainDefinitionMap(){ LinkedHashMap<String, String> map = newLinkedHashMap<String, String>(); map.put("/login.jsp", "anon"); map.put("/shiro/login", "anon"); map.put("/shiro/logout", "logout"); map.put("/user.jsp", "roles[user]"); map.put("/admin.jsp", "roles[admin]"); map.put("/**", "authc"); return map; } }
在application中:
把註釋的地方替換成紅色標準的地方
<!-- <property name="filterChainDefinitions"> <value> /login.jsp = anon /shiro/login = anon /shiro/logout = logout /user.jsp = roles[user] /admin.jsp = roles[admin] # everything else requires authentication: /** = authc </value> </property> --> <property name="filterChainDefinitionMap"ref="filterIniDef"></property>
<!-- 配置一個bean,實際上是一個map,例項通過工廠模式的方法 --> <bean id="filterIniDef"factory-bean="filterChainDefinitionMapperBUilder" factory-method="builderFilterChainDefinitionMap"></bean> <bean id="filterChainDefinitionMapperBUilder"class="com.MrChengs.shiro.Factory.FilterChainDefinitionMapperBUilder"></bean>
其餘不變測試時沒有任何問題的!!!
會話管理
測試如下