spring boot thymeleaf的使用

thymeleaf用法详解

1.    Thymeleaf简介à摘自官网

Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎,能够处理HTMLXMLJavaScriptCSS甚至纯文本。

Thymeleaf的主要目标是提供一个优雅和高度可维护的创建模板的方式。为了实现这一点,它建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型。这改善了设计的沟通,弥合了设计和开发团队之间的差距。

Thymeleaf也从一开始就设计了Web标准 -特别是HTML5 -允许您创建完全验证的模板

2.    Thymeleaf支持的模版

开箱即用的Thymeleaf可让您处理六种模板,每种模板称为模板模式:

有两种标记模板模式(HTMLXML),三个文本模板模式(TEXTJAVASCRIPTCSS)和无操作模板模式(RAW

·        HTML

·        XML

·        TEXT

·        JAVASCRIPT

·        CSS

·        RAW

3.    Thymeleaf优点

浏览器不仅可以正确显示这些信息,而且还可以(可选地)在浏览器中静态打开原型时显示的值(可选地)指定一个值属性(在这种情况下为“JamesCarrot”),将由${user.name}模板处理过程中的评估结果代替。

这有助于您的设计师和开发人员处理相同的模板文件,并减少将静态原型转换为工作模板文件所需的工作量。这样做的功能是称为自然模板的功能

4.    Thymeleaf使用详解

4.1 读取外部属性文件中的文本,官网称之为:外部化文本

Thymeleaf中的外部化文本的位置是完全可配置的,它将取决于org.thymeleaf.messageresolver.IMessageResolver所使用的具体实现。通常,.properties将使用基于文件的实现,但是如果我们想要从数据库获取消息,我们可以创建自己的实现,标准消息解析器org.thymeleaf.messageresolver.StandardMessageResolver

标准消息解析器希望classpath:/templates/home.html在同一文件夹中的属性文件中找到与模板相同名称的消息,如:

classpath:/templates/home_en.properties 英文文本。

classpath:/templates/home_es.properties 用于西班牙语文本。

classpath:/templates/home_pt_BR.properties 用于葡萄牙语(巴西)语言文本。

classpath:/templates/home.properties 对于默认文本(如果语言环境不匹配)。

而我们采用的是springbootspring采用的默认区域解析器AcceptHeaderLocaleResolver,根据requestheader中的accept-language值来解析locale,并且是不可变的。那么想要实现国际化,就要使用SessionLocaleResolver或者CookieLocaleResolver。正如类的名字所示,是按sessioncookie中储存的locale值来解析locale

4.2   标准表达式语法介绍

·        简单表达式

o   可变表达式: ${...}

o   选择变量表达式: *{...}

o   消息表达式: #{...}

o   链接网址表达式: @{...}

o   片段表达式: ~{...}

·        字面

o   文本文字:'one text''Another one!'...

o   号码文字:0343.012.3...

o   布尔文字:truefalse

o   空字面: null

o   文字标记:onesometextmain...

·        文字操作:

o   字符串连接: +

o   文字替代: |The nameis ${name}|

·        算术运算:

o   二元运算符:+-*/%

o   减号(一元运算符): -

·        布尔运算:

o   二元运算符:andor

o   布尔否定(一元运算符): !not

·        比较和平等:

o   比较:><>=<=gtltgele

o   平等运营商:==!=eqne

·        条件运算符:

o   IF-THEN (if) ?(then)

o   IF-THEN-ELSE (if) ?(then) : (else)

o   默认: (value) ?:(defaultvalue)

·        特殊令牌:

o   无操作: _

所有这些功能可以组合和嵌套:

'User is of type' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

 

4.3   表达式基本对象

·        #ctx:上下文对象。

·        #vars: 上下文变量。

·        #locale:上下文区域设置。

·        #request:(仅在Web上下文中)HttpServletRequest对象。

·        #response:(仅在Web上下文中)HttpServletResponse对象。

·        #session:(仅在Web上下文中)HttpSession对象。

·        #servletContext:(仅在Web上下文中)ServletContext对象。

使用方式如下:

/*
 * ======================================================================
 * 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}
${#locale}
/*
 *param:用于检索请求参数。${param.foo}是一个请求参数String[]的值foo,所以${param.foo[0]}通常用于获取第一个值
 * ============================================================================
 * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap
 * ============================================================================
 */

${param.foo}              // Retrieves a String[] with the values of request parameter 'foo'
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}

/*
 *会话:用于检索会话属性。
 * ======================================================================
 * See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap
 * ======================================================================
 */

${session.foo}                 // Retrieves the session atttribute 'foo'
${session.size()}
${session.isEmpty()}
${session.containsKey('foo')}

