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;
}
}
}
效果截图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!