Thymeleaf模板的使用(轉)


原文:http://blog.csdn.net/pdw2009/article/details/44701127

使用模板的要點:
    頁面主體結構固定,具體參數可變,盡可能讓參數動態化,才能提高模板的復用性

===================================================================
Thymeleaf's core  is a DOM processing engine


Processor: An Object which applies some logic to a DOM node


Standard Dialect: a set of processor,provided by Thymeleaf core library


Template Engine :  can be configured several dialects at a time,called  process chain

================================================================
Template Resolver
Template Resolvers are objects  that  implement an  interface  from  the Thymeleaf API called org.thymeleaf.templateresolver.ITemplateResolver

public TemplateResolution resolveTemplate(final TemplateProcessingParameters    templateProcessingParameters);

All implementaion class :
    -ClassLoaderTemplateResolver
    -FileTemplateResolver
    -ServletContextTemplateResolver
    -UrlTemplateResolver


Initial Template Engine use ServletContextTemplateResolver
    private static void initializeTemplateEngine() {
        
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        
        // XHTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode("XHTML");
        
    // This will convert "home" to "/WEB-INF/templates/home.html"
    // 設置模板的前置路徑
        templateResolver.setPrefix("/WEB-INF/templates/");
    //設置模板統一的后綴名
        templateResolver.setSuffix(".html");

        // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
        
        // Cache is set to true by default. Set to false if you want templates to
        // be automatically updated when modified.
        templateResolver.setCacheable(true);
        
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        
    }

1.new one TemplateResolver instance
2.config the resolver
3.new Template engine
4.set resolver to this engine
5.invoke engine's process method to work

============================================================================

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">


或者使用下面的文檔聲明也可以,這樣就沒有Thymeleaf對文檔的校驗功能了,因為沒有引入對應的DTD,而且IDE可能會提示錯誤,但是不影響對模板的解析。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
============================================================================
#{}
specify  that a  text should correspond  to a specific message
引用外部文件(message)中的內容,進行替換
首先,需要指定外部文件的位置,如果沒有指定,則使用默認的Standard Message Resolver
會到/WEB-INF/templates/下尋找properties文件
home_en.properties文件是如何被定為到的呢?
通過WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
其中,request.getLocale()就說明了當前系統的所在地,就能確定讀取en/zh_CN了。
當然,可以配置外部文件的位置!

th:text="#{home.welcome}"
The th:text attribute, which evaluates its value expression and sets the result of this evaluation as the body of  the  tag  it is  in
th:text 計算表達式的結果,並使用這個結果來替換當前標簽中的內容

============================================================================
public void process(
    final HttpServletRequest request, final HttpServletResponse response,
    final ServletContext servletContext, final TemplateEngine templateEngine) 
    throws Exception {

    WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
    ctx.setVariable("today", Calendar.getInstance());

    templateEngine.process("home", ctx, response.getWriter());

}

Thymeleaf中提供了2個實現IContext的實現類
    org.thymeleaf.context.Context   implements  IContext
    org.thymeleaf.context.WebContext   implements  IWebContext
WebContext 提供了更多的方法可用

=============================================================================
Unescaped Text
照原樣對文本進行輸出,不對> < 進行轉義

th:utext="<b>Big Character</b>" 將輸出為:<b>Big Character</b>

=============================================================================
Using and displaying variables

1.設置變量
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
    Calendar cal = Calendar.getInstance();
    WebContext ctx = new WebContext(request, servletContext, request.getLocale());
    ctx.setVariable("today", dateFormat.format(cal.getTime()));
    templateEngine.process("home", ctx, response.getWriter());
2.在模板中使用變量
    th:text="${today}"
    
3.使用Thymeleaf提供的內置變量,不用提前設置,直接在模板中使用
    th:text="${#calendars.format(today,'dd MMMM yyyy')}"
