SpringBoot-shiro頁面中使用Shiro標籤(5)

SpringBoot-Thymeleaf中使用Shiro標籤

在之前權限控制中,當用戶訪問沒有權限的資源時,採取的做法是跳轉到403.html沒有權限頁面,在實際項目中更爲常見的做法是隻顯示當前用戶擁有訪問權限的資源,沒有權限的直接爲不可見。配合Thymeleaf中的Shiro標籤可以很簡單的實現這個目標。

實際上Thymeleaf官方並沒有提供Shiro的標籤,我們需要引入第三方實現,地址爲**thymeleaf-extras-shiro**

1.引入thymeleaf-extras-shiro依賴:

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

2. 在ShiroConfig.java增加配置

	/**
     * 註冊這個bean目的就是爲了在thymeleaf中使用shiro的自定義tag。
     *
     * @return at.pollux.thymeleaf.shiro.dialect.ShiroDialect
     * @author: zhihao
     * @date: 2019/12/16
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

3, 首頁index.html改造

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:shiro="http://www.w3.org/1999/xhtml">
    <!--需要注意要使用shiro標籤得加上xmlns:shiro="http://www.w3.org/1999/xhtml"-->
<head>
  <meta charset="UTF-8">
  <title>首頁</title>
</head>
<body>
<p>[[${user.username}]]帥哥你好!</p>
<div>
  <a shiro:hasPermission="user:user" th:href="@{/list}">獲取用戶信息</a>
  <a shiro:hasPermission="user:add" th:href="@{/add}">新增用戶</a>
  <a shiro:hasPermission="user:delete" th:href="@{/delete}">刪除用戶</a>
</div>
<p shiro:hasRole="admin">你的角色爲超級管理員</p>
<p shiro:hasRole="test">你的角色爲測試賬戶</p>
<a th:href="@{/logout}">註銷</a>
</body>
</html>

4. 進行測試,擁有權限的纔可見

擴展資料:

標籤說明:

以下示例說明如何將標籤集成到Thymeleaf模板中。這些都是Apache Shiro文檔的JSP / GSP標記庫部分中給出的示例的全部實現。

標籤可以用屬性或元素符號表示:

<p shiro:guest="">
  Please--驗證當前用戶是否爲“訪客”,即未認證(包含未記住)的用戶 <a href="login.html">Login</a>
</p>

<p shiro:user="">
  Welcome back John! Not John? Click <a href="login.html">here<a> to login.認證通過或已記住的用戶出現
</p>

<a shiro:authenticated="" href="updateAccount.html">Update your contact information已認證纔會出現</a>

<p shiro:notAuthenticated="">
  Please <a href="login.html">login</a> in order to update your credit card information.
  未認證纔會出現
</p>

<p>Hello, <span shiro:principal=""></span>, 輸出了用戶信息</p>

<p>Hello, <shiro:principal/>輸出了用戶信息</p>

<p shiro:hasRole="admin" >
  用戶擁有管理員角色纔會出現
</p>


<p shiro:lacksRole="admin">
  用戶缺管理員角色纔會出現
</p>

<p shiro:hasAllRoles="admin,test">
  用戶擁有管理員和測試角色纔會出現123123
</p>

<p shiro:hasAnyRoles="admin,test">
  用戶擁有管理員或者測試角色纔會出現
</p>


<p shiro:hasPermission="user:add">
  用戶擁有添加權限纔會出現
</p>


<p shiro:lacksPermission="user:delete">
  用戶缺少刪除權限纔會出現
</p>

<p shiro:hasAllPermissions="user:add, user:user">
  驗證當前用戶是否擁有所有權限纔會出現
</p>

<p shiro:hasAnyPermissions="user:add, user:user">
  驗證當前用戶是否擁有以下任意一個權限纔會出現
</p>
發佈了29 篇原創文章 · 獲贊 3 · 訪問量 1623
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章