freemarker用字符串构建模版

 

代码:

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class StringTemplateLoader implements TemplateLoader {

	private String template;

	public StringTemplateLoader(String template) {
		this.template = template;
		if (template == null) {
			this.template = "";
		}
	}

	public Object findTemplateSource(String name) throws IOException {
		return new StringReader(template);
	}

	@Override
	public long getLastModified(Object templateSource) {
		return 0;
	}

	public Reader getReader(Object templateSource, String encoding)
			throws IOException {
		return (Reader) templateSource;
	}

	public void closeTemplateSource(Object templateSource) throws IOException {
		((StringReader) templateSource).close();
	}

	public static void main(String[] args) throws Exception {
        Configuration cfg = new Configuration();
        cfg.setTemplateLoader(new StringTemplateLoader("..Hello,${user}!"));
        Map root = new HashMap();
        root.put("user", "Jack");
        StringWriter writer = new StringWriter();

        long start = System.currentTimeMillis();

        Template template = cfg.getTemplate("");
        template.process(root, writer);

        System.out.println(System.currentTimeMillis() - start);
        System.out.println(writer.toString());
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值