==============================================================================
 Thymeleaf Standard Dialect:  the Thymeleaf Standard Expression syntax

 Thymeleaf 支持的運算符和表達式的應用
 所有的操作符都可以嵌套使用,非常強大!

 1.Text literals: '...'
 2.Number literals: 0,1.0,12.3,etc

 Simple expression: 表達式語法
     1.Message expression : #{}
     2.Variable expression : ${}
     3.Link URL expression: @{}
     4.Selection Variable expression: *{}
        結合th:object使用,在某個范圍內進行變量的查找,而不是在context中查找,縮小了查詢的范圍,效率如何呢?
        如何沒有與th:object結合使用,*{}與${}效果一樣,因為其范圍自動擴展到context。

 Binary operations:  運算符
     1.String concatenation: +
     2.Arithetic operatiors : +, -, *, /, %
     3.Comparators: >, <, >=, <=
     4.Boolean operators: and, or
     5.Equality operators: ==, !=

 Unary operations:
     1.Minus sign(): -  負號
     2.Boolean negation: !, not 否定符

 Conditional operators: 條件表達式
     1.If-then-else: (if)?(then):else 三元運算符
     2.If-then: (if) ? (then) ,省略了else部分,如果條件不成立,返回null
     3.Default: (value)?:(defaultValue) , use second value only first is null 

All  this operations can be combined and nested: 
    'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown')


=================================================================================
Message  在模板中獲取消息
    動態指定message的內容/甚至可以動態指定訪問哪個message
    th:utext="#{home.welcome(${session.user.name})}",其中${session.user.name}作為參數,替換home.welcome的映射文本中的{0}
    th:utext="#{${welcomeMsgKey}(${session.user.name})}",其中${welcomeMsgKey}動態指定message文件中的key

==================================================================================
Variables  在模板中獲取數據
     ${...}  expressions are  in  fact OGNL  (Object-Graph Navigation Language) expressions executed
on  the map of variables contained  in  the context.

     模板中獲取變量值的方式,使用${},針對不同類型數據,用法如下:

    /*
    * Access to properties using the point (.). Equivalent to calling property getters.
    * 通過.進行導航,相當於調用getters()
    */
    ${person.father.name}

    /*
    * Access to properties can also be made by using brackets ([]) and writing
    * the name of the property as a variable or between single quotes.
    * 使用[]等效於使用. ,但是[]在某些場合能完成.不能完成的任務
    */
    ${person['father']['name']}

    /*
    * If the object is a map, both dot and bracket syntax will be equivalent to
    * executing a call on its get(...) method.
    * 訪問Map集合
    */
    ${countriesByCode.ES}
    ${personsByName['Stephen Zucchini'].age}

    /*
    * Indexed access to arrays or collections is also performed with brackets,
    * writing the index without quotes.
    * 訪問數組
    */
    ${personsArray[0].name}

    /*
    * Methods can be called, even with arguments.
    * 調用對象的方法
    */
    ${person.createCompleteName()}
    ${person.createCompleteNameWithSeparator('-')}

=======================================================================================
Expression utility objects  在模板中使用內置對象
內置對象,提供了很多方便的功能,日期格式化,字符串處理,數字格式化等
    #dates, formatting,component extraction,etc
    #calendars
    #numbers, formatting numeric objects.
    #strigns, contains,startsWith,prepending/appending,etc
    #bools
    #arrays
    #lists
    #sets
    #maps
    #aggregates, creating aggregates on arrays or collections
    #messages, equal to using #{}
    #ids, deal with id attributes, eg: as a result of an iteration
    #ctx等等,還有很多!

======================================================================================
Link URLs  在模板中使用URL鏈接
    @{}
Several types of URLs:
    1.Absolute URL,like http://localhost:8080/thymeleaf
    2.Relative URL,which can be:

        Page-relative,like: user/login.html 頁面相對定位

        Context-relative,like: /itemdetails?id=1 (context name in server will be added automatically)項目根路徑定位,模板解析時會自動加上應用程序的名稱作為前綴

        Server-relative,like: ~/billing/processInvoice (allow calling URLs in another context in the same server) 相同服務器根目錄下的定位

    如何要使用相對定位,必須指定一個實現了IWebcontext接口的對象,因為需要從其中獲取httprequest對象,從而得到應用程序的根路徑,才能處理相對路徑

    相對路徑,並且在URL上使用OGNL表達式取參數,而且themeleaf會自動對URL進行編碼:
        <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
        <a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>

