美文网首页
freemarker简单用法

freemarker简单用法

作者: 夜阑人儿未静 | 来源:发表于2018-05-07 17:27 被阅读6次

1.引入jar包(pom)

<dependency>

<groupId> freemarker</groupId>

<artifactId> freemarker </artifactId>

<version>2.3.19</version>

2.准备html模板(此处指粘贴部分)

3.撸代码

//替换参数

Map map =new HashMap();

map.put("title",record.getTitle());

map.put("summary", record.getSummary());

map.put("url", record.getUrl());//链接

map.put("coverImgUrl",faviconIco);

map.put("ideaForwardId",record.getId());

Configuration configuration =new Configuration();

configuration.setDirectoryForTemplateLoading(new File(templatePath));//此文件为上文贴出模板

configuration.setObjectWrapper(new DefaultObjectWrapper());

configuration.setDefaultEncoding("utf-8");

Template template = configuration.getTemplate("forwardTemplate.html", "UTF-8");

template.setEncoding("UTF-8");

String path =new StringBuilder(localForwardHtml).append(md5).append("/index.html").toString();

File file =new File(path);

if (!file.exists()) {

FileUtil.createFile(path);//创建新文件

}

Writer writer =new OutputStreamWriter(new FileOutputStream(new File(path)), "utf-8");

template.process(param, writer);//替换参数

writer.flush();

writer.close();

注:模板中替换参数后加“!”是站位符,防止传入参数为空报错!

相关文章

网友评论

      本文标题:freemarker简单用法

      本文链接:https://www.haomeiwen.com/subject/ujhahftx.html