FreeMarker之產生頁面(三),freemarker產生頁面

來源:互聯網
上載者:User

FreeMarker之產生頁面(三),freemarker產生頁面

       這篇文章介紹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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.