=======================================================================================
Literals    模板中使用簡單文本
    字符串/數字
        a.原樣輸出
            <p>The year is <span th:text="2011">1492</span>.</p>
        b.字符串拼接
            th:text="'The name of the user is ' + ${user.name}"

========================================================================================
Arithmetic operations 模板中對變量進行算數運算 
+ - * / %
有兩種計算方式,都可以。
    1.使用Thymeleaf進行運算--->先OGNL表達式取到變量值,然后thymeleaf再進行運算
        th:with="isEven=(${prodStat.count} % 2 == 0)"

    2.使用OGNL進行運算--->直接在OGNL表達式中進行運算
        th:with="isEven=${prodStat.count % 2 == 0}"

========================================================================================
Comparators and Equality 模板中使用比較符和等號
    模板中不能直接使用 > < >= <=
    需要進行轉義:
        > gt;
        < lt;
        >= ge; gte;
        <= le; lte;
        == eq;
        != ne; neq;

    th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

=======================================================================================
Conditional expressions 三元運算,第一個表達式的結果為boolean類型

    if ? then : else ---> A ? B : C

    <tr th:class="${row.even}? 'even' : 'odd'"> 設置tr的class屬性,用來控制行的顯示效果很方便
    
    嵌套使用條件表達式:
    <tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'"> 靈活控制首行,偶數行,奇數行的class屬性值,便於進行css樣式定義

    還可以省略else部分,當表達式結果為false,返回null,否則返回'alt'
    <tr th:class="${row.even}? 'alt'">
        ...
    </tr>
======================================================================================
Default Expression 具有默認值的表達式,第一個表達式的結果只要不為null,就取第一個表達式的結果
    
    being  the second one evaluated only  in  the case of  the first one  returning null .
    
    A ?: B  ---> A不為null,則取A,否則取B
    
    如果第一個表達式的計算結果為null,則取第二個表達式的結果
    <div th:object="${session.user}">
        ...
        <p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
    </div>
    
    等效於:
    <p>Age: <span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>.</p>
    
    條件表達式嵌套:
    <p>Name: <span th:text="*{firstName} ?: (*{admin} ? 'Admin' : #{default.username})">Sebastian</span>.</p>

        
=========================================================================================
靜態方法的調用
    <p th:text="${@myapp.translator.Translator@translateToFrench('textVar')}">Some text here...</p>

==========================================================================================
******************************************************************************************
Setting the value of any attribute 在模板中對目標設置任何屬性,action, class, value, etc

非常強大,不僅處理HTML模板方便,處理FO-XSL(PDF模板)一樣通用。
    設置action屬性
    <form action="subscribe.html" th:attr="action=@{/subscribe}">

    設置value屬性
    <input type="submit" value="Subscribe me!" th:attr="value=#{subscribe.submit}"/>

    一次設置多個屬性
    <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}"/>
    模板處理后的結果--->  <img src="/gtgv/images/gtvglogo.png" title="Logo de Good Thymes" alt="Logo de Good Thymes" />

    設置屬性更優雅的方式(僅在HTML模板中有效,處理PDF模板,只能用th:attr=""來實現,因為PDF模板中的屬性在Thymeleaf中好像沒有定義)
        <input type="submit" value="Subscribe me!" th:value="#{subscribe.submit}"/>
        <form action="subscribe.html" th:action="@{/subscribe}">
        <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>
        Themeleaf支持HTML中幾乎所有的屬性定義,使用時具體參考Thymeleaf的手冊
        th:bgcolor,th:border,th:cellpadding,th:cellspacing, th:colspan,th:align,th:src,th:width,th:size 等等

控制樣式:
    第一種方式直接在tr上定義css樣式,如bgcolor,border等
    第二種方式,在tr上定義class屬性,通過外部css樣式進行控制。(復雜樣式,采用第二種方案)

============================================================================================
Appending and prepending 在已有屬性上追加屬性
    th:attrappend  追加
    th:attrprepend 放到前面
    
    <input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />
    ---> <input type="button" value="Do it!" class="btn warning" />
    
    遍歷prods集合,每次生成一行
    <tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">
        <td>${prod.name}</td>
    </tr>
