读书人

freemaker示范

发布时间: 2012-10-14 14:55:08 作者: rapoo

freemaker示例

??? 在WebService的项目中,要求与客户交互传输些信息,首先需要转换系统生成的request请求信息,发现先使用freemaker模板来处理XML很方便,最后通过SOAP传输。freemaker的官方网址:http://freemarker.sourceforge.net/index.html 。附近提供是 freemarker-2.3.15.jar 。下面是使用freemaker的示例代码:

?

1.JAVA代码

?

package freemaker;import java.io.IOException;import java.io.StringWriter;import java.util.HashMap;import java.util.List;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.DefaultObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateException;import freemarker.template.TemplateMethodModel;import freemarker.template.TemplateModelException;public class TestFreemaker {/** * @param sukyl */public static void main(String[] args) {//配置对象Configuration cfg = new Configuration();cfg.setObjectWrapper(new DefaultObjectWrapper());try {//得到模板对象Template temp = cfg.getTemplate("test.ftl");//合并模板和数据模型Map<String,Object> context = new HashMap<String,Object>();context.put("agentId", "0000");context.put("getPlanType", new TemplateMethodModel(){@Overridepublic Object exec(List arg0) throws TemplateModelException {String planType = (String)arg0.get(0); if ("1".equals(planType)) return "VISION";        if ("4".equals(planType)) return "DENTAL";        return "MEDICAL";}});StringWriter writer = new StringWriter();try {temp.process(context, writer);System.out.println(writer.toString());} catch (TemplateException e) {e.printStackTrace();}} catch (IOException e) {e.printStackTrace();}}}
?

2.对应的ftl文件

?

<AgtID>${agentId}</AgtID>
<#assign plan_type = getPlanType(1!)>
<Rq mlob="${plan_type}"/>

?

3.运行输出:

?

<AgtID>0000</AgtID>
<Rq mlob="VISION"/>

?

?

?

?

读书人网 >软件架构设计

热点推荐