freemarker静态化关键在于public void process(Object dataModel, Writer out) 方法。
演示环境:springMVC+spring
在spring中注入freemarker配置
<bean id="freeMarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="/WEB-INF"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">10</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="boolean_format">true,false</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.##</prop>
<prop key="whitespace_stripping">true</prop>
</props>
</property>
</bean>
/**
* freemarker静态化示例
*/
@RequestMapping("freemarkerStatic")
public void freemarkerStatic()
{
String templatePath = "d:/file.html";//静态化页面输出路径
Map<String, String> staticDatas = new HashMap<String, String>();//待静态化数据
staticDatas.put("title", "freemarker静态化示例");
staticDatas.put("name", "小明");
staticDatas.put("act", "说");
staticDatas.put("content", "这是freemarker静态化的一个简单实例");
Configuration cfg = freeMarkerConfigurer.getConfiguration();//得到静态化配置
try
{
Template template = cfg.getTemplate("demo.ftl");//得到模板(Configuration中配置为WEB-INF根目录下)
File file = new File(templatePath);
Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");//包装文件输入流为输出流
template.process(staticDatas, out);//静态化关键方法
IOUtils.closeQuietly(out);//关闭输出流
}
catch (TemplateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
运行截图,可以在d盘下找到file.html文件
页面内容为
来源:oschina
链接:https://my.oschina.net/u/2494581/blog/686986