文章目录
freemarker获取html模板进行渲染输出
应用场景
1、获取html文件内容进行模板解析,返回到页面展示
2、获取html文件内容进行模板解析,进行邮件发送
3、获取xml文件内容进行模板接卸,生成office办公文件,达到apache poi的效果
一些class引用官方demo,当做测试。
maven工程配置引入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
创建获取模板测试类
package test.freemarker;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
/**
* @author yunfeng
* @version V.1.0
* @title
* @Desc
* @create 2018-05-14 22:49
**/
public class TestFm {
@Test
public void test() throws IOException {
/* ------------------------------------------------------------------------ */
/* You should do this ONLY ONCE in the whole application life-cycle: */
/* Create and adjust the configuration singleton */
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
cfg.setDirectoryForTemplateLoading(new File("d:/freemarker/templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
/* ------------------------------------------------------------------------ */
/* You usually do these for MULTIPLE TIMES in the application life-cycle: */
/* Create a data-model */
Map root = new HashMap();
root.put("user", "Big Joe");
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
root.put("latestProduct", latest);
/* Get the template (uses cache internally) */
Template temp = cfg.getTemplate("test.ftlh");
/* Merge data-model with template */
Writer out = new OutputStreamWriter(System.out);
try {
temp.process(root, out);
} catch (TemplateException e) {
e.printStackTrace();
}
// Note: Depending on what `out` is, you may need to call `out.close()`.
// This is usually the case for file output, but not for servlet output.
}
}
Product类
package test.freemarker;
/**
* @author yunfeng
* @version V.1.0
* @title
* @Desc
* @create 2018-05-14 22:51
**/
public class Product {
private String url;
private String name;
// As per the JavaBeans spec., this defines the "url" bean property
// It must be public!
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
// As per the JavaBean spec., this defines the "name" bean property
// It must be public!
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
执行输出
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>
Freemarker相应工具类FreemarkerUtil
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
/**
* @author yunfeng
* @version V1.0
* @date 2018-05-24 22:55
*/
public class FreemarkerUtil {
private final static Logger logger = LoggerFactory.getLogger(QuartzUtils.class);
/**
* 获取模板内容
*
* @param template 模板文件
* @param map 模板参数
* @return 渲染后的模板内容
* @throws IOException IOException
* @throws TemplateException TemplateException
*/
public static String getTemplate(String template, Map map) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
String templatePath = FreemarkerUtil.class.getResource("/").getPath();
logger.info("FreemarkerUtil template = " + template);
logger.debug("templatePath = " + templatePath);
cfg.setDirectoryForTemplateLoading(new File(templatePath));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
Template temp = cfg.getTemplate(template);
StringWriter stringWriter = new StringWriter();
temp.process(map, stringWriter);
return stringWriter.toString();
}
}
总结
然后项目中通过调用FreemarkerUtil .getTemplate(String template, Map map)即可返回对应渲染模板内容。也可以用其他模板框架去渲染页面jsonup
注意事项
- Configuration缓存 Template实例,所以当你cfg.getTemplate(“test.ftlh”)下次调用 时,它可能不会再读取和解析模板文件,只是Template第一次返回相同的 实例。
- 不要不必要地重新创建Configuration 实例; 创建很消耗性能,而且会失去了模板缓存。Configuration实例应当作为应用程序级别的单例。