Struts2、Spring、Freemarker自定义标签

1.继承FreemarkerManager重写createConfiguration方法

package com.rx.freemarker;

import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import freemarker.template.Configuration;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;

public class MyFreemarkerManager extends FreemarkerManager {

@Override
protected Configuration createConfiguration(ServletContext servletContext)
throws TemplateException {
Configuration configuration = super.createConfiguration(servletContext);

// 设置标签类型([]、<>),[]这种标记解析要快些
configuration.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);

// 取出上下文
ApplicationContext applicationContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(servletContext);

// 获取实现TemplateDirectiveModel的bean
Map<String, Object> beans = applicationContext
.getBeansOfType(TemplateDirectiveModel.class);

for (String key : beans.keySet()) {
Object obj = beans.get(key);
if (obj != null && obj instanceof TemplateDirectiveModel) {
configuration.setSharedVariable(key, obj);
}
}

return configuration;
}

}

2.在struts.properties中配置自定义管理类

struts.freemarker.manager.classname=com.rx.freemarker.MyFreemarkerManager

3.自定义标签

package com.rx.freemarker;

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

import org.springframework.stereotype.Component;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Component("ranks")
public class RanksTemplateDirectiveModel implements TemplateDirectiveModel {

public void execute(Environment environment, Map map,
TemplateModel[] atemplatemodel,
TemplateDirectiveBody templatedirectivebody)
throws TemplateException, IOException {
environment.setVariable("ranks", ObjectWrapper.DEFAULT_WRAPPER
.wrap(getRanks()));
templatedirectivebody.render(environment.getOut());
}

private List<String> getRanks() {
List<String> list = new ArrayList<String>();

list.add("第一名");
list.add("第二名");
list.add("第三名");
list.add("第四名");
list.add("第五名");
list.add("第六名");
list.add("第七名");
list.add("第八名");
list.add("第九名");
list.add("第十名");

return list;
}

}

4.模板

[@ranks]
[#list ranks as rank]
${rank}
[/#list]
[/@ranks]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值