Freemarker模板文件返回字符串

首先,先创建一个ftl文件:
<div style="width:100%;font-size:12px;">Hello ${name}(${getUserAge(name)})</div>

之后,创建一个java应用程序类:

package freemarker;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

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

/**
*
* @Desc 获取FTL文件生成的字符串,以供调用
* @author xujp1
* @version Revision: 1.00 Date: May 9, 2012
*/
public class GenerateStringFromFtl
{

private static Configuration conf = null;

public static void main(String args[])
{
conf = new Configuration();
try
{
conf.setDirectoryForTemplateLoading(new File("WebRoot/WEB-INF/template"));
}
catch (IOException e)
{
e.printStackTrace();
}
conf.setObjectWrapper(new DefaultObjectWrapper());
conf.setLocale(Locale.CHINA);
conf.setSharedVariable("getUserAge", new GetUserAge());//自定义方法供调用
conf.setDefaultEncoding("utf-8");
conf.setClassicCompatible(true);//处理空值为空字符串
String tempReturn = "";
Map<String, Object> root = new HashMap<String, Object>();
String name = "xujp1";
root.put("name", name);
try
{
tempReturn = generateHtmlFromFtl(root, "hellouser.ftl");
}
catch (IOException e)
{
e.printStackTrace();
}
catch (TemplateException e)
{
e.printStackTrace();
}
System.out.println(tempReturn);
}

public static String generateHtmlFromFtl(Object root, String tempPath) throws IOException, TemplateException
{
Template temp = conf.getTemplate(tempPath);
Writer out = new StringWriter(2048);
temp.process(root, out);
return out.toString();
}
}

由于有用到自定义方法,因此在建个方法类:

package freemarker;

import java.util.List;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
*
* @Desc freemarker中使用的方法,根据传入的参数返回相应的值
* @author xujp1
* @version Revision: 1.00 Date: May 9, 2012
*/
public class GetUserAge implements TemplateMethodModel
{

/* (non-Javadoc)
* @see freemarker.template.TemplateMethodModel#exec(java.util.List)
*/
@SuppressWarnings("unchecked")
@Override
public Object exec(List args) throws TemplateModelException
{
if(args.size() != 1)
{
throw new TemplateModelException("Wrong arguments!");
}
int age = 0;
if("xujp1".equalsIgnoreCase((String)args.get(0)))
age = 25;
else
age = 24;
return new SimpleScalar(String.valueOf(age));
}
}

运行后,得到所要的结果
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值