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;
    }
  }
}

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

posted @ 2022-09-16 00:09  凌康  阅读(203)  评论(0编辑  收藏  举报