codestory

Vordefinierte Objekte in Thymeleaf

  1. Predefined Objects
  2. Basic Objects
  3. Utility Objects

1. Predefined Objects

In Thymeleaf gibt es einige Objekte, die vordefiniert werden und Sie können sie überall in Thymeleaf Template benutzen. Im Grunde gibt es 2 solchen Objektstypen. Das sind die Basic Objekte und die Utility Objekte:
Die vordefinierten Objekte werden nach der Standard OGNL referenziert, die mit dem Zeichen ( # ) beginnt.

2. Basic Objects

Object
Class/Interface
Die Bezeichnung
#ctx
org.thymeleaf.context.IContext
org.thymeleaf.context.IWebContext
Ein Objekt implementiert die Interface IContext oder IWebContext, das von der Umwelt abhängig ist (Standard oder Web).
#locale
java.util.Locale
Ein Objekt versorgt die Informationen,die Locale betreffen.
#request
javax.servlet.http.HttpServletRequest
(Nur in die Umwelt Web) das Objekt HttpServletRequest.
#response
javax.servlet.http.HttpServletResponse
(Nur in die Umwelt Web) das Objekt HttpServletResponse.
#session
javax.servlet.http.HttpSession
(Nur in die Umwelt Web) das Objekt HttpSession.
#servletContext
javax.servlet.http.ServletContext
(Nur in die Umwelt Web) das Objekt ServletContext.
#ctx
#ctx ist ein Context Objekt. Es implementiert die Interface org.thymeleaf.context.IContext oder org.thymeleaf.context.IWebContext, das von der Umwelt (Standard oder Web) abhängig ist.
Die zwei anderen Objekte #vars, #root sind gleich wie #ctx. Aber #ctx wird empfohlen zu benutzen anstatt von 2 anderen Objekte.
Abhängig von der Umwelt, Standard oder Web, kann das Objekt #ctx Sie die Information versorgen:
<!--
 * ===============================================
 * See javadoc API for class org.thymeleaf.context.IContext
 * ===============================================
 -->

${#ctx.locale}
${#ctx.variableNames}

<!--
 * ================================================
 * See javadoc API for class org.thymeleaf.context.IWebContext
 * ================================================
  -->

${#ctx.request}
${#ctx.response}
${#ctx.session}
${#ctx.servletContext}
In der Umwelt Spring funktioniert das Objekt #ctx nicht wie erwartet. ${#ctx.locale}, ${#ctx.request}, ${#ctx.response}, ${#ctx.request}, ${#ctx.servletContext} gibt immer null zurück. Sie sollen die Objekte #locale, #request, #response, #servletContext benutzen um zu ersetzen.
#locale
Das Objekt #locale (java.util.Locale) bietet Sie die Information von der Umwelt, in die die Applikation funktioniert, z.B die geografischer Bereich, Sprache, Kultur, digitales Format, Datums- und Uhrzeitformat, ...
predefined-object-locale.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #locale</h1>
       <h3>#locale.locale</h3>
       <span th:utext="${#locale.country}"></span>
       <h3>#locale.language</h3>
       <span th:utext="${#locale.language}"></span>
   </body>
</html>
#request
predefined-object-request.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #request</h1>
       <h3>#request.contextPath</h3>
       <span th:utext="${#request.contextPath}"></span>
       <h3>#request.requestURI</h3>
       <span th:utext="${#request.requestURI}"></span>
       <h3>#request.requestURL</h3>
       <span th:utext="${#request.requestURL}"></span>
   </body>
</html>
#response
predefined-object-response.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #response</h1>
       <h3>#response.headerNames  (java.utils.Enumeration)</h3>
       <ul>
          <th:block  th:each="headerName : ${#request.headerNames}">
            <li th:utext="${headerName}">Header Name</li>
          </th:block>
       </ul>  
   </body>
</html>
#servletContext
predefined-object-servletContext.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #servletContext</h1>
       <h3>#servletContext.attributeNames (java.utils.Enumeration)</h3>
       <ul>
          <th:block th:each="attrName : ${#servletContext.attributeNames}">
            <li th:utext="${attrName}">Attribute Name</li>
            <li th:utext="${#servletContext.getAttribute(attrName)}">Attribute Value</li>
          </th:block>
       </ul>  
   </body>
</html>
#session
Spring Controller
// ....
@RequestMapping("/predefined-object-session")
public String objectSession(HttpServletRequest request) {
   HttpSession session = request.getSession();
   session.setAttribute("mygreeting", "Hello Everyone!");
   return "predefined-object-session";
}
predefined-object-session.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #session</h1>
       <h3>#session.getAttribute('mygreeting')</h3>
       <span th:utext="${#session.getAttribute('mygreeting')}"></span>  
   </body>
</html>

3. Utility Objects

Object
Class/Interface
Die Bezeichnung
#execInfo
org.thymeleaf.expression.ExecutionInfo
Die Information von Template wird gerade behandelt.
#messages
org.thymeleaf.expression.Messages
Die Methode zur Arbeit mit message.
#uris
org.thymeleaf.expression.Uris
Die Methode zum Austritt (escape) der Teile von URLs/URIs.
#conversions
org.thymeleaf.expression.Conversions
Die Methode zur Implementierung der konfigurierten "Umwandlungsdienstleistung" (conversion service) (wenn ja)
#dates
javax.servlet.http.HttpSession
Die Methode zur Formatierung des Objekt java.util.Date, oder zur Holung der betreffenden Information wie Datum, Monat, Jahr..
#calendars
javax.servlet.http.ServletContext
Wie #dates, aber mit dem Objekt java.util.Calendar.
#numbers
org.thymeleaf.expression.Numbers
Die Methode zur Formatierung des numerischen Objekte (Zahl).
#strings
org.thymeleaf.expression.Strings
Die Methode für die Objekte String. zum Beispiel contains, startsWith, ...
#objects
org.thymeleaf.expression.Objects
Die Methode für die Objekte im allgemeinen.
#bools
org.thymeleaf.expression.Bools
Die Methode für die Bewertung boolean.
#arrays
org.thymeleaf.expression.Arrays
Die Methode für die Array.
#lists
org.thymeleaf.expression.Lists
Die Methode für lists.
#sets
org.thymeleaf.expression.Sets
Die Methode für sets.
#maps
org.thymeleaf.expression.Maps
Die Methode für maps.
#aggregates
org.thymeleaf.expression.Aggregates
Die Methode für die Berechnung der Summe, Durchschnitt,.. auf einer Kollektion oder Array.
#ids
org.thymeleaf.expression.Ids
#execInfo
Das Objekt hilft Ihnen bei der Holung der Information über Template , das gerade behandelt wird.
@RequestMapping("/predefined-u-object-execInfo")
public String execInfo_object() {
      return "predefined-u-object-execInfo";
}
predefined-u-object-execInfo.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>#execInfo</h1>
       <h3>#execInfo.templateMode</h3>
       <span th:utext="${#execInfo.templateMode}"></span> 
       <h3>#execInfo.templateName</h3>
       <span th:utext="${#execInfo.templateName}"></span>
       <h3>#execInfo.now (java.util.Calendar)</h3>
       <span th:utext="${#execInfo.now}"></span>
   </body>
</html>
#uris
Das Objekt bietet die Methode um die Teile von URLs/URIs zu fluchten (escape).
predefined-u-object-uris.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>#uris</h1>
       <h4>#uris.escapePath('https://example.com?user=Tom&gender=Male')</h4>
       <span th:utext="${#uris.escapePath('https://example.com?user=Tom&gender=Male')}"></span>
       <h4>#uris.unescapePath('https://example.com%3Fuser=Tom&gender=Male')</h4>
       <span th:utext="${#uris.unescapePath('https://example.com%3Fuser=Tom&gender=Male')}"></span>  
   </body>
</html>
#dates
Die Methode bieten um das Objekt java.util.Date zu formatieren oder die betreffenden Informationen wie Datum, Monat, Jahr,.. zu holen
predefined-u-object-dates.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#dates</h1>
    <!-- Create a variable 'now' (java.util.Date), it exists in block -->
    <th:block th:with="now = ${#dates.createNow()}">
        <span th:utext="${now}"></span>
        <h4>#dates.format(now, 'yyyy-MM-dd HH:mm:ss')</h4>
        <span th:utext="${#dates.format( now , 'yyyy-MM-dd HH:mm:ss')}">Date String</span>
        <h4>#dates.year(now)</h4>
        <span th:utext="${#dates.year(now)}">Year</span>
        <h4>#dates.month(now)</h4>
        <span th:utext="${#dates.month(now)}">Month</span>
    </th:block>
</body>
</html>
#calendars
Die Methode bieten um das Objekt java.util.Calendar zu formatieren oder die betreffenden Informationen wie Datum, Monat, Jahr,..zu holen.
predefined-u-object-calendars.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#calendars</h1>
    <!-- Create a variable 'now' (java.util.Calendar), it exists in block -->
    <th:block th:with="now = ${#calendars.createNow()}">
        <span th:utext="${now}"></span>
        <h4>#calendars.format(now, 'yyyy-MM-dd HH:mm:ss')</h4>
        <span th:utext="${#dates.format( now , 'yyyy-MM-dd HH:mm:ss')}">Date String</span>
        <h4>#dates.year(now)</h4>
        <span th:utext="${#dates.year(now)}">Year</span>
        <h4>#dates.month(now)</h4>
        <span th:utext="${#dates.month(now)}">Month</span>
    </th:block>
</body>
</html>
#numbers
Die Methode bieten um die nummerischen Objekte zu formatieren (Number).
predefined-u-object-numbers.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#numbers</h1>
    <!-- Create a Number, it exists in block -->
   <th:block th:with="num = 12345.987654">
        <h4>num</h4>
        <span th:utext="${num}">Number</span>
        <h4>${#numbers.formatInteger(num,3)}</h4>
        <span th:utext="${#numbers.formatInteger(num,3)}">Number</span>
        <h4>${#numbers.formatInteger(num,3,'POINT')}</h4>
        <span th:utext="${#numbers.formatInteger(num,3,'POINT')}">Number</span>
        <h4>${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}</h4>
        <span th:utext="${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}">Number</span>
    </th:block>
</body>
</html>
#strings
#objects
Die Methode für die Objekte im allgemeinen bieten.
@RequestMapping("/predefined-u-object-objects")
public String objects_object(Model model) {
    // An array store null values.
    String[] colors = new String[] {"red", "blue", null, "green", null, "red"};
    model.addAttribute("colors", colors);
    return "predefined-u-object-objects";
}
predefined-u-object-objects.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#objects</h1>  
    <h4>#objects.arrayNullSafe(colors,'white')</h4>
    <ul>
        <li th:each="color : ${#objects.arrayNullSafe(colors,'white')}"
            th:utext="${color}"></li>
    </ul>
    <h4>And other methods..</h4>
</body>
</html>
#bools
Die Methode für die Bewertung boolean bieten.
@RequestMapping("/predefined-u-object-bools")
public String bools_object(Model model) {
    // An array store null values.
    String[] colors = new String[] {"red", null , "blue"};
    model.addAttribute("colors", colors);
    return "predefined-u-object-bools";
}
predefined-u-object-bools.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#bools</h1>  
    <h4>Array: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#bools.arrayIsTrue(colors)</h4>
    <ul>
        <li th:each="color : ${#bools.arrayIsTrue(colors)}"
            th:utext="${color}"></li>
    </ul>
    <h4>#bools.arrayIsFalse(colors)</h4>
    <ul>
        <li th:each="color : ${#bools.arrayIsFalse(colors)}"
            th:utext="${color}"></li>
    </ul>
    <h4>And other methods..</h4>
</body>
</html>
#arrays
Die Methode für die Array bieten.
@RequestMapping("/predefined-u-object-arrays")
public String arrays_object(Model model) {
    String[] colors = new String[] {"red", null , "blue"};
    model.addAttribute("colors", colors);
    return "predefined-u-object-arrays";
}
predefined-u-object-arrays.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#arrays</h1>  
    <h4>Array: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#arrays.isEmpty(colors)</h4>
    <span th:utext="${#arrays.isEmpty(colors)}"></span>
    <h4>#arrays.length(colors)</h4>
    <span th:utext="${#arrays.length(colors)}"></span>
    <h4>#arrays.contains(colors,'red')</h4>
    <span th:utext="${#arrays.contains(colors,'red')}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#lists
Die Methode für lists bieten.
@RequestMapping("/predefined-u-object-lists")
public String lists_object(Model model) {
    String[] array = new String[] {"red", "blue", "green"};
    List<String> colors = Arrays.asList(array);
    model.addAttribute("colors", colors);
    return "predefined-u-object-lists";
}
predefined-u-object-lists.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#lists</h1>  
    <h4>List: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#lists.sort(colors)</h4>
    <ul>
        <li th:each="color : ${#lists.sort(colors)}"
            th:utext="${color}"></li>
    </ul>
    <h4>#lists.isEmpty(colors)</h4>
    <span th:utext="${#lists.isEmpty(colors)}"></span>
    <h4>#lists.size(colors)</h4>
    <span th:utext="${#lists.size(colors)}"></span>
    <h4>#lists.contains(colors,'red')</h4>
    <span th:utext="${#lists.contains(colors,'red')}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#sets
Die Methode für sets bieten.
@RequestMapping("/predefined-u-object-sets")
public String sets_object(Model model) {
    Set<String> colors = new HashSet<String>();
    colors.add("red");
    colors.add("blue");
    colors.add("green");
    model.addAttribute("colors", colors);
    return "predefined-u-object-sets";
}
predefined-u-object-sets.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#sets</h1>  
    <h4>List: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#sets.isEmpty(colors)</h4>
    <span th:utext="${#sets.isEmpty(colors)}"></span>
    <h4>#sets.size(colors)</h4>
    <span th:utext="${#sets.size(colors)}"></span>
    <h4>#sets.contains(colors,'red')</h4>
    <span th:utext="${#sets.contains(colors,'red')}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#maps
Die Methode für maps bieten.
@RequestMapping("/predefined-u-object-maps")
public String maps_object(Model model) {
    Map<String,String> contacts = new HashMap<String,String>();
    contacts.put("111 222","Tom");
    contacts.put("111 333","Jerry");
    contacts.put("111 444","Donald");
    model.addAttribute("contacts", contacts);
    return "predefined-u-object-maps";
}
predefined-u-object-maps.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#maps</h1>  
    <h4>Map: contacts</h4>
    <h4>#maps.isEmpty(contacts)</h4>
    <span th:utext="${#maps.isEmpty(contacts)}"></span>
    <h4>#maps.size(contacts)</h4>
    <span th:utext="${#maps.size(contacts)}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#aggregates
Die Methode zur Berechnung der Summe, Durchschnitt.. in einer Kollektion oder ein Array bieten.
#aggregates
@RequestMapping("/predefined-u-object-aggregates")
public String aggregates_object(Model model) {
    double[] salaries = new double[] {100, 200, 500};
    model.addAttribute("salaries", salaries);
    return "predefined-u-object-aggregates";
}
predefined-u-object-aggregates.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#aggregates</h1>  
    <h4>Array: salaries</h4>
    <ul>
        <li th:each="salary : ${salaries}"
            th:utext="${salary}"></li>
    </ul>
    <h4>#aggregates.avg(salaries)</h4>
    <span th:utext="${#aggregates.avg(salaries)}"></span>
  
    <h4>#aggregates.sum(salaries)</h4>
    <span th:utext="${#aggregates.sum(salaries)}"></span>
</body>
</html>
#ids