=============================================================================================
Fixed-value boolean attributes  設置某些具有固定值的屬性
XHTML/HTML5中,有一些特殊的屬性,要么沒有值,要么為某個固定的值
    checked
    selected
    disabled
    mutiple
    readonly
如果計算結果為true,則使用它的固定值,否則不處理。
<input type="checkbox" name="active" th:checked="${user.active}" />

還有:
    th:autofocus
    th:default
    th:hidden
    ...

===============================================================================================
***********************************************************************************************
Iteration 循環遍歷

th:each="obj : ${objList}"  循環所在標簽的片段,每次片段中用到的都是當前遍歷到的對象

    后台准備數據
    public void process(
        HttpServletRequest request, HttpServletResponse response,
        ServletContext servletContext, TemplateEngine templateEngine) {
        ProductService productService = new ProductService();
        List<Product> allProducts = productService.findAll();
        WebContext ctx = new WebContext(request, servletContext, request.getLocale());
        ctx.setVariable("prods", allProducts);
        templateEngine.process("product/list", ctx, response.getWriter());
    }

    模板中進行遍歷,每次遍歷生成一個tr,td列取到的對象為當前遍歷到的對象
    <tr th:each="prod : ${prods}">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>

Keeping    iteration status 跟蹤迭代過程中的狀態變化
    遍歷過程中,提供了如下屬性:
        index    starting with 0
        count    starting with 1
        size    total amount of elements in the iterated variables
        current    current object
        even/odd    boolean value,第偶數個/奇數個
        first/last    boolean value.第1個/最后1個

    在th:each中,在iter variable變量后面,定義一個status variable,通過該變量來獲取遍歷過程中的狀態
    <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">

prefix    前綴
suffix    后綴
    If you don't explicitly set an  iteration variable, Thymeleaf will  always create one  for you by suffixing 'Stat' to  the name of  the iter variable。
    如果沒有定義status variable,thymeleaf會自動為我們提供一個來使用,通過在iter variable后面添加后綴Stat來使用。
    <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">

================================================================================================
************************************************************************************************
Conditional evaluation 條件語句

Simple conditionals: "if" and "unless"
    在某種條件成立時,對某個fragment進行處理:

    當th:if條件成立時,該標簽中其它th:*標簽才會發揮作用,如果條件不成立,則th:*不會執行
    <a href="comments.html"
    th:href="@{/product/comments(prodId=${prod.id})}"
    th:if="${not #lists.isEmpty(prod.comments)}">view</a>

    th:if 判斷表達式結果是否為真的規則:
    If value is not null:
        value is a boolean and is true;
        value is a number and is non-zero;
        value is a character and is non-zero;
        value is a String and is not "false", "off" or "no";
        value is not a boolean, a number, a character or a String;


    If value is null, th:if will evaluate to false;

    另外,還可以用th:unless,進行條件控制。如果條件為真,則不執行。
    <a href="comments.html"
    th:href="@{/comments(prodId=${prod.id})}"
    th:unless="${#lists.isEmpty(prod.comments)}">view</a>

====================================================================================
Switch statement    Switch選擇語句

Note  that as soon as one  th:case  attribute  is evaluated as  true , every other  th:case  attribute  in  the same switch context is evaluated as  false .

The defaul t option  is speci fied as  th:case="*" :

    <div th:switch="${user.role}">
        <p th:case="'admin'">User is an administrator</p>
        <p th:case="#{roles.manager}">User is a manager</p>
        <p th:case="*">User is some other thing</p>
    </div>

    
======================================================================================
Template Layout  模板布局/模板重用

