free marker之模板使用,

本文介绍了FreeMarker模板引擎的使用,不仅限于转换FTL文件生成HTML,还展示了其在处理XML模板以生成XML文件的能力。通过代码示例,展现了FreeMarker的灵活性和广泛的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的思维停留在,使用freemarker来将.ftl文件生成静态html页面。今天用到了,来读取xml模板,并生成xml模板。

上代码:

package xxx;

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

public freemarkerTest class {

    /** 随着类加载而加载的静态代码块 */
    static {
        //freemarker的配置类
        Configuration configuration = new Configuration();
        //因为是springBoot项目,指定模板在templates路径下
        configuration.setClassForTemplateLoading(configuration.getClass(), "/templates");
        try {
            //获取模板类
            TEMPLATE = configuration.getTemplate("/freemarker.xml", "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.warn("模板加载解析异常:" + e);
        }
    }

    
    //生成xml
    public void createXML(){
        //给定xml文件输出路径
        Writer writer = new FileWriter("E:/demo.xml");
        
        //按照用法,来个map集合
        Map<String, String> map = new HashMap<String, String>();
        map.put("guid","GIHIHO-OJUYU-HKOO";
        map.put("version","1.0.0");
        map.put("hello","hello freemarker");

        //调用process方法
        TEMPLATE.process(map,writer);
    }

}
//模板xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ceb:CEB511Message guid="${guid}" version="${version}"  xmlns:ceb="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <ceb:Logistics>
      <ceb:LogisticsHead>
         <ceb:guid>${guid}</ceb:guid>
         <ceb:appType>${hello}</ceb:appType>
      </ceb:LogisticsHead>
   </ceb:Logistics>
</ceb:CEB511Message>
//结果xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ceb:CEB511Message guid="GIHIHO-OJUYU-HKOO" version="1.0.0"  xmlns:ceb="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <ceb:Logistics>
      <ceb:LogisticsHead>
         <ceb:guid>GIHIHO-OJUYU-HKOO</ceb:guid>
         <ceb:appType>hello freemarker</ceb:appType>
      </ceb:LogisticsHead>
   </ceb:Logistics>
</ceb:CEB511Message>

freemarker不仅可以转换ftl文件,还可以转换xml,jsp文件

小小手掌,大大力量,小小工具,大大场景,

欢迎指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值