/*
 *应用程序:用于检索应用程序/ servlet上下文属性。
 * =============================================================================
 * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap
 * =============================================================================
 */

${application.foo}              // Retrieves the ServletContext atttribute 'foo'
${application.size()}
${application.isEmpty()}
${application.containsKey('foo')}


/*
 *#request:直接访问javax.servlet.http.HttpServletRequest与当前请求相关联的对象。
 */
 
 ${#request.getAttribute('foo')}
${#request.getParameter('foo')}
${#request.getContextPath()}
${#request.getRequestName()}

/*
 *#session:直接访问javax.servlet.http.HttpSession与当前请求相关联的对象。
 *${#session.getAttribute('foo')}
 */
 
 ${#session.getAttribute('foo')}
${#session.id}
${#session.lastAccessedTime}

/*
 *#servletContext:直接访问javax.servlet.ServletContext与当前请求相关联的对象。
 */
 
 ${#servletContext.getAttribute('foo')}
${#servletContext.contextPath}

4.4 表达式内置对象

 

·        #execInfo:有关正在处理的模板的信息。

·        #messages:在变量表达式中获取外部化消息的方法,与使用#{...}语法获得的方式相同。

·        #uris:转义URL / URI部分的方法

·        #conversions:执行配置的转换服务(如果有)的方法。

·        #datesjava.util.Date对象的方法:格式化,组件提取等

·        #calendars:类似于#dates但是java.util.Calendar对象。

·        #numbers:用于格式化数字对象的方法。

·        #stringsString对象的方法:containsstartsWithprepending / appending

·        #objects:一般对象的方法。

·        #bools:布尔评估的方法。

·        #arrays:数组方法。

·        #lists:列表的方法。

·        #sets:集合的方法。

·        #maps:地图方法。

·        #aggregates:在数组或集合上创建聚合的方法。

·        #ids:处理可能重复的id属性的方法(例如,作为迭代的结果)。

使用方式如下:

/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.ExecutionInfo
 * ======================================================================
 */

/*
 * Return the name and mode of the 'leaf' template. This means the template
 * from where the events being processed were parsed. So if this piece of
 * code is not in the root template "A" but on a fragment being inserted
 * into "A" from another template called "B", this will return "B" as a
 * name, and B's mode as template mode.
 */
${#execInfo.templateName}
${#execInfo.templateMode}

/*
 * Return the name and mode of the 'root' template. This means the template
 * that the template engine was originally asked to process. So if this
 * piece of code is not in the root template "A" but on a fragment being
 * inserted into "A" from another template called "B", this will still 
 * return "A" and A's template mode.
 */
${#execInfo.processedTemplateName}
${#execInfo.processedTemplateMode}

/*
 *#execInfo:表达式对象,提供有关在Thymeleaf标准表达式中处理的模板的有用信息。
 * Return the stacks (actually, List
    
    
     
      or List
     
     
      
      ) of
 * templates being processed. The first element will be the 
 * 'processedTemplate' (the root one), the last one will be the 'leaf'
 * template, and in the middle all the fragments inserted in nested
 * manner to reach the leaf from the root will appear.
 */
${#execInfo.templateNames}
${#execInfo.templateModes}

/*
 * Return the stack of templates being processed similarly (and in the
 * same order) to 'templateNames' and 'templateModes', but returning
 * a List
      
      
       
        with the full template metadata.
 */
${#execInfo.templateStack}
      
      
     
     
    
    
/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Messages
 * ======================================================================
 */

/*
 * Obtain externalized messages. Can receive a single key, a key plus arguments,
 * or an array/list/set of keys (in which case it will return an array/list/set of 
 * externalized messages).
 * If a message is not found, a default message (like '??msgKey??') is returned.
 */
${#messages.msg('msgKey')}
${#messages.msg('msgKey', param1)}
${#messages.msg('msgKey', param1, param2)}
${#messages.msg('msgKey', param1, param2, param3)}
${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsg(messageKeyArray)}
${#messages.listMsg(messageKeyList)}
${#messages.setMsg(messageKeySet)}

/*
 *#messages:用于在变量表达式中获取外部化消息的实用方法,与使用#{...}语法获得的方式相同。
 * Obtain externalized messages or null. Null is returned instead of a default
 * message if a message for the specified key is not found.
 */
${#messages.msgOrNull('msgKey')}
${#messages.msgOrNull('msgKey', param1)}
${#messages.msgOrNull('msgKey', param1, param2)}
${#messages.msgOrNull('msgKey', param1, param2, param3)}
${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsgOrNull(messageKeyArray)}
${#messages.listMsgOrNull(messageKeyList)}
${#messages.setMsgOrNull(messageKeySet)}
/*
 *#uris:用于在Thymeleaf标准表达式中执行URI / URL操作(尤其是转义/取消转义)的实用程序对象。
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Uris
 * ======================================================================
 */

/*
 * Escape/Unescape as a URI/URL path
 */
${#uris.escapePath(uri)}
${#uris.escapePath(uri, encoding)}
${#uris.unescapePath(uri)}
${#uris.unescapePath(uri, encoding)}

/*
 * Escape/Unescape as a URI/URL path segment (between '/' symbols)
 */
${#uris.escapePathSegment(uri)}
${#uris.escapePathSegment(uri, encoding)}
${#uris.unescapePathSegment(uri)}
${#uris.unescapePathSegment(uri, encoding)}

/*
 * Escape/Unescape as a Fragment Identifier (#frag)
 */
${#uris.escapeFragmentId(uri)}
${#uris.escapeFragmentId(uri, encoding)}
${#uris.unescapeFragmentId(uri)}
${#uris.unescapeFragmentId(uri, encoding)}

/*
 * Escape/Unescape as a Query Parameter (?var=value)
 */
${#uris.escapeQueryParam(uri)}
${#uris.escapeQueryParam(uri, encoding)}
${#uris.unescapeQueryParam(uri)}
${#uris.unescapeQueryParam(uri, encoding)}
/*
 *#conversions:允许在模板任意位置执行转换服务的实用程序对象:
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Conversions
 * ======================================================================
 */

/*
 * Execute the desired conversion of the 'object' value into the
 * specified class.
 */
${#conversions.convert(object, 'java.util.TimeZone')}
${#conversions.convert(object, targetClass)}
/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Calendars
 * ======================================================================
 */

/*
 * Format calendar with the standard locale format
 * Also works with arrays, lists or sets
 */
${#calendars.format(cal)}
${#calendars.arrayFormat(calArray)}
${#calendars.listFormat(calList)}
${#calendars.setFormat(calSet)}

/*
 * Format calendar with the ISO8601 format
 * Also works with arrays, lists or sets
 */
${#calendars.formatISO(cal)}
${#calendars.arrayFormatISO(calArray)}
${#calendars.listFormatISO(calList)}
${#calendars.setFormatISO(calSet)}

/*
 * Format calendar with the specified pattern
 * Also works with arrays, lists or sets
 */
${#calendars.format(cal, 'dd/MMM/yyyy HH:mm')}
${#calendars.arrayFormat(calArray, 'dd/MMM/yyyy HH:mm')}
${#calendars.listFormat(calList, 'dd/MMM/yyyy HH:mm')}
${#calendars.setFormat(calSet, 'dd/MMM/yyyy HH:mm')}

/*
 * Obtain calendar properties
 * Also works with arrays, lists or sets
 */
${#calendars.day(date)}                // also arrayDay(...), listDay(...), etc.
${#calendars.month(date)}              // also arrayMonth(...), listMonth(...), etc.
${#calendars.monthName(date)}          // also arrayMonthName(...), listMonthName(...), etc.
${#calendars.monthNameShort(date)}     // also arrayMonthNameShort(...), listMonthNameShort(...), etc.
${#calendars.year(date)}               // also arrayYear(...), listYear(...), etc.
${#calendars.dayOfWeek(date)}          // also arrayDayOfWeek(...), listDayOfWeek(...), etc.
${#calendars.dayOfWeekName(date)}      // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc.
${#calendars.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc.
${#calendars.hour(date)}               // also arrayHour(...), listHour(...), etc.
${#calendars.minute(date)}             // also arrayMinute(...), listMinute(...), etc.
${#calendars.second(date)}             // also arraySecond(...), listSecond(...), etc.
${#calendars.millisecond(date)}        // also arrayMillisecond(...), listMillisecond(...), etc.

/*
 * Create calendar (java.util.Calendar) objects from its components
 */
${#calendars.create(year,month,day)}
${#calendars.create(year,month,day,hour,minute)}
${#calendars.create(year,month,day,hour,minute,second)}
${#calendars.create(year,month,day,hour,minute,second,millisecond)}

${#calendars.createForTimeZone(year,month,day,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)}

/*
 * Create a calendar (java.util.Calendar) object for the current date and time
 */
${#calendars.createNow()}

${#calendars.createNowForTimeZone()}

/*
 * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00)
 */
${#calendars.createToday()}

${#calendars.createTodayForTimeZone()}
/*
 *#dates:java.util.Date对象的实用程序方法:
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Dates
 * ======================================================================
 */

/*
 * Format date with the standard locale format
 * Also works with arrays, lists or sets
 */
${#dates.format(date)}
${#dates.arrayFormat(datesArray)}
${#dates.listFormat(datesList)}
${#dates.setFormat(datesSet)}

/*
 * Format date with the ISO8601 format
 * Also works with arrays, lists or sets
 */
${#dates.formatISO(date)}
${#dates.arrayFormatISO(datesArray)}
${#dates.listFormatISO(datesList)}
${#dates.setFormatISO(datesSet)}

/*
 * Format date with the specified pattern
 * Also works with arrays, lists or sets
 */
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}

/*
 * Obtain date properties
 * Also works with arrays, lists or sets
 */
${#dates.day(date)}                    // also arrayDay(...), listDay(...), etc.
${#dates.month(date)}                  // also arrayMonth(...), listMonth(...), etc.
${#dates.monthName(date)}              // also arrayMonthName(...), listMonthName(...), etc.
${#dates.monthNameShort(date)}         // also arrayMonthNameShort(...), listMonthNameShort(...), etc.
${#dates.year(date)}                   // also arrayYear(...), listYear(...), etc.
${#dates.dayOfWeek(date)}              // also arrayDayOfWeek(...), listDayOfWeek(...), etc.
${#dates.dayOfWeekName(date)}          // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc.
${#dates.dayOfWeekNameShort(date)}     // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc.
${#dates.hour(date)}                   // also arrayHour(...), listHour(...), etc.
${#dates.minute(date)}                 // also arrayMinute(...), listMinute(...), etc.
${#dates.second(date)}                 // also arraySecond(...), listSecond(...), etc.
${#dates.millisecond(date)}            // also arrayMillisecond(...), listMillisecond(...), etc.

/*
 * Create date (java.util.Date) objects from its components
 */
${#dates.create(year,month,day)}
${#dates.create(year,month,day,hour,minute)}
${#dates.create(year,month,day,hour,minute,second)}
${#dates.create(year,month,day,hour,minute,second,millisecond)}

/*
 * Create a date (java.util.Date) object for the current date and time
 */
${#dates.createNow()}

${#dates.createNowForTimeZone()}

/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}

${#dates.createTodayForTimeZone()}
/*#numbers:数字对象的实用程序方法:*/
/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Numbers
 * ======================================================================
 */

/*
 * ==========================
 * Formatting integer numbers
 * ==========================
 */

/* 
 * Set minimum integer digits.
 * Also works with arrays, lists or sets
 */
${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#numbers.listFormatInteger(numList,3)}
${#numbers.setFormatInteger(numSet,3)}


/* 
 * Set minimum integer digits and thousands separator: 
 * 'POINT', 'COMMA', 'WHITESPACE', 'NONE' or 'DEFAULT' (by locale).
 * Also works with arrays, lists or sets
 */
${#numbers.formatInteger(num,3,'POINT')}
${#numbers.arrayFormatInteger(numArray,3,'POINT')}
${#numbers.listFormatInteger(numList,3,'POINT')}
${#numbers.setFormatInteger(numSet,3,'POINT')}


/*
 * ==========================
 * Formatting decimal numbers
 * ==========================
 */

/*
 * Set minimum integer digits and (exact) decimal digits.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,2)}
${#numbers.arrayFormatDecimal(numArray,3,2)}
${#numbers.listFormatDecimal(numList,3,2)}
${#numbers.setFormatDecimal(numSet,3,2)}

/*
 * Set minimum integer digits and (exact) decimal digits, and also decimal separator.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,2,'COMMA')}

/*
 * Set minimum integer digits and (exact) decimal digits, and also thousands and 
 * decimal separator.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,'POINT',2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,'POINT',2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,'POINT',2,'COMMA')}


/* 
 * =====================
 * Formatting currencies
 * =====================
 */

${#numbers.formatCurrency(num)}
${#numbers.arrayFormatCurrency(numArray)}
${#numbers.listFormatCurrency(numList)}
${#numbers.setFormatCurrency(numSet)}


/* 
 * ======================
 * Formatting percentages
 * ======================
 */

${#numbers.formatPercent(num)}
${#numbers.arrayFormatPercent(numArray)}
${#numbers.listFormatPercent(numList)}
${#numbers.setFormatPercent(numSet)}

/* 
 * Set minimum integer digits and (exact) decimal digits.
 */
${#numbers.formatPercent(num, 3, 2)}
${#numbers.arrayFormatPercent(numArray, 3, 2)}
${#numbers.listFormatPercent(numList, 3, 2)}
${#numbers.setFormatPercent(numSet, 3, 2)}


/*
 * ===============
 * Utility methods
 * ===============
 */

/*
 * Create a sequence (array) of integer numbers going
 * from x to y
 */
${#numbers.sequence(from,to)}
${#numbers.sequence(from,to,step)}
/*#strings:String对象的实用程序方法:*/
/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Strings
 * ======================================================================
 */

/*
 * Null-safe toString()
 */
${#strings.toString(obj)}                           // also array*, list* and set*

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}

/*
 * Perform an 'isEmpty()' check on a string and return it if false, defaulting to
 * another specified string if true.
 * Also works with arrays, lists or sets
 */
${#strings.defaultString(text,default)}
${#strings.arrayDefaultString(textArr,default)}
${#strings.listDefaultString(textList,default)}
${#strings.setDefaultString(textSet,default)}

/*
 * Check whether a fragment is contained in a String
 * Also works with arrays, lists or sets
 */
${#strings.contains(name,'ez')}                     // also array*, list* and set*
${#strings.containsIgnoreCase(name,'ez')}           // also array*, list* and set*

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

/*
 * Substring-related operations
 * Also works with arrays, lists or sets
 */
${#strings.indexOf(name,frag)}                      // also array*, list* and set*
${#strings.substring(name,3,5)}                     // also array*, list* and set*
${#strings.substringAfter(name,prefix)}             // also array*, list* and set*
${#strings.substringBefore(name,suffix)}            // also array*, list* and set*
${#strings.replace(name,'las','ler')}               // also array*, list* and set*

/*
 * Append and prepend
 * Also works with arrays, lists or sets
 */
${#strings.prepend(str,prefix)}                     // also array*, list* and set*
${#strings.append(str,suffix)}                      // also array*, list* and set*

/*
 * Change case
 * Also works with arrays, lists or sets
 */
${#strings.toUpperCase(name)}                       // also array*, list* and set*
${#strings.toLowerCase(name)}                       // also array*, list* and set*

/*
 * Split and join
 */
${#strings.arrayJoin(namesArray,',')}
${#strings.listJoin(namesList,',')}
${#strings.setJoin(namesSet,',')}
${#strings.arraySplit(namesStr,',')}                // returns String[]
${#strings.listSplit(namesStr,',')}                 // returns List
    
    
     
     
${#strings.setSplit(namesStr,',')}                  // returns Set
     
     
      
      

/*
 * Trim
 * Also works with arrays, lists or sets
 */
${#strings.trim(str)}                               // also array*, list* and set*

/*
 * Compute length
 * Also works with arrays, lists or sets
 */
${#strings.length(str)}                             // also array*, list* and set*

/*
 * Abbreviate text making it have a maximum size of n. If text is bigger, it
 * will be clipped and finished in "..."
 * Also works with arrays, lists or sets
 */
${#strings.abbreviate(str,10)}                      // also array*, list* and set*

/*
 * Convert the first character to upper-case (and vice-versa)
 */
${#strings.capitalize(str)}                         // also array*, list* and set*
${#strings.unCapitalize(str)}                       // also array*, list* and set*

/*
 * Convert the first character of every word to upper-case
 */
${#strings.capitalizeWords(str)}                    // also array*, list* and set*
${#strings.capitalizeWords(str,delimiters)}         // also array*, list* and set*

/*
 * Escape the string
 */
${#strings.escapeXml(str)}                          // also array*, list* and set*
${#strings.escapeJava(str)}                         // also array*, list* and set*
${#strings.escapeJavaScript(str)}                   // also array*, list* and set*
${#strings.unescapeJava(str)}                       // also array*, list* and set*
${#strings.unescapeJavaScript(str)}                 // also array*, list* and set*

/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(first, second)}
${#strings.equalsIgnoreCase(first, second)}
${#strings.concat(values...)}
${#strings.concatReplaceNulls(nullValue, values...)}

/*
 * Random
 */
${#strings.randomAlphanumeric(count)}
     
     
    
    
/*
 *#objects:一般对象的实用程序方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Objects
 * ======================================================================
 */

/*
 * Return obj if it is not null, and default otherwise
 * Also works with arrays, lists or sets
 */
${#objects.nullSafe(obj,default)}
${#objects.arrayNullSafe(objArray,default)}
${#objects.listNullSafe(objList,default)}
${#objects.setNullSafe(objSet,default)}
/*
 *#bools:布尔评估的实用程序方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Bools
 * ======================================================================
 */

/*
 * Evaluate a condition in the same way that it would be evaluated in a th:if tag
 * (see conditional evaluation chapter afterwards).
 * Also works with arrays, lists or sets
 */
${#bools.isTrue(obj)}
${#bools.arrayIsTrue(objArray)}
${#bools.listIsTrue(objList)}
${#bools.setIsTrue(objSet)}

/*
 * Evaluate with negation
 * Also works with arrays, lists or sets
 */
${#bools.isFalse(cond)}
${#bools.arrayIsFalse(condArray)}
${#bools.listIsFalse(condList)}
${#bools.setIsFalse(condSet)}

/*
 * Evaluate and apply AND operator
 * Receive an array, a list or a set as parameter
 */
${#bools.arrayAnd(condArray)}
${#bools.listAnd(condList)}
${#bools.setAnd(condSet)}

/*
 * Evaluate and apply OR operator
 * Receive an array, a list or a set as parameter
 */
${#bools.arrayOr(condArray)}
${#bools.listOr(condList)}
${#bools.setOr(condSet)}
/*
 *#arrays:数组的实用方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Arrays
 * ======================================================================
 */

/*
 * Converts to array, trying to infer array component class.
 * Note that if resulting array is empty, or if the elements
 * of the target object are not all of the same class,
 * this method will return Object[].
 */
${#arrays.toArray(object)}

/*
 * Convert to arrays of the specified component class.
 */
${#arrays.toStringArray(object)}
${#arrays.toIntegerArray(object)}
${#arrays.toLongArray(object)}
${#arrays.toDoubleArray(object)}
${#arrays.toFloatArray(object)}
${#arrays.toBooleanArray(object)}

/*
 * Compute length
 */
${#arrays.length(array)}

/*
 * Check whether array is empty
 */
${#arrays.isEmpty(array)}

/*
 * Check if element or elements are contained in array
 */
${#arrays.contains(array, element)}
${#arrays.containsAll(array, elements)}
/*
 *#lists:列表的实用程序方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Lists
 * ======================================================================
 */

/*
 * Converts to list
 */
${#lists.toList(object)}

/*
 * Compute size
 */
${#lists.size(list)}

/*
 * Check whether list is empty
 */
${#lists.isEmpty(list)}

/*
 * Check if element or elements are contained in list
 */
${#lists.contains(list, element)}
${#lists.containsAll(list, elements)}

/*
 * Sort a copy of the given list. The members of the list must implement
 * comparable or you must define a comparator.
 */
${#lists.sort(list)}
${#lists.sort(list, comparator)}
/*
 *#sets:集合的实用方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Sets
 * ======================================================================
 */

/*
 * Converts to set
 */
${#sets.toSet(object)}

/*
 * Compute size
 */
${#sets.size(set)}

/*
 * Check whether set is empty
 */
${#sets.isEmpty(set)}

/*
 * Check if element or elements are contained in set
 */
${#sets.contains(set, element)}
${#sets.containsAll(set, elements)}
/*
 *#maps:地图的实用方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Maps
 * ======================================================================
 */

/*
 * Compute size
 */
${#maps.size(map)}

/*
 * Check whether map is empty
 */
${#maps.isEmpty(map)}

/*
 * Check if key/s or value/s are contained in maps
 */
${#maps.containsKey(map, key)}
${#maps.containsAllKeys(map, keys)}
${#maps.containsValue(map, value)}
${#maps.containsAllValues(map, value)}
/*
 *#aggregates:在数组或集合上创建聚合的实用方法
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Aggregates
 * ======================================================================
 */

/*
 * Compute sum. Returns null if array or collection is empty
 */
${#aggregates.sum(array)}
${#aggregates.sum(collection)}

/*
 * Compute average. Returns null if array or collection is empty
 */
${#aggregates.avg(array)}
${#aggregates.avg(collection)}
/*
 *#ids:处理id可能重复的属性的实用方法(例如,作为迭代的结果)。
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Ids
 * ======================================================================
 */

/*
 * Normally used in th:id attributes, for appending a counter to the id attribute value
 * so that it remains unique even when involved in an iteration process.
 */
${#ids.seq('someId')}

/*
 * Normally used in th:for attributes in 

4.5 选择表达式(星号语法)

不仅可以将变量表达式写为${...},也可以写为*{...}

有一个重要的区别:星号语法评估所选对象而不是整个上下文的表达式。也就是说,只要没有选定的对象,美元和星号语法就会完全相同。

什么是选定对象?使用th:object属性的表达式的结果。我们在用户个人资料(userprofile.html)页面中使用一个:

  <divth:object="${session.user}">

    <p>Name: <spanth:text="*{firstName}">Sebastian</span>.</p>

    <p>Surname: <spanth:text="*{lastName}">Pepper</span>.</p>

    <p>Nationality: <spanth:text="*{nationality}">Saturn</span>.</p>

  </div>

这完全相当于:

<div>

  <p>Name: <spanth:text="${session.user.firstName}">Sebastian</span>.</p>

  <p>Surname: <spanth:text="${session.user.lastName}">Pepper</span>.</p>

  <p>Nationality: <spanth:text="${session.user.nationality}">Saturn</span>.</p>

</div>

当然,美元和星号的语法可以混合使用:

<divth:object="${session.user}">

  <p>Name: <spanth:text="*{firstName}">Sebastian</span>.</p>

  <p>Surname: <spanth:text="${session.user.lastName}">Pepper</span>.</p>

  <p>Nationality: <spanth:text="*{nationality}">Saturn</span>.</p>

</div>

当对象选择到位时,所选对象也将作为#object表达式变量使用美元表达式:

<divth:object="${session.user}">

  <p>Name: <spanth:text="${#object.firstName}">Sebastian</span>.</p>

  <p>Surname: <spanth:text="${session.user.lastName}">Pepper</span>.</p>

  <p>Nationality: <spanth:text="*{nationality}">Saturn</span>.</p>

</div>

如上所述,如果没有执行对象选择,则美元和星号语法是等效的。

<div>

  <p>Name: <spanth:text="*{session.user.name}">Sebastian</span>.</p>

  <p>Surname: <spanth:text="*{session.user.surname}">Pepper</span>.</p>

  <p>Nationality: <spanth:text="*{session.user.nationality}">Saturn</span>.</p>

</div>

 

4.6 URL链接

@{...}

<!-- Willproduce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting)-->

<ahref="details.html"

   th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

 

<!-- Willproduce '/gtvg/order/details?orderId=3' (plus rewriting) -->

<ahref="details.html"th:href="@{/order/details(orderId=${o.id})}">view</a>

 

<!-- Willproduce '/gtvg/order/3/details' (plus rewriting) -->

<ahref="details.html"th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

·        如果需要几个参数,这些参数将以逗号分隔: @{/order/process(execId=${execId},execType='FAST')}

 

5.实际例子,代码如下,分为server与web


pom引入




 




    
   
   
    登录页面


read from properties

username: password:

   
   
© 2016

 



    
        
   
   
        欢迎界面
    
    
        Welcome to the index,hello 

body!


----- read from properties ----------

read from properties


变量替换:

变量替换


字符串部分替换-写法1:字符串部分替换-写法1
字符串部分替换-写法2:字符串部分替换-写法2
-----url用法------
相对路径-->通常不推荐这样写登录页面
绝对路径登录页面
绝对路径欢迎页面
url带有一个参数欢迎页面
url带有多个参数欢迎页面
url路径中带有参数-->restful风格this is abc444
运算符用法1this is bcd
运算符用法2this is true
运算符用法3this is false

-----循环用法1 非空集合------
INDEXNAMEUSERNAMEPASSWORD
indexOnions111***

-----循环用法2 空集合,判断为空则整体表格不显示------
NAMEUSERNAMEPASSWORD
Onions111***

-----switch 用法,相当于jstl的choose when 默认属性default可以用*表示:------

User is an administrator

User`s username equals the name

User is some other thing


-----Utility对象(内置于Context中):------ -----#dates:------


-----#strings:------


-----ajax 动态获取数据:------
INDEXNAMEUSERNAMEPASSWORD
indexOnions111***

-----页面布局引用:------
<script th:src="@{/webjars/jquery/3.2.1/jquery.min.js}"></script> <script th:inline="javascript" th:src="@{/js/index.js}"></script>

 

 

 

 

 注明:1.参考资料:http://www.thymeleaf.org/

       2.th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

             3.iterStat称作状态变量,属性有:

  • index:当前迭代对象的index(从0开始计算)
  • count: 当前迭代对象的index(从1开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个

      4.资源文件的约定目录结构 

Maven的资源文件目录:/src/java/resources 
spring-boot项目静态文件目录:/src/java/resources/static 
spring-boot项目模板文件目录:/src/java/resources/templates 
spring-boot静态首页的支持,即index.html放在以下目录结构会直接映射到应用的根目录下
5. 在表达式中的值可以与进行比较 > < >= <= 符号,以及 == != 运营商可以被用来检查是否相等(或缺乏)。需要注意的是XML建立了 < > 符号不应该在属性值被使用,并且因此他们应该被取代 &lt; &gt;
6. src/main/webapp 如果您的应用程序将被打包为jar,请不要使用该目录。虽然这个目录是一个通用的标准,但 它只 适用于战争包装,如果生成一个jar,它将被绝大多数构建工具忽略( 默认情况下,Spring Boot将从类路径或根目录中的 /static (  /public /resources /META-INF/resources )目录中提供静态内容 ServletContext 。它使用 ResourceHttpRequestHandler 从Spring MVC,所以你可以通过添加自己 WebMvcConfigurerAdapter 和覆盖该  addResourceHandlers 方法来修改这种行为。

7. 当您使用默认配置的其中一个模板引擎时,您的模板将自动从中提取 src/main/resources/templates
8. 模版文件位置可自行配置,如下图所示:


附录:
给属性赋值:这些属性有很多属性,每个都针对特定的HTML5属性:
th:abbr th:accept th:accept-charset
th:accesskey th:action th:align
th:alt th:archive th:audio
th:autocomplete th:axis th:background
th:bgcolor th:border th:cellpadding
th:cellspacing th:challenge th:charset
th:cite th:class th:classid
th:codebase th:codetype th:cols
th:colspan th:compact th:content
th:contenteditable th:contextmenu th:data
th:datetime th:dir th:draggable
th:dropzone th:enctype th:for
th:form th:formaction th:formenctype
th:formmethod th:formtarget th:fragment
th:frame th:frameborder th:headers
th:height th:high th:href
th:hreflang th:hspace th:http-equiv
th:icon th:id th:inline
th:keytype th:kind th:label
th:lang th:list th:longdesc
th:low th:manifest th:marginheight
th:marginwidth th:max th:maxlength
th:media th:method th:min
th:name th:onabort th:onafterprint
th:onbeforeprint th:onbeforeunload th:onblur
th:oncanplay th:oncanplaythrough th:onchange
th:onclick th:oncontextmenu th:ondblclick
th:ondrag th:ondragend th:ondragenter
th:ondragleave th:ondragover th:ondragstart
th:ondrop th:ondurationchange th:onemptied
th:onended th:onerror th:onfocus
th:onformchange th:onforminput th:onhashchange
th:oninput th:oninvalid th:onkeydown
th:onkeypress th:onkeyup th:onload
th:onloadeddata th:onloadedmetadata th:onloadstart
th:onmessage th:onmousedown th:onmousemove
th:onmouseout th:onmouseover th:onmouseup
th:onmousewheel th:onoffline th:ononline
th:onpause th:onplay th:onplaying
th:onpopstate th:onprogress th:onratechange
th:onreadystatechange th:onredo th:onreset
th:onresize th:onscroll th:onseeked
th:onseeking th:onselect th:onshow
th:onstalled th:onstorage th:onsubmit
th:onsuspend th:ontimeupdate th:onundo
th:onunload th:onvolumechange th:onwaiting
th:optimum th:pattern th:placeholder
th:poster th:preload th:radiogroup
th:rel th:rev th:rows
th:rowspan th:rules th:sandbox
th:scheme th:scope th:scrolling
th:size th:sizes th:span
th:spellcheck th:src th:srclang
th:standby th:start th:step
th:style th:summary th:tabindex
th:target th:title th:type
th:usemap th:value th:valuetype
th:vspace th:width th:wrap
th:xmlbase th:xmllang th:xmlspace
标准方言中存在以下固定值布尔属性:
th:async th:autofocus th:autoplay
th:checked th:controls th:declare
th:default th:defer th:disabled
th:formnovalidate th:hidden th:ismap
th:loop th:multiple th:novalidate
th:nowrap th:open th:pubdate
th:readonly th:required th:reversed
th:scoped th:seamless th:selected
5.6设置任何属性的值(默认属性处理器)
Thymeleaf提供了一个 默认属性处理器 ,允许我们设置 任何 属性的值,即使 th:* 在标准方言中没有为其定义特定的处理器。
所以这样的东西:
< span th:whatever =" ${user.name} ">...</ span >
将导致:
< span whatever =" John Apricot ">...</ span >


可迭代的值
java.util.List 班是不是可以用于Thymeleaf迭代onlyvalue。有一组相当完整的对象被一个属性认为 可迭代 th:each
  • 任何对象实现 java.util.Iterable
  • 任何对象实现java.util.Enumeration
  • 任何实现的对象java.util.Iterator,其值将被迭代器返回,而不需要在内存中缓存所有值。
  • 任何对象实现java.util.Map。迭代映射时,迭代变量将是类java.util.Map.Entry
  • 任何数组。
  • 任何其他对象将被视为包含对象本身的单值列表。
所以,所有的Thymeleaf属性定义一个数字优先级,它确定在标签中执行它们的顺序。这个订单是:
订购特征属性
1片段包含 th:insert
th:replace
2片段迭代 th:each
3有条件的评估 th:if
th:unless
th:switch
th:case
4局部变量定义 th:object
th:with
一般属性修改 th:attr
th:attrprepend
th:attrappend
6具体属性修改 th:value
th:href
th:src
...
7文本(标签体修改) th:text
th:utext
8片段规范 th:fragment
9片段去除 th:remove

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JAVA小男子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值