freemaker模板引擎使用详解
目錄:
一.freemaker介紹
二.freemaker的使用
?
正文:
一.freemaker介紹
1.1FreeMarker概述:FreeMarker是一款模板引擎,即一種基于模板和要改變的數據,并用來生成輸出文本(HTML網頁,電子郵件,配置文件,源代碼等)的通用工具。
?
1.2獲得FreeMarker
官網:http://freemarker.org/
中文幫助文檔:https://sourceforge.net/projects/freemarker/files/chinese-manual/
下載FreeMarker jar包:下載地址http://freemarker.org/freemarkerdownload.html
中文網:http://freemarker.foofun.cn/
使用Maven依賴jar包:
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker-gae</artifactId><version>2.3.25-incubating</version> </dependency>二.FreeMarker的使用
?
2.1、新建一個基于Maven的Web項目
?
2.2、添加依賴
這里沒有使用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>依賴成功的結果:
2.3、創建文章POJO類
在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;}@Overridepublic String toString() {return "Article [id=" + id + ", title=" + title + ", content=" + content + "]";} }2.4、創建文章業務類
在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;} }2.5、添加模板
在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>2.6、添加Servlet生成靜態頁
新增一個名為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>2.7、運行結果
?
轉載于:https://www.cnblogs.com/zjl6/p/9447937.html
總結
以上是生活随笔為你收集整理的freemaker模板引擎使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手眼标定(一)
- 下一篇: ubutun 因为端口冲突引起安装ngi