通过FreeMarker的Java api生成网页模板 - Go语言中文社区

通过FreeMarker的Java api生成网页模板


摘自freemarker官网,增加了自己的注释和改动,简单复制和翻译了官网的代码注释,后面有自己根据需要简单改动过的代码。
官网链接为freemarker官网quick start页

第一步,创建freemarker配置,应用的生命周期中只要配置一次;

// 创建配置,有特殊需求要指定版本,细节查看java文档
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);

// 指定模板文件地址
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));

// 指定文字编码
cfg.setDefaultEncoding("UTF-8");

// 错误说明的设置,在网页上则 *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER更好
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

// 不要设置freemarker内部Log,有错误总会看到的
cfg.setLogTemplateExceptions(false);

//将不在范围内的exception指定给TemplateException处理
cfg.setWrapUncheckedExceptions(true);

第二步,创建数据模型;

// 一般数据模型是map格式,也可以是JavaBean
Map<String, Object> root = new HashMap<>();

// 填充数据到模型里
root.put("user", "Big Joe");

// 这里的Product是一个JavaBean,一个类,MVC中的Model,我这不放代码
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
// 将Bean填充到模型中
root.put("latestProduct", latest);

第三步,获取模板;

Template temp = cfg.getTemplate("test.ftlh");

第四步,融合模板和数据模型;

Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);

最后将代码合在一起,代码太多不放了。

官网代码较少,注释较多,放上我的代码;
新建了一个FreeMarkerUtil类,可以根据模板和数据生成的FreeMarker模板,以字符串格式返回;

import freemarker.template.*;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @description: Freemarker工具类
 * @author: lyc
 * @create: 2018-06-04
 **/
public class FreemarkerUtil {

    /**
     * 生成要发送的文件的字符串,摘自官网
     * @param fltFile freemarker模板文件
     * @param templatePath freemarker模板文件夹地址
     * @param datas 写进模板的数据
     * @return String格式的模板
     */
    public static String geneFileStr(String fltFile,String templatePath,Map<String, Object> datas){
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
        try {
            cfg.setDirectoryForTemplateLoading(new File(templatePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        Template temp = null;
        StringWriter out = null;
        try {
            temp = cfg.getTemplate(fltFile);
            out = new StringWriter();
            temp.process(datas, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (TemplateException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return out.getBuffer().toString();

    }

}

模板文件地址为
这里写图片描述

模板内容如图,需要填充的是${username}

你好${username},你的登陆有问题!

最后简单测试,将lyc填充到username中,输出生成的字符串,看是否符合要求;

@Test
    public void geneFileStr() {
        Map<String, Object> data = new HashMap();
        data.put("username","lyc");
        System.out.println(FreemarkerUtil.geneFileStr("login_exception.html","src/main/resources/templates/mails",data));
    }

测试结果为
这里写图片描述
测试通过,没有问题。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/steveliu13/article/details/80587547
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 20:02:04
  • 阅读 ( 1430 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