Including template fragments
    th:fragment  
    th:include    
    用法:
        在某個標簽中使用th:fragment屬性定義一個變量名,然后在其他模板中通過th:include,即可引入。
    a.html 
        <div th:fragment="hello">   定義一個fragment,並取名為"hello"
            include me.!
        </div>

    b.html
        <div th:include="a :: hello">what?</div> 從名稱為a.html的模板中引入名稱為"hello"的fragment
    

    ***還可以不使用th:fragment屬性進行引入,通過DOMSelector
    "templatename::[domselector]"    like XPath expressions.
    
    ***將模板整個引入
    "templatename" 
    
    th:include中同樣可以嵌套使用表達式
    <div th:include="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>

    
    th:include 
        引入fragment中定義的內容
    th:substituteby 
        引入fragment所在標簽和內容,並替換當前的標簽
    
    如:
    footer.html
    <footer th:fragment="copy">
        &copy; 2011 The Good Thymes Virtual Grocery
    </footer>

    main.html
    --------------------------------------------> th:include只引入內容
    <div th:include="footer :: copy"></div>
    result:
    <div>
        &copy; 2011 The Good Thymes Virtual Grocery
    </div>
    
    --------------------------------------------> 整個引入,並替換掉host tag
    <div th:substituteby="footer :: copy"></div>
    result:
    <footer>
        &copy; 2011 The Good Thymes Virtual Grocery
    </footer>

============================================================================
Removing template fragments
    th:remove 為了靜態顯示時提供充分的數據,但是在模板被解析后,又不需要這些模擬的數據,需要將其刪除
    可選屬性:
        th:remove="all", 刪除所有
        th:remove="all-but-first",刪除所有,但保留第一個
        th:remove="body", 刪除內容,但保留標簽
        th:remove="tag", 刪除標簽,但保留內容

=============================================================================
Local variables  模板中自定義變量
    th:with="fisrtPerson=${persons[0]}"
    使用自定義的變量:
    <span th:text="${firstPer.name}">

    <div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
        <p>The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.</p>
        <p>But the name of the second person is <span th:text="${secondPer.name}">Marcus Antonius</span>.</p>
    </div>
    
    
    原理:定義的變量將被添加到context的map中,這樣就能像其它變量一樣被使用到了。
    自定義變量的有效范圍:僅在被定義的標簽內有效,比如,上面的firstPerson,僅在當前div中有效

    另一個用途:
    定義變量存放message中的配置
    然后在表達式中用
    如,從message中獲取date.format的配置,然后復制給變量df,然后在其它地方(自定義變量所在標簽內)進行使用

    <p th:with="df=#{date.format}">
        Today is: <span th:text="${#calendars.format(today,df)}">13 february 2011</span>
    </p>
    
    也可以直接:
    <p>
        Today is: <span th:with="df=#{date.format}" th:text="${#calendars.format(today,df)}">13 february 2011</span>
    </p>

    優先級的問題:
    th:with 優先級高於 th:text 
    th:each 優先級高於 th:*

==============================================================================================
Attribute precedence 屬性的優先級問題

Thymeleaf attributes have a numeric precedence:
    1  fragment inclusion            th:include
    2  fragment iteration            th:each
    3  condition evaluation            th:if/th:unless/th:switch/th:case
    4  Local variable definition        th:object, th:with
    5  General attribute modification    th:attr, th:attrprepend, th:attrappend
    6  Specific attribute modification    th:value, th:href, th:src, etc
    7  Text                    th:text, th:utext
    8  Fragment specification        th:fragment
    9  Fragment removal            th:remove    

    <ul th:each="item : ${items}">
        <li th:text="${item.description}">Item description here...</li>
    </ul>
    
    由於th:each的優先級高於其它th:*,所以可以簡寫為:

    <ul>
        <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
    </ul>

    還可以這樣寫,將循環放到后面,只是閱讀性不好,但不影響結果:
    <ul>
        <li th:text="${item.description}" th:each="item : ${items}">Item description here...</li>
    </ul>

=======================================================================================
Inlining

Text inlining
    好處:簡化書寫
    弊端:以prototype呈現(靜態地打開網頁),將原樣顯示
    用法,在標簽上定義th:inline="text"
    該標簽中任意地方都可以使用內聯樣式獲取數據

    <p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>
    簡化為:
    <p>Hello, [[${session.user.name}]]!</p>

    parent tag中定義
    <body th:inline="text">
        ...
        <p>hello:[[${session.user.name}]]</p>
        ...
    <body>

