freemarker自定义标签实现权限管理

目的:自定义一个freemarker标签,当满足时显示标签体中的内容,并输出动态内容,否则不进行显示。

实现:

1、实现 TemplateDirectiveModel 接口(freemarker实现自定义标签需要实现这个接口)

2、在freemarker的配置类中,在freemarker的Configuration中注册这个自定义标签

3、页面上进行使用

注:自定义标签每次渲染都会进入一次标签处理类

一、实现TemplateDirectiveModel接口

import freemarker.core.Environment;
import freemarker.core.StringArraySequence;
import freemarker.template.*;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Log4j2
public class AuthDirective implements TemplateDirectiveModel {

    private static final String AUTH = "auth";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        // 1.获取用户所有的权限
        List<String> list = new ArrayList<>();
        list.add("01");
        list.add("03");
        log.info("获取当前权限列表:{} AuthDirective-execute", JsonBinder.buildNormalBinder().toJson(list));
        
        // 2.获取标签中auth属性的值,此处我知道前台页面传递过来的是String类型,所以可以直接强制转换成SimpleScalar类型
        SimpleScalar auth = (SimpleScalar) params.get(AUTH);
        log.info("获取到标签需要的权限:{} AuthDirective-execute",JsonBinder.buildNormalBinder().toJson(auth));
        // 3、给页面上的循环变量设置值
        if (null != loopVars && loopVars.length > 0) {
            loopVars[0] = new SimpleScalar("<span style='color:red'>这个是后台返回的值</span>"); // 返回给前台一个String的类型
            loopVars[1] = new StringArraySequence(new String[]{"张三", "李四", "王五"});         // 返回给前台一个Sequence类型
        }
        // 4.判断用户是否拥有这个权限
        if (list.contains(auth.getAsString())) {
            log.info("拥有权限就输出显示 AuthDirective-execute");
            // 显示指令包含的中间的内容
            body.render(env.getOut());
        }else{
            log.info("没有权限不显示 AuthDirective-execute");
        }
    }
}

二、注册标签


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @describe FreeMarker初始化配置
 *
 */
@Log4j2
@Data
@Configuration
@NoArgsConstructor
@AllArgsConstructor
public class FreeMarkerConfig implements InitializingBean {
	
	@Resource
	private freemarker.template.Configuration configuration;

	@Bean
	public AuthDirective authDirective() {
		return new AuthDirective();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		configuration.setSharedVariable("auth", authDirective());
	}
}

三、使用标签(其中的auth值为传到服务端进行匹配用的)

<@auth auth="03";loopVar01,loopVar02>
					我可以出来,获取到后台返回${loopVar01}<br/>
					<#list loopVar02 as loop>
						per : ${loop_index}-${loop}
					</#list>
				</@auth>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 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 标签了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值