freemarker实现动态生成内容

 

Freemarker作为一款非常优秀的模版框架,struts2默认集成,配置返回resulttype属性为freemarker,即将该返回的表现层指定为freemarker模版文件后缀为.ftl

当然,freemarker的魅力远远不止表现在这。

 

比如在实际开发中,会有各种各样的报文,假如报文的格式如下:

<?xml version="1.0" encoding="utf-8"?>

<commands>

<command>Im index on 0</command>

<command>Im index on 1</command>

<command>Im index on 2</command>

<command>Im index on 3</command>

<command>Im index on 4</command>

<command>Im index on 5</command>

<command>Im index on 6</command>

<command>Im index on 7</command>

<command>Im index on 8</command>

<command>Im index on 9</command>

</commands>

 

我们可以通过freemaker的api动态的生成我们想要的报文,只需要把原料给它,它就能给我们想要的东西,当然这也是模版框架意义.

下面给出代码:



package com.zhl.modules.fk.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateUtils {
	public static String mergeTemplateContent(Map<String, List<String>> values,String ftl){
		//定义字节数组输出流
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		//这是配置的核心类
		Configuration config = new Configuration();
		try {
			//设置模版存放目录
			config.setDirectoryForTemplateLoading(new File("WebContent/ftls"));
			//模版类
			Template tp = config.getTemplate(ftl+".ftl");
			//将变量与模版合并,并将合并后的内容给输出流
			tp.process(values, new OutputStreamWriter(output));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		//返回输出流的字符串形式
		return output.toString();
	}
	
	public static void main(String[] args) {
		Map<String, List<String>> values = new HashMap<String, List<String>>();
		List<String> vals = new ArrayList<String>();
		for(int i = 0;i<10;i++){
			vals.add("Im index on "+i);
		}
		values.put("aValue", vals);
		//将最终结果打印出来
		System.out.println(mergeTemplateContent(values, "form"));
	}
}

模版文件form.ftl内容:

<?xml version="1.0" encoding="utf-8"?>

<commands>

<#list aValue as cm>

<command>${cm}</command>

</#list>

</commands>

 

 

执行我们的程序:

工程目录:

关于struts2部分,自行忽略



版权声明:本文为sky54bc原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。