freemarker实现自定义标签

freemarker实现自定义标签

freemarker实现自定义标签其实并没有什么难度,这个功能我们叫自定义标签,在官网中称为指令,也并不是什么高级技术,只是大家没发现而已,参考下官网文档就能实现:https://freemarker.apache.org/docs/pgui_datamodel_directive.html
http://freemarker.foofun.cn/pgui_datamodel_directive.html
更多功能需要自己去研究,编写这编文章的目的是因为我在网上无法搜索到满意的结果。

一、依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

二、首先自定义一个标签 auth

我们的标签是这个样子:

<!-- 提前将标签引入 -->
<#assign auth="com.lingkang.flynovel.config.tag.AuthTag"?new()>
<@auth security="isAuthenticated">
    已经登录
</@auth>

<@auth hasRole="ROLE_USER">
  存在角色 ROLE_USER
</@auth>

那么我们的Java代码这样写:

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author 绫小路
 * @date 2021/3/27
 * @description 自定义标签, 首先引入 <#assign auth="com.lingkang.flynovel.config.tag.AuthTag"?new()>
 * <p><@auth hasRole="ROLE_USER"> 存在角色 ROLE_USER </@auth>
 */
@Component
public class AuthTag implements TemplateDirectiveModel {

  @Override
  public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody)
      throws TemplateException, IOException {
    // 判断是否授权标签:
    /**
     * <#assign auth="com.lingkang.flynovel.config.tag.AuthTag"?new()>
     * <@auth security="isAuthenticated";aaaa>
     *     已经登录
     * </@auth>
     */
    Object o = map.get("security");
    if (o != null && "isAuthenticated".equals(o.toString())) {
      if (SecurityContextHolder.getContext().getAuthentication() == null) {
      // 输出标签的内容为null
        templateDirectiveBody.render(null);
      } else {
      // 将标签的内容输出
        templateDirectiveBody.render(environment.getOut());
      }
      return;
    }

    //判断是否存在角色
    /**
     * <@auth hasRole="ROLE_USER">
     *   存在角色 ROLE_USER
     * </@auth>
     */
    Object hasRole = map.get("hasRole");
    if (hasRole != null) {
      String role = hasRole.toString();
      Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
      for (GrantedAuthority g : authorities) {
        if (role.equals(g.getAuthority())) {
          templateDirectiveBody.render(environment.getOut());
          return;
        }
      }
      return;
    }
  }
}

效果截图:
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 中使用 Freemarker 自定义标签,可以通过以下步骤实现: 1. 创建一个自定义标签类,继承 `freemarker.template.TemplateDirectiveModel` 接口,并实现其中的 `execute` 方法,该方法用于处理自定义标签的逻辑。 ```java @Component public class CustomTagDirective implements TemplateDirectiveModel { @Autowired private UserService userService; // 举例注入一个服务类 @Override public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // 处理自定义标签逻辑,可以使用 environment、params、body 等参数 String userId = params.get("userId").toString(); User user = userService.getUserById(userId); environment.getOut().write(user.getName()); } } ``` 2. 在 Spring Boot 的配置文件中注册自定义标签类。 ```java @Configuration public class FreemarkerConfig { @Autowired private CustomTagDirective customTagDirective; @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath("classpath:/templates"); Map<String, Object> variables = new HashMap<>(); variables.put("customTag", customTagDirective); configurer.setFreemarkerVariables(variables); return configurer; } } ``` 3. 在 Freemarker 模板中使用自定义标签。 ```html <#assign userId = "1" /> <@customTag userId=userId /> ``` 在以上代码中,我们首先通过 `<#assign>` 定义了一个变量 `userId`,然后通过 `<@customTag>` 调用自定义标签,并将 `userId` 作为参数传入。 这样就可以在 Spring Boot 中使用自定义Freemarker 标签了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

凌康ACG

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

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

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

打赏作者

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

抵扣说明:

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

余额充值