Shiro提供了JSTL標簽用於在JSP/GSP頁面進行權限控制,如根據登錄用戶顯示相應的頁面按鈕。
導入標簽庫
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
標簽庫定義在shiro-web.jar包下的META-INF/shiro.tld中定義。
guest標簽
<shiro:guest> 歡迎游客訪問,<a href="${pageContext.request.contextPath}/login.jsp">登錄</a> </shiro:guest>
用戶沒有身份驗證時顯示相應信息,即游客訪問信息。
user標簽
<shiro:user> 歡迎[<shiro:principal/>]登錄,<a href="${pageContext.request.contextPath}/logout">退出</a> </shiro:user>
用戶已經身份驗證/記住我登錄后顯示相應的信息。
authenticated標簽
<shiro:authenticated> 用戶[<shiro:principal/>]已身份驗證通過 </shiro:authenticated>
用戶已經身份驗證通過,即Subject.login登錄成功,不是記住我登錄的。
notAuthenticated標簽
<shiro:notAuthenticated> 未身份驗證(包括記住我)</shiro:notAuthenticated>
用戶已經身份驗證通過,即沒有調用Subject.login進行登錄,包括記住我自動登錄的也屬於未進行身份驗證。
principal標簽
<shiro: principal/>
顯示用戶身份信息,默認調用Subject.getPrincipal()獲取,即Primary Principal。
<shiro:principal type="java.lang.String"/>
相當於Subject.getPrincipals().oneByType(String.class)。
<shiro:principal type="java.lang.String"/>
相當於Subject.getPrincipals().oneByType(String.class)。
<shiro:principal property="username"/>
相當於((User)Subject.getPrincipals()).getUsername()。
hasRole標簽
<shiro:hasRole name="admin"> 用戶[<shiro:principal/>]擁有角色admin<br/> </shiro:hasRole>
如果當前Subject有角色將顯示body體內容。
hasAnyRoles標簽
<shiro:hasAnyRoles name="admin,user"> 用戶[<shiro:principal/>]擁有角色admin或user<br/> </shiro:hasAnyRoles>
如果當前Subject有任意一個角色(或的關系)將顯示body體內容。
lacksRole標簽
<shiro:lacksRole name="abc"> 用戶[<shiro:principal/>]沒有角色abc<br/> </shiro:lacksRole>
如果當前Subject沒有角色將顯示body體內容。
hasPermission標簽
<shiro:hasPermission name="user:create"> 用戶[<shiro:principal/>]擁有權限user:create<br/> </shiro:hasPermission>
如果當前Subject有權限將顯示body體內容。
lacksPermission標簽
<shiro:lacksPermission name="org:create"> 用戶[<shiro:principal/>]沒有權限org:create<br/> </shiro:lacksPermission>
如果當前Subject沒有權限將顯示body體內容。
另外又提供了幾個權限控制相關的標簽:
導入自定義標簽庫
<%@taglib prefix="zhang" tagdir="/WEB-INF/tags" %>
示例
<zhang:hasAllRoles name="admin,user"> 用戶[<shiro:principal/>]擁有角色admin和user<br/> </zhang:hasAllRoles> <zhang:hasAllPermissions name="user:create,user:update"> 用戶[<shiro:principal/>]擁有權限user:create和user:update<br/> </zhang:hasAllPermissions> <zhang:hasAnyPermissions name="user:create,abc:update"> 用戶[<shiro:principal/>]擁有權限user:create或abc:update<br/> </zhang:hasAnyPermissions>
hasAllRoles表示擁有所有相關的角色;hasAllPermissions表示擁有所有相關的權限;hasAnyPermissions表示擁有任意一個相關的權限。