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

}
posted @ 2013-04-11 13:03  lifeng_study  阅读(670)  评论(0编辑  收藏  举报