Spring mvc整合freemarker詳解

1.什麼是FreeMarker

FreeMarker是一個模板引擎,一個基於模板生成文本輸出的通用工具,使用純Java編寫
FreeMarker被設計用來生成HTML Web頁面,特別是基於MVC模式的應用程序
雖然FreeMarker具備一些編程的能力,但一般由Java程序準備要顯示的數據,由FreeMarker生成頁面,經過模板顯示準備的數據(以下圖)
這裏寫圖片描述javascript

2.FreeMarker特性

可以生成各類文本:HTML、XML、RTF、Java源代碼等等
易於嵌入到你的產品中:輕量級;不須要Servlet環境
插件式模板載入器:能夠從任何源載入模板,如本地文件、數據庫等等
你能夠按你所需生成文本:保存到本地文件;做爲Email發送;從Web應用程序發送它返回給Web瀏覽器html

3. springMVC整合Freemarker

1.添加jar包

添加freemarker的jar,還須要額外添加spring-content-support的jar包,否則會報錯。java

2.而後再Spring的配置文件中添加對freemarker的配置

<!-- 配置freeMarker的模板路徑 -->  
     <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="WEB-INF/ftl/" />  
        <property name="defaultEncoding" value="UTF-8" />  
     </bean>  
     <!-- freemarker視圖解析器 -->  
     <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="suffix" value=".html" />  
        <property name="contentType" value="text/html;charset=UTF-8" />  
        <!-- 此變量值爲pageContext.request, 頁面使用方法:rc.contextPath -->  
        <property name="requestContextAttribute" value="rc" />  
     </bean>

3.寫一個User類:

package com.my.springmvc.bean;

public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

4.一個FreeMarkerController類:

@Controller
@RequestMapping("/home")
public class FreeMarkerController {

    @RequestMapping("/index")
    public ModelAndView Add(HttpServletRequest request,HttpServletResponse response){
        User user = new User();
        user.setUsername("sg");
        user.setPassword("1234");
        List<User> users  = new ArrayList<User>();
        users.add(user);

        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        mv.addObject("users",users);
        return mv;
    }
}

5.而後再WEB-INF/ftl目錄下建立一個index.html文件:

##web

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>another</title>
</head>
<body>  
<#list users as user>  
username : ${user.username}<br/>  
password : ${user.password}  
</#list>  
</body>  
</html>

結果:

這裏寫圖片描述

4.freemarker語法介紹:

1. FreeMarker模板文件主要由以下4個部分組成

文本:直接輸出的部分
註釋:<#– … –> 格式部分,不會輸出
插值:即 ${…} 或 #{…} 格式的部分,將使用數據模型中的部分替代輸出
指令:FreeMarker 指定,和 HTML 標記相似,名字前加 # 予以區分,不會輸出面試

<html>
<head>
    <title>Welcome!</title>
</head>
<body>
    <#-- 註釋部分 -->
    <#-- 下面使用插值 -->
    <h1>Welcome ${username} !</h1>

    <p>We have these animals:</p>
    <u1>
        <!-- 使用FTL指令 -->
        <#list animals as animal>
        <li>${animal.name} for ${animal.price} Euros</li>
        </#list>
    </u1>
</body>
</html 

2.控制語句

<#if condition> 
    ... 
<#elseif condition2> 
    ... 
<#elseif condition3> 
    ... 
<#else>
<#switch value> 
    <#case refValue1> 
        ... 
        <#break> 
    <#case refValue2> 
        ... 
        <#break> 
    <#case refValueN> 
        ... 
        <#break> 
    <#default> 
        ... 
</#switch>

3判斷變量是否存在

<#if readonly??></#if>

4.防止空指針報錯

變量名後用 ! 加默認值:${foo!」Default」},若是 foo 爲 null 則輸出 Defaultspring

5.普通的變量

這是最簡單的狀況,直接<nobr><span class="math" id="MathJax-Span-1" style="width: 6.041em; display: inline-block;"><span style="display: inline-block; position: relative; width: 5.664em; height: 0px; font-size: 106%;"><span style="position: absolute; clip: rect(1.261em 1000em 2.645em -0.563em); top: -2.261em; left: 0.003em;"><span class="mrow" id="MathJax-Span-2"><span class="texatom" id="MathJax-Span-3"><span class="mrow" id="MathJax-Span-4"><span class="texatom" id="MathJax-Span-5"><span class="mrow" id="MathJax-Span-6"><span class="mo" id="MathJax-Span-7"><span style='font-family: STIXGeneral, "Arial Unicode MS", serif; font-size: 94%; font-style: normal; font-weight: normal;'>變</span></span></span></span><span class="texatom" id="MathJax-Span-8"><span class="mrow" id="MathJax-Span-9"><span class="mo" id="MathJax-Span-10"><span style='font-family: STIXGeneral, "Arial Unicode MS", serif; font-size: 94%; font-style: normal; font-weight: normal;'>量</span></span></span></span><span class="texatom" id="MathJax-Span-11"><span class="mrow" id="MathJax-Span-12"><span class="mo" id="MathJax-Span-13"><span style='font-family: STIXGeneral, "Arial Unicode MS", serif; font-size: 94%; font-style: normal; font-weight: normal;'>名</span></span></span></span><span class="texatom" id="MathJax-Span-14"><span class="mrow" id="MathJax-Span-15"><span class="mo" id="MathJax-Span-16"><span style='font-family: STIXGeneral, "Arial Unicode MS", serif; font-size: 94%; font-style: normal; font-weight: normal;'>稱</span></span></span></span></span></span><span class="texatom" id="MathJax-Span-17"><span class="mrow" id="MathJax-Span-18"><span class="mo" id="MathJax-Span-19"><span style='font-family: STIXGeneral, "Arial Unicode MS", serif; font-size: 94%; font-style: normal; font-weight: normal;'>,</span></span></span></span><span class="texatom" id="MathJax-Span-20"><span class="mrow" id="MathJax-Span-21"><span class="mo" id="MathJax-Span-22"><span style='font-family: STIXGeneral, "Arial Unicode MS", serif; font-size: 94%; font-style: normal; font-weight: normal;'>如</span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.267em;"></span></span></span><span style="border-left-width: 0.003em; border-left-style: solid; display: inline-block; overflow: hidden; width: 0px; height: 1.203em; vertical-align: -0.263em;"></span></span></nobr><script type="math/tex" id="MathJax-Element-1">{變量名稱} ,如</script>{name}數據庫

須要注意的是有的變量是須要轉義的如雙引號編程

6..遍歷List集合

<#list ["克里斯埃文斯", "斯嘉麗約翰遜", "小羅伯特唐尼"]  as x>  
${x}  
</#list>

此外,迭代集合對象時,還包含兩個特殊的循環變量:
item_index:當前變量的索引值
item_has_next:是否存在下一個對象
也可使用<#break>指令跳出迭代瀏覽器

7.運算符

FreeMarker表達式中徹底支持算術運算,FreeMarker支持的算術運算符包括:+, - , * , / , %
比較運算符微信

表達式中支持的比較運算符有以下幾個:
1,=或者==:判斷兩個值是否相等.
2,!=:判斷兩個值是否不等.
3,>或者gt:判斷左邊值是否大於右邊值
4,>=或者gte:判斷左邊值是否大於等於右邊值
5,<或者lt:判斷左邊值是否小於右邊值
6,<=或者lte:判斷左邊值是否小於等於右邊值

注意:=和!=能夠用於字符串,數值和日期來比較是否相等,但=和!=兩邊必須是相同類型的值,不然會產生錯誤,並且FreeMarker是精確比較,」x」,」x 「,」X」是不等的.其它的運行符能夠做用於數字和日期,但不能做用於字符串,大部分的時候,使用gt等字母運算符代替>會有更好的效果,由於FreeMarker會把>解釋成FTL標籤的結束字符,固然,也可使用括號來避免這種狀況,如:<#if (x>y)>

邏輯運算符

和普通程序同樣,freemarker也有&&,|| ,!三種

8.變量的聲明

<#assign num=0/>

9.include指令

include指令的做用相似於JSP的包含指令,用於包含指定頁.include指令的語法格式以下:
<#include filename [options]>
在上面的語法格式中,兩個參數的解釋以下:
filename:該參數指定被包含的模板文件
options:該參數能夠省略,指定包含時的選項,包含encoding和parse兩個選項,其中encoding指定包含頁面時所用的解碼集,而parse指定被包含文件是否做爲FTL文件來解析,若是省略了parse選項值,則該選項默認是true.

10.import指令

該指令用於導入FreeMarker模板中的全部變量,並將該變量放置在指定的Map對象中,import指令的語法格式以下:
<#import 「/lib/common.ftl」 as com>
上面的代碼將導入/lib/common.ftl模板文件中的全部變量,交將這些變量放置在一個名爲com的Map對象中.

11 macro的使用

這個能夠用來實現自定義指令,通常用來作公共組件,例如分頁條
最後說下list中含有map的遍歷,這種狀況可使用點語法或方括號語法.假若有下面的數據模型:
Map root = new HashMap();
Book book = new Book();
Author author = new Author();
author.setName(「annlee」);
author.setAddress(「gz」);
book.setName(「struts2」);
book.setAuthor(author);
root.put(「info」,」struts」);
root.put(「book」, book);

爲了訪問數據模型中名爲struts2的書的做者的名字,可使用以下語法:
book.author.name //所有使用點語法
book[「author」].name
book.author[「name」] //混合使用點語法和方括號語法
book[「author」][「name」] //所有使用方括號語法

個人微信二維碼以下,歡迎交流討論

這裏寫圖片描述

歡迎關注《IT面試題彙總》微信訂閱號。天天推送經典面試題和麪試心得技巧,都是乾貨!

微信訂閱號二維碼以下:

這裏寫圖片描述

參考:
http://blog.csdn.net/walkcode/article/details/26393211
http://blog.csdn.net/win_man/article/details/51317957
http://rongjih.blog.163.com/blog/static/3357446120127632757911/
http://qtdebug.com/spring-web/11.%20Freemarker%20%E8%AF%AD%E6%B3%95%E7%AE%80%E4%BB%8B.html
http://blog.csdn.net/walkcode/article/details/26393211
http://blog.csdn.net/shimiso/article/details/8778793

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
相關文章
相關標籤/搜索