freemarker简介和入门使用

一.freemarker简介 

 二.使用入门

  》使用freemaker写代码前,准备号模板文件,它的作用跟jsp差不多,可以理解为现有的文本+el表达式;格式没有任何要求,但是freemarker默认的格式是ftl,但我准备的是html文件作为模板

   》正式进入代码部分:书写入门步骤大致分为8步:

    1.创建configuration对象,该对象用于加载模板文件和设置文本编码

    2.设置文本编码

    3.指定模板文件所在的目录路径

    4.指定模板文件,并生成模板对象

    5.准备数据集,最好是map

    6.准备一个字符流足够,比如fileWriter,用于输出最终生成的文本文件,文件的后缀可以自己指定,html,css,js,java,xml等待都可以

    7.根据数据集和字符流,执行生成文本文件的proceess方法

    8.关闭流

    @Test
    public void testFreeMarker() throws Exception {
        
        //1。创建模板文件(手动创建,无需编码)
        
        //2.创建configuration:用于加载模板文件和设置编码
        Configuration configuration = new Configuration(Configuration.getVersion());
        
        //3.设置编码
        configuration.setDefaultEncoding("utf-8");
        
        //4.设置模板文件所在目录路径
        File file = new File("D:\eclipse-workspace-javaee\e3-item-web\src\main\webapp\WEB-INF");
        configuration.setDirectoryForTemplateLoading(file);
        
        //5.指定要加载模板文件,生成模板对象
        Template template = configuration.getTemplate("freemarker.html");
        
        //6.准备数据集,可以是map
        HashMap<String, String> map = new HashMap<String,String>();
        
        map.put("hello", "hello world");
        
        //7.准备字符流:writer,用于输出最终的文本文件(可以指定输出的文本文件的后缀)
        FileWriter writer = new FileWriter("D:\eclipse-workspace-javaee\e3-item-web\src\main\webapp\WEB-INF\fm.html");
        
        //8.执行模板并生成文本文件
        template.process(map, writer);
        
        //9.关闭流
        writer.close();
        
    }

  》生成的fm.html如下:

原文地址:https://www.cnblogs.com/ibcdwx/p/13553893.html