背景:
對實時性要求不高的網站需要靜態化操作,那么我們基于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的編碼
結果如下圖:
?
?
?