freemarker生成静态页面

1.概述

今天尝试将网站首页静态化,使用的freemarker,用ftl文件作为模板,传入从数据库中查询的数据。

2,代码

public static boolean createHTML(ServletContext context,
			Map<String, Object> data, String templatePath, String targetHtmlPath) {
		Configuration freemarkerCfg = new Configuration();
		// 加载模版
		freemarkerCfg.setServletContextForTemplateLoading(context, "/");
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
		freemarkerCfg.setNumberFormat("0.######");
		try {
			// 指定模版路径
			Template template = freemarkerCfg
					.getTemplate(templatePath, "UTF-8");
			template.setEncoding("UTF-8");
			// 静态页面路径
			String htmlPath = context.getRealPath("/templates/shop/html/") + "/"
					+ targetHtmlPath;
			File htmlFile = new File(htmlPath);
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版
			template.process(data, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			
			e.printStackTrace();
			return false;
		}
		return true;

	}

注意:1,参数ServletContext context,servlet上下文,在spring中获得方式:

WebApplicationContext webApplicationContext = ContextLoader
				.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext
				.getServletContext();

2,参数Map<String, Object> data 数据

3,参数templatePath:模板文件路劲,targetHtmlPath生成文件路径

4,如果模板文件使用<#include "filepath">,找不到文件,可使用freemarkerCfg.setServletContextForTemplateLoading(context, setPath);设置模板文件加载路径。

最后的路经应该是setPath + filepath。

5,我在页面放入数字123456,静态化之后得到的是123,456,必须要设置freemarkerCfg.setNumberFormat("0.######");才能得到想要的结果。想必有其他解析结果显示问题,也可以通过设置cfg来解决。

6,ftl模板中有注释(<!-- -->)的时候生成错误,不能确定是什么原因




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值