thymeleaf自定义标签

前言

使用thymeleaf自定义标签,环境:springboot 2.3.7 + thymeleaf 3.0.11(2021-01-14最新版)
由于使用shiro,我们需要与thymeleaf整合一些标签方便更好操作,以isAuthenticated为例。
ps:虽然有一个开源的框架,但是很久没维护了,还不如照着官网来自定义。

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      <version>2.3.7.RELEASE</version>
    </dependency>

参考官方文档:https://www.thymeleaf.org/doc/tutorials/3.0/extendingthymeleaf.html
官方demo:https://github.com/thymeleaf/thymeleafexamples-extrathyme

一、创建方言

前缀仍然使用th

package com.example.shirodemo.config.thymeleaf;

import java.util.HashSet;
import java.util.Set;
import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;

/**
 * @author 绫小路
 * @date 2021/1/14 22:43
 * @description
 */
public class ShiroDialect extends AbstractProcessorDialect {

  private static final String DIALECT_NAME = "shiro方言";

  public ShiroDialect() {
    // We will set this dialect the same "dialect processor" precedence as
    // the Standard Dialect, so that processor executions can interleave.
    super(DIALECT_NAME, "th", StandardDialect.PROCESSOR_PRECEDENCE);
  }

  @Override
  public Set<IProcessor> getProcessors(String s) {
    final Set<IProcessor> processors = new HashSet<>();
    processors.add(new AuthTagProcessor(s));
    return processors;
  }
}

二、标签处理

package com.example.shirodemo.config.thymeleaf;

import static org.thymeleaf.standard.processor.StandardWithTagProcessor.PRECEDENCE;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @author 绫小路
 * @date 2021/1/14 23:02
 * @description
 */
public class AuthTagProcessor extends AbstractAttributeTagProcessor {

  private static final String SHIRO = "shiro";

  public AuthTagProcessor(String dialectPrefix) {
    super(
        TemplateMode.HTML, // This processor will apply only to HTML mode
        dialectPrefix,     // Prefix to be applied to name for matching 前缀
        null,              // No tag name: match any tag name
        false,             // No prefix to be applied to tag name
        SHIRO,         // Name of the attribute that will be matched
        true,              // Apply dialect prefix to attribute name
        PRECEDENCE,        // Precedence (inside dialect's own precedence)优先级
        true);             // Remove the matched attribute afterwards
//    super( TemplateMode.HTML, dialectPrefix, elementName, prefixElementName, isAuthenticated, prefixAttributeName, precedence, removeAttribute);
  }

  @Override
  protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, String attributeValue,
      IElementTagStructureHandler structureHandler) {
    Subject subject = SecurityUtils.getSubject();
    if ("isAuthenticated".equals(attributeValue)) {//判断是否登录
      if (!subject.isAuthenticated()) {
        structureHandler.removeElement();//未登录时将元素移除  例如<a href="/admin" th:shiro="isAuthenticated">admin</a>
      }
    }
  }
}

三、配置

直接交给spring容器管理即可

  @Bean
  public ShiroDialect shiroDialect() {
    return new ShiroDialect();//添加自定义的标签
  }

四、使用

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
首页 <a href="/login">登录</a>
<br>
<a href="/logout" th:shiro="isAuthenticated">注销</a>
<br>
<a href="/admin" th:shiro="isAuthenticated">admin</a>
</body>
</html>

未登陆时
在这里插入图片描述
登陆后:
在这里插入图片描述

如果你在使用 Thymeleaf 时遇到了页面报错,可以查看控制台输出的错误信息,找到具体的问题所在。常见的错误包括语法错误、模板引用错误、标签使用错误等等。 如果你想利用 Thymeleaf 自定义错误页面,可以按照以下步骤进行: 1. 首先在 `src/main/resources/templates` 目录下创建一个 `error` 目录。在该目录下创建一个名为 `error.html` 的 Thymeleaf 模板文件。 2. 在 `application.properties` 文件中配置错误处理的地址: ``` server.error.path=/error ``` 3. 创建一个名为 `ErrorController` 的控制器类,用于处理错误请求: ```java @Controller public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController { @RequestMapping("/error") public String handleError(HttpServletRequest request, HttpServletResponse response) { // 获取错误状态码 Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); // 根据状态码返回不同的错误页面 if (statusCode == 404) { return "error/404"; } else { return "error/500"; } } @Override public String getErrorPath() { return "/error"; } } ``` 4. 在 `error` 目录下创建 `404.html` 和 `500.html` 两个 Thymeleaf 模板文件,用于显示不同类型的错误页面。 例如,`404.html` 可以这样编写: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>404 Not Found</title> </head> <body> <h1>404 Not Found</h1> <p>您请求的页面不存在,请检查您输入的地址是否正确。</p> </body> </html> ``` 5. 访问不存在的页面,尝试触发 404 错误,可以看到自定义的错误页面。 如果你想测试 500 错误,可以在控制器中抛出一个异常,例如: ```java @RequestMapping("/test") public String test() { throw new RuntimeException("测试错误"); } ``` 然后访问 `/test` 地址即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌康ACG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值