shiro學習--jsp標籤

在頁面上,若是要實現對某些文本、按鈕等的控制,例如須要有什麼角色或者權限才能夠看見這個按鈕,利用shiro自帶的shiro標籤能很容易就實現html

1、引入shiro標籤庫

    首先得在jsp頁面的頭部引入EL表達式,來引入shiro標籤,以及在本頁面中使用的標籤前綴java

<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>

說明:<% @ taglib %>指令聲明此JSP文件使用了自定義的標籤,同時引用標籤庫,也指定了他們的標籤的前綴,例如上面的是引入了shiro的標籤庫,指定了標籤的前綴爲:shiro(這個能夠根據本身的命名喜愛來命名)。apache

    注意:jsp

    你必須在使用自定義標籤以前使用<% @ taglib %>指令定義,並且你能夠在一個頁面中屢次使用,可是前綴只能定義一次spa

2、shiro的標籤

下圖爲shiro標籤庫中定義的方法:code

接下來,讓我爲你們詳細解析一下shiro標籤的具體做用:orm

1.shiro:authenticated (表示已認證經過,但不包括remember me登陸的)
<shiro:authenticated> <label>用戶身份驗證已經過 </label> </shiro:authenticated> 

說明:只有已經過用戶認證,但不是經過記住我(remember me)瀏覽纔會看到標籤內的內容xml

2.shiro:guest (表示是遊客身份,沒有登陸)
<shiro:guest>     <label>您當前是遊客,</label><a href="/login.jsp" >請登陸</a> </shiro:guest>

說明:只有是沒有登陸過,以遊客的身份瀏覽纔會看到標籤內的內容htm

3.shiro:hasAnyRoles(表示擁有這些角色中其中一個)
<shiro:hasAnyRoles name="admin,user">     <label>這是擁有admin或者是user角色的用戶</label> </shiro:hasAnyRoles>

說明:只有成功登陸後,且具備admin或者user角色的用戶纔會看到標籤內的內容;name屬性中能夠填寫多個角色名稱,以逗號(,)分隔對象

4.shiro:hasPermission(表示擁有某一權限)
<shiro:hasPermission name="admin:add">     <label>這個用戶擁有admin:add的權限</label> </shiro:hasPermission>

說明:只有成功登陸後,且具備admin:add權限的用戶才能夠看到標籤內的內容,name屬性中只能填寫一個權限的名稱

5.shiro:hashRole (表示擁有某一角色)
<shiro:hasRole name="admin">     <label>這個用戶擁有的角色是admin</label> </shiro:hasRole>

說明:只有成功登陸後,且具備admin角色的用戶才能夠看到標籤內的內容,name屬性中只能填寫一個角色的名稱

6.shiro:lacksPermission (表示不擁有某一角色)
<shiro:lacksPermission name="admin:delete">     <label>這個用戶不擁有admin:delete的權限</label> </shiro:lacksPermission>

說明:只有成功登陸後,且不具備admin:delete權限的用戶才能夠看到標籤內的內容,name屬性中只能填寫一個權限的名稱

7.shiro:lacksRole (表示不擁有某一角色)
<shiro:lacksRole name="admin">     <label>這個用戶不擁有admin的角色</label> </shiro:lacksRole>

說明:只有成功登陸後,且不具備admin角色的用戶才能夠看到標籤內的內容,name屬性中只能填寫一個角色的名稱

8.shiro:notAuthenticated (表示沒有經過驗證)
<shiro:notAuthenticated>     <label>用戶身份驗證沒有經過(包括經過記住我(remember me)登陸的) </label> </shiro:notAuthenticated>

說明:只有沒有經過驗證的才能夠看到標籤內的內容,包括經過記住我(remember me)登陸的

9.shiro:principal (表示用戶的身份)

取值取的是你登陸的時候,在Realm 實現類中的new SimpleAuthenticationInfo(第一個參數,....) 放的第一個參數:

....
return new SimpleAuthenticationInfo(user,user.getPswd(), getName());

    1)若是第一個放的是username或者是一個值 ,那麼就能夠直接用。

<!--取到username--> <shiro: principal/>

    2)若是第一個參數放的是對象,好比放User 對象。那麼若是要取其中某一個值,能夠經過property屬性來指定。

<!--須要指定property--> <shiro:principal property="username"/>
10.shiro:user (表示已登陸)
<shiro:user>     <label>歡迎[<shiro:principal/>],</label><a href="/logout.jsp">退出</a> </shiro:user>

說明:只有已經登陸(包含經過記住我(remember me)登陸的)的用戶才能夠看到標籤內的內容;通常和標籤shiro:principal一塊兒用,來作顯示用戶的名稱

 

注意:

    shiro的jsp標籤能夠嵌套使用,能夠根據業務的具體場景進行使用。例如一個按鈕須要排除不是admin或user角色的用戶才能夠顯示,能夠像以下這樣實現:

<shiro:lacksRole name="admin">     <shiro:lacksRole name="user">         <label>這個用戶不擁有admin或user的角色</label>     </shiro:lacksRole> </shiro:lacksRole>
相關文章
相關標籤/搜索