自定义freemarker标签实现TemplateDirectiveModel时获取request

1 篇文章 0 订阅
1 篇文章 0 订阅

  1: 使用spring freemarker 3 起的话,可以使用

 @Autowired
    private HttpServletRequest request;

2:

使用: ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

在web.xml添加监听器:

<span style="white-space:pre"></span><pre name="code" class="html"><span style="white-space:pre">	</span><listener>
		<listener-class>
			org.springframework.web.context.request.RequestContextListener
		</listener-class>
	</listener>

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 使用 Freemarker 模板引擎,可以通过自定义标签实现一些常用的功能。下面介绍如何自定义一个列表标签。 首先,创建一个类,实现 `freemarker.template.TemplateDirectiveModel` 接口。这个接口只有一个方法 `execute`,需要在其实现自定义标签的逻辑。例如: ``` import java.io.IOException; import java.util.Map; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; public class CustomListDirective implements TemplateDirectiveModel { @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // 获取参数 String items = params.get("items").toString(); String separator = params.get("separator").toString(); // 分割字符串,生成列表 String[] itemList = items.split(","); StringBuilder result = new StringBuilder(); for (String item : itemList) { result.append(item).append(separator); } // 输出结果 env.getOut().write(result.toString()); } } ``` 这个类实现了一个简单的列表标签,根据传入的参数 `items` 和 `separator`,将 `items` 字符串按照 `separator` 分割生成列表,并输出。 接着,在 Spring Boot 的配置类注册这个自定义标签: ``` import java.util.HashMap; import java.util.Map; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import freemarker.template.Configuration; import freemarker.template.TemplateDirectiveModel; @Configuration public class FreemarkerConfig { @Bean public Configuration freemarkerConfig() { Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); configuration.setClassForTemplateLoading(this.getClass(), "/templates"); // 注册自定义标签 Map<String, TemplateDirectiveModel> directives = new HashMap<>(); directives.put("customList", new CustomListDirective()); configuration.setSharedVariable("directives", directives); return configuration; } } ``` 这里将自定义标签注册到了 `Configuration` ,然后在模板使用 `<@directives.customList items="a,b,c" separator="-" />` 的方式调用即可。 需要注意的是,在模板使用自定义标签需要加上 `@` 符号,例如 `<@directives.customList ... />`。另外,`directives` 名称可以自定义,只要与 `freemarkerConfig` 设置的名称一致即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值