JavaScript inlining
    <script th:inline="javascript">
        /*<![CDATA[*/
        ...
        var username = [[${session.user}]];
        ...
        /*]]>*/
    </script>

    thymeleaf將自動對user對象進行轉換,而且轉換為javascript中的user對象

    <script th:inline="javascript">
        /*<![CDATA[*/
        ...
        var user = {'age':null,'firstName':'John','lastName':'Apricot','name':'John Apricot','nationality':'Antarctica'};
        ...
        /*]]>*/
    </script>
=================================================================================
Validation and Doctypes

Validating templates 
    
    使用Thymeleaf的DTD進行校驗和聲明Thymeleaf的命名空間

    <!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

Doctype translation  Thymeleaf對模板處理完成后,會自動將DOCTYPE轉換為正確的類型,這樣瀏覽器端就能正常解析了!
    
    <!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd">

    After Thymeleaf process the template, will automatically transformate the DOCTYPE to:
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

===================================================================================
Template Resolver

org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
    return Thread.currentThread().getContextClassLoader().getResourceAsStream(templateName);

org.thymeleaf.templateresolver.FileTemplateResolver
    return new FileInputStream(new File(templateName));

org.thymeleaf.templateresolver.UrlTemplateResolver 
    return (new URL(templateName)).openStream();

--->

Prefix and suffix:
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");

Encoding  to be appl ied when  reading  templates:
    templateResolver.setEncoding("UTF-8");

Defaul t  template mode, and patterns  for defining other modes  for speci fic  templates:
    // Default is TemplateMode.XHTML
    templateResolver.setTemplateMode("HTML5");
    templateResolver.getXhtmlTemplateModePatternSpec().addPattern("*.xhtml");

Defaul t mode  for  template cache, and patterns  for defining whether speci fic  templates are cacheable or not:
    // Default is true
    templateResolver.setCacheable(false);
    templateResolver.getCacheablePatternSpec().addPattern("/users/*");

TTL  in mi l l iseconds  for parsed  template cache entries originated  in  this  template  resolver.  If not set,  the only way  to
remove an entry  from  the cache wi l l  be LRU  (cache max size exceeded and  the entry  is  the oldest).
    // Default is no TTL (only LRU would remove entries)
    templateResolver.setCacheTTLMs(60000L);

Also, a Template Engine can be set several   template  resolvers,  in which case an order can be establ ished between  them  for
template  resolution so  that,  if  the  first one  is not able  to  resolve  the  template,  the second one  is asked, and so on:
When several   template  resolvers are applied,  it  is  recommended  to specify patterns  for each  template  resolver so  that
Thymeleaf can quickly discard  those  template  resolvers  that are not meant  to  resolve  the  template, enhancing performance.
Doing  this  is not a  requi rement, but an optimization:

    ClassLoaderTemplateResolver classLoaderTemplateResolver = new ClassLoaderTemplateResolver();
    classLoaderTemplateResolver.setOrder(Integer.valueOf(1));
    // This classloader will not be even asked for any templates not matching these patterns
    classLoaderTemplateResolver.getResolvablePatternSpec().addPattern("/layout/*.html");
    classLoaderTemplateResolver.getResolvablePatternSpec().addPattern("/menu/*.html");

    ServletContextTemplateResolver servletContextTemplateResolver = new ServletContextTemplateResolver();
    servletContextTemplateResolver.setOrder(Integer.valueOf(2));
===================================================================================
Message Resolver 

    The implementation being used was an org.thymeleaf.messageresolver.StandardMessageResolver object as default in web application.

    you can create your own by  just  implementing  the  org.thymeleaf.messageresolver.IMessageResolver interface.
    And why would you want  to have more  than one message  resolver?  for  the same  reason as  template  resolvers: 
    message resolvers are ordered and  if  the  first one cannot  resolve a specific message, the second one will be asked, then the third, etc.
    
    // For setting only one
    templateEngine.setMessageResolver(messageResolver);

===================================================================================
Template Cache 模板緩存管理

    // Default is 50
    StandardCacheManager cacheManager = new StandardCacheManager();
    cacheManager.setTemplateCacheMaxSize(100);
    ...
    templateEngine.setCacheManager(cacheManager);

    // Clear the cache completely
    templateEngine.clearTemplateCache();
    // Clear a specific template from the cache
    templateEngine.clearTemplateCacheFor("/users/userList");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM