日期:2014-05-16  浏览次数:20592 次

利用freemarker做html页面静态化

背景:

对实时性要求不高的网站需要静态化操作,那么我们基于freemarker做静态化处理

环境:

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.20</version>
</dependency>
<dependency>
	<groupId>commons-logging</groupId>
	<artifactId>commons-logging</artifactId>
	<version>1.1.1</version>
</dependency>

代码实现:

模板文件:news.ftl

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  
  <head>
    <title>
      ${article.title!}
    </title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!-- <link rel="stylesheet" type="text/css" href="styles.css">  
    -->
  </head>
  
  <body>
    <h2>
      ${article.title!}
    </h2>
    <hr/>
    <pre>
      ${article.content}
    </pre>
  </body>
</html>

Java封装类Article:

public class Article  implements Serializable{
	private static final long serialVersionUID = 554206256994693476L;
	private String title;
	private String content;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}

注意:此类必须为public否则报freemarker.core.InvalidReferenceException

测试实现:

public static void main(String[] ar) throws Exception, TemplateException {
	Configuration configuration = new Configuration();
	configuration.setEncoding(Locale.getDefault(), "UTF-8");
	TemplateLoader templateLoader = new FileTemplateLoader(new File("d:/"));
	configuration.setTemplateLoader(templateLoader);
	Template template = configuration.getTemplate("news.ftl");
	template.setEncoding("UTF-8");
	File file = new File("d:/news.html");
	Map<String, Article> rootMap = new HashMap<String, Article>();
	Article article = new Article();
	article.setTitle("关于小网客");
	article.setContent("解决方案咨询<br>大数据处理<br>系统架构<br>企业信息化咨询<br>Email:smallnetvisitor@qq.com<br>来自北京");
	rootMap.put("article", article);
	Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

	template.process(rootMap, out);
}

?

说明:

此处采用了FileTemplateLoader,以D盘为根,写的html页面采用utf-8的编码

结果如下图:

?

?

?