shiro+thymeleaf 整合

423 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第30天,点击查看活动详情

SpringBoot框架整合了thymeleaf,后端用shiro做权限管理。

首先我先对thymeleaf做一个简单的介绍方便大家更好的理解相关的知识

hymeleaf 是一款用于渲染 XML/XHTML/HTML 5 内容的模板引擎。类似 JSP、Velocity、FreeMaker 等,它也可以轻易的与 Spring MVC 等 Web 框架进行集成作为 Web 应用的模板引擎。可以使用Thymeleaf来完全代替JSP或其他模板引擎

常用标签语法介绍

1、常用语法 

  • 赋值、字符串拼接
<p th:text="${userName}">相信光的奥特王小懒</p>
<span th:text="|Welcome to our application, ${userName}!|"></span>
  • for 循环
<table>
    <tr  th:each="user,iterStat : ${users}">
        <td th:text="${user.name}">王小懒</td>
        <td th:text="${user.age}">25</td>
    </tr>
</table>

一些比较重要的特点

  • 动静结合

  • 开箱即用

  • 多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。

  • 与 SpringBoot 完美整合

片段引用表达式

片段引用表达式用于在模板页面中引用其他的模板片段,该表达式支持以下 2 中语法结构:

  • 推荐:~{templatename::fragmentname}
  • 支持:~{templatename::#id}

templatename:模版名,fragmentname:片段名,Thymeleaf 通过 th:fragment 声明定义代码块,即:th:fragment="fragmentname"。id:HTML 的 id 选择器,使用时要在前面加上 # 号,不支持 class 选择器。

接下来开始讲述整合的大概的一个步骤如下:

  1. 导入jar
  2. 导入命名空间,使用shiro:hasPermission=""来判断用户是否拥有这一个权限。
  3. 在Config上面导入ShiroDialect的Bean对象
  4. 根据用户是否已经存在来决定是否显示按钮。

1.1 首先导入依赖

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

1.2 完成使用前的配置

image.png

在ShiroConfig文件中进行配置:

  @Bean
    public ShiroDialect getShiroDialect(){
       return new ShiroDialect();

1.3相关的应用实例

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>

<div >
    <a th:href="@{/toLogin}">登录</a>
<div/>

<p th:text="${msg}"></p>
<hr>



<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a>
</div>

<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>

</body>
</html>

前端页面:
shiro:hasPermission 作用:
用于判断用户是否拥有这个权限,有则显示这个div,没有则不显示。

<div shiro:hasPermission="user:add">
进入用户添加功能:<a href="add">用户添加</a><br/>
</div>