這篇文章介紹Freemarker最核心的功能,或者說它的出現是用來解決什麼問題的。在第一篇提到了Freemarker是一種模板語言,那麼什麼叫做模板語言呢。
自己也是接觸沒多久就在網上搜了搜資料,下面是我搜到的一篇介紹Java模板技術的博客覺得寫的聽清楚的,覺得我想知道的關於模板的知識,這篇博客中基本上都講到了,有興趣的可以看看:http://blog.csdn.net/logic_202/article/details/573850。
我簡單的總結一下我理解的模板語言,從本質上講他就是一個佔位符動態替換技術。而我們在web開發中經常使用的EL表達式,struts tablib等技術也是一種佔位符動態替換技術。但是Freemarker和他們卻有不同的地方,第一篇博客中提到了Freemarker是一種獨立的模板技術,他是脫離servlet容器獨立運行的,這一點與我們平時經常使用的jsp技術是不同的。Jsp必須依賴servlet容器纔可以運行,因爲jsp本質上就是servlet。使用jsp這種機制,向前臺傳送數據是通過request流中,而Freemarker中向前臺傳送數據只需要向頁面傳入一個POJO就行而不是request對象。
簡單瞭解模板語言之後就來實現一個例子吧!
1. 在MyEclipse上創建一個web項目,然後添加Freemarker的jar包; 在WebRoot文件夾下新建templates文件夾,用於存放需要輸出的頁面模板。
2. 編寫模板
新建名爲ftl的文件放到templates文件夾中,文件的內容如下所示。
(注意:如果創建文件之後文件報紅,可以使用如下的方式就可以消除)
3. 後臺代碼獲得數據
從上面的ftl文件中得出我們需要的數據有:${title},userList,${user.id},${user.name};那麼我們在後臺就需要傳遞給她這些佔位符上數據
FreeMarkerHandler類中的代碼:
package com.ftl;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.User;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerHandler extends HttpServlet {
private Configuration configuration = null; //解釋Configuration
//構造函數
public FreeMarkerHandler(){
//創建Configuration實例
configuration = new Configuration();
//輸出的數據默認的編碼類型
configuration.setDefaultEncoding("utf-8");
}
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
//---------------1.準備數據-----------------
//要填入的數據文件
Map dataMap = new HashMap();//解釋數據的容器
//添加數據
dataMap.put("title", "FreeMarker示例");
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setId("1");
user1.setName("小依");
User user2 = new User();
user2.setId("2");
user2.setName("小耳");
userList.add(user1);
userList.add(user2);
dataMap.put("userList", userList); //將數據放到Map中
//---------------------------------------
//---------------2.設置模板裝載的方法(有多種方法)-
//介紹兩種方法:
configuration.setServletContextForTemplateLoading(getServletContext(),"templates");
// configuration.setClassForTemplateLoading(this.getClass(),"/com/template");
//---------------------------------------
//----------------3.獲得模板----------------
//獲得需要裝載的模版
Template template = null;
try {
template = configuration.getTemplate("hello.ftl");
template.setEncoding("utf-8");
} catch (IOException e) {
e.printStackTrace();
}
//---------------------------------------
//--------------4.開始準備生成輸出--------------
//使用模版文件的charset作爲本頁面的charset
//使用text/html MIME-type
response.setContentType("text/html; charset=" + template.getEncoding());
PrintWriter out = response.getWriter();
//合併數據模型和模版,並將結果輸出到out中
try
{
template.process(dataMap,out);// 用模板來開發servlet可以只在代碼裏面加入動態的數據
}
catch(TemplateException e)
{
throw new ServletException("處理Template模版中出現錯誤", e);
}
//------------------------------------------
}
}
4. web.xml中的配置信息
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FreeMarkerHandler</servlet-name>
<servlet-class>com.ftl.FreeMarkerHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FreeMarkerHandler</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
5. index.jsp提供訪問位置
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
點擊下面鏈接查看效果:
<hr>
<a href="freeMarkerHandler.do">點擊查看效果</a>
</body>
</html>
6. 效果展示
將項目部署到tomcat上,然後訪問就可以看到效果了。
總結
以上測試的例子沒有使用任何的web框架,其實這種模板語言是可以和我們常用的框架一起使用的,自己查找到了一些相關的資料分享給大家,有興趣的可以去看看!
Freemarker全部文檔:http://www.open-open.com/doc/list/101?o=p
具體實例:http://www.zuidaima.com/share/kfreemarker-p1-s1.htm