目錄:html
一.freemaker介紹java
二.freemaker的使用web
正文:spring
一.freemaker介紹apache
1.1FreeMarker概述:FreeMarker是一款模板引擎,即一種基於模板和要改變的數據,並用來生成輸出文本(HTML網頁,電子郵件,配置文件,源代碼等)的通用工具。api
1.2得到FreeMarker服務器
中文幫助文檔:https://sourceforge.net/projects/freemarker/files/chinese-manual/app
下載FreeMarker jar包:下載地址http://freemarker.org/freemarkerdownload.htmlwebapp
中文網:http://freemarker.foofun.cn/
使用Maven依賴jar包:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker-gae</artifactId> <version>2.3.25-incubating</version> </dependency>
二.FreeMarker的使用
這裏沒有使用MVC,只需依賴FreeMarker、Servlet與JSP核心包就能夠了,修改後的pom.xml文件以下。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhangguo</groupId> <artifactId>SpringMVC71</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- FreeMarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker-gae</artifactId> <version>2.3.25-incubating</version> </dependency> <!-- Servlet核心包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!--JSP --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> </dependencies> </project>
依賴成功的結果:
在src/main/java源代碼目錄下建立Article.java文件,該類表明文章,代碼以下:
package com.zhangguo.springmvc71.entities; /** * 文章 * */ public class Article { /* * 編號 */ private int id; /* * 標題 */ private String title; /* * 內容 */ private String content; public Article() { } public Article(int id, String title, String content) { super(); this.id = id; this.title = title; this.content = content; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } @Override public String toString() { return "Article [id=" + id + ", title=" + title + ", content=" + content + "]"; } }
在src/main/java源代碼目錄下建立ArticleService.java文件,該類表明文章業務,主要提供文章數據,定義了一個文章集合中,初始化時向集合中隨意添加了5個文章對象,代碼以下:
package com.zhangguo.springmvc71.Services; import java.util.ArrayList; import java.util.List; import com.zhangguo.springmvc71.entities.Article; /** * 文章業務類(模擬) * */ public class ArticleService { private static List<Article> articles; static { articles = new ArrayList<Article>(); articles.add(new Article(20160701, "不明真相的美國人被UFO驚呆了 實際上是長征7號","據美國《洛杉磯時報》報道,當地時間週三晚(北京時間週四),在美國中西部的猶他州、內華達州、加利福利亞州,數千人被劃過夜空的神祕火球嚇到")); articles.add(new Article(20160702, "法國巴黎聖母院爲教堂恐襲案遇害神父舉行大彌撒", "而據美國戰略司令部證明,其實這是中國長征七號火箭從新進入大氣層,恰好通過加利福利亞附近。")); articles.add(new Article(20160703, "日東京知事候選人小池百合子回擊石原:濃妝能夠", "然而昨晚的美國人民可不明真相,有些人甚至懷疑這些火球是飛機解體,還有些人猜想是流星雨。")); articles.add(new Article(20160704, "日資慰安婦基金在首爾成立 韓國示威者闖入抗議","美國戰略司令部發言人表示,到目前爲止尚未任何受損報告,他說相似物體一般在大氣中就會消失,這也解釋了爲什麼出現一道道光痕,這一切都並未形成什麼威脅。")); articles.add(new Article(20160705, "中日關係正處十字路口日應尋求減小與華衝突","中國長征七號火箭6月25日在海南文昌航天發射中心首次發射,併成功升空進入軌道。有學者指出長征七號第二級火箭一直在地球低軌運行,一個月後從新進入大氣層。")); } /** * 全部的文章 */ public List<Article> getArticles() { return articles; } /* * 得到文章經過文章編號 */ public Article getArticle(int id) { for (Article article : articles) { if (article.getId() == id) { return article; } } return null; } }
在src/main/java源代碼目錄的templates包下添加兩個模板,一個名爲newsList.ftl用於生成新聞列表,另外一個名爲news.ftl用於生成單篇新聞,newsList.ftl文件內容以下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>新聞焦點</title> </head> <body> <div id="container"> <h2>新聞焦點</h2> <#setting number_format="#"> <ul> <#list articles as article> <li> <a href="news/${article.id}.html">${article.title}</a> </li> </#list> </ul> </div> <style> #container{ font-family:"microsoft yahei"; width:800px; margin:0 auto; } a{ color:#333; text-decoration:none; } li{ height:26px; line-height:26px; } </style> </body> </html>
文件中使用了FreeMarker標記,具體語法能夠看第四點;news.ftl文件內容以下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>${article.title}</title> </head> <body> <div id="container"> <h2>${article.title}</h2> <p> ${article.content} </p> </div> <style> #container{ font-family:"microsoft yahei"; width:800px; margin:0 auto; } </style> </body> </html>
新增一個名爲News的Servlet類,當Servlet收到客戶端請求時會查看系統中是否存在index.html(新聞列表)靜態頁面,若是存在直接轉發,若是不存在則生成新聞列表靜態頁面及子頁面。建立好的Servlet代碼以下所示:
package com.zhangguo.springmvc71.actions; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zhangguo.springmvc71.Services.ArticleService; import com.zhangguo.springmvc71.entities.Article; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** *新聞列表 */ @WebServlet("/News") public class News extends HttpServlet { private static final long serialVersionUID = 1L; ArticleService articleService=new ArticleService(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ //設置編碼格式與MIME類型 response.setContentType("text/html; charset=UTF-8"); //首頁新聞列表路徑 String indexPath=request.getServletContext().getRealPath("/index.html"); //文件是否存在 File file=new File(indexPath); if(!file.exists()){ //若是新聞列表不存在,生成新聞列表 //建立一個freemarker.template.Configuration實例,它是存儲 FreeMarker 應用級設置的核心部分 //指定版本號 Configuration cfg=new Configuration(Configuration.VERSION_2_3_22); //得到模板文件路徑 String templatePath=this.getClass().getClassLoader().getResource("/templates").getPath(); //設置模板目錄 cfg.setDirectoryForTemplateLoading(new File(templatePath)); //設置默認編碼格式 cfg.setDefaultEncoding("UTF-8"); //數據 Map<String, Object> articleData = new HashMap<>(); List<Article> articles=articleService.getArticles(); articleData.put("articles", articles); //從設置的目錄中得到模板 Template template = cfg.getTemplate("newsList.ftl"); //合併模板和數據模型 try { //將數據與模板渲染的結果寫入文件中 Writer writer=new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); template.process(articleData, writer); writer.flush(); articleData.clear(); template = cfg.getTemplate("news.ftl"); //生成單個新聞文件 for (Article article : articles) { articleData.put("article", article); //單個新聞文件 file=new File(request.getServletContext().getRealPath("/news/"+article.getId()+".html")); //文件輸出流寫入器 writer=new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); //將模板+數據生成的結果寫入文件中,獲得一個靜態文件 template.process(articleData, writer); writer.flush(); } writer.close(); } catch (TemplateException e) { e.printStackTrace(); } } //若是新聞單頁下存在,生成新聞單頁 request.getRequestDispatcher("index.html").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
從代碼中能夠看出生成的單篇文章所有存放在news目錄下,要記得在webapp根目錄下建立news目錄。這裏只是示例代碼,若是要在項目中應用,應該把FreeMarker,文件操做的內容分Servlet分開。另外web.xml文件中添加index.html爲第1個歡迎頁,這樣作的目的是當首頁被生成時直接讓服務器響應index.html。web.xml文件以下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
index.jsp直接轉發到News Servlet中,文件內容以下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <jsp:forward page="News"></jsp:forward>