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部分,自行忽